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
78 #ifdef PERL_IN_XSUB_RE
84 #include "inline_invlist.c"
85 #include "unicode_constants.h"
88 /* At least one required character in the target string is expressible only in
90 static const char* const non_utf8_target_but_utf8_required
91 = "Can't match, because target string needs to be in UTF-8\n";
94 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
95 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
99 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
102 #define STATIC static
105 /* Valid only for non-utf8 strings: avoids the reginclass
106 * call if there are no complications: i.e., if everything matchable is
107 * straight forward in the bitmap */
108 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
109 : ANYOF_BITMAP_TEST(p,*(c)))
115 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
116 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
118 #define HOPc(pos,off) \
119 (char *)(reginfo->is_utf8_target \
120 ? reghop3((U8*)pos, off, \
121 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
124 #define HOPBACKc(pos, off) \
125 (char*)(reginfo->is_utf8_target \
126 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
127 : (pos - off >= reginfo->strbeg) \
131 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
132 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
134 /* lim must be +ve. Returns NULL on overshoot */
135 #define HOPMAYBE3(pos,off,lim) \
136 (reginfo->is_utf8_target \
137 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
138 : ((U8*)pos + off <= lim) \
142 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
143 * off must be >=0; args should be vars rather than expressions */
144 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
145 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
146 : (U8*)((pos + off) > lim ? lim : (pos + off)))
148 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
149 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
151 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
153 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
154 #define NEXTCHR_IS_EOS (nextchr < 0)
156 #define SET_nextchr \
157 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
159 #define SET_locinput(p) \
164 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
166 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
167 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
168 1, 0, invlist, &flags); \
173 /* If in debug mode, we test that a known character properly matches */
175 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
178 utf8_char_in_property) \
179 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
180 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
182 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
185 utf8_char_in_property) \
186 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
189 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
190 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
192 PL_XPosix_ptrs[_CC_WORDCHAR], \
193 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
195 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
197 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_regular_begin, \
198 "_X_regular_begin", \
200 LATIN_CAPITAL_LETTER_SHARP_S_UTF8); \
201 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_extend, \
204 COMBINING_GRAVE_ACCENT_UTF8); \
207 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
208 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
210 /* for use after a quantifier and before an EXACT-like node -- japhy */
211 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
213 * NOTE that *nothing* that affects backtracking should be in here, specifically
214 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
215 * node that is in between two EXACT like nodes when ascertaining what the required
216 * "follow" character is. This should probably be moved to regex compile time
217 * although it may be done at run time beause of the REF possibility - more
218 * investigation required. -- demerphq
220 #define JUMPABLE(rn) ( \
222 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
224 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
225 OP(rn) == PLUS || OP(rn) == MINMOD || \
227 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
229 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
231 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
234 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
235 we don't need this definition. */
236 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
237 #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 )
238 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
241 /* ... so we use this as its faster. */
242 #define IS_TEXT(rn) ( OP(rn)==EXACT )
243 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
244 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
245 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
250 Search for mandatory following text node; for lookahead, the text must
251 follow but for lookbehind (rn->flags != 0) we skip to the next step.
253 #define FIND_NEXT_IMPT(rn) STMT_START { \
254 while (JUMPABLE(rn)) { \
255 const OPCODE type = OP(rn); \
256 if (type == SUSPEND || PL_regkind[type] == CURLY) \
257 rn = NEXTOPER(NEXTOPER(rn)); \
258 else if (type == PLUS) \
260 else if (type == IFMATCH) \
261 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
262 else rn += NEXT_OFF(rn); \
266 /* These constants are for finding GCB=LV and GCB=LVT in the CLUMP regnode.
267 * These are for the pre-composed Hangul syllables, which are all in a
268 * contiguous block and arranged there in such a way so as to facilitate
269 * alorithmic determination of their characteristics. As such, they don't need
270 * a swash, but can be determined by simple arithmetic. Almost all are
271 * GCB=LVT, but every 28th one is a GCB=LV */
272 #define SBASE 0xAC00 /* Start of block */
273 #define SCount 11172 /* Length of block */
276 #define SLAB_FIRST(s) (&(s)->states[0])
277 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
279 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
280 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
281 static regmatch_state * S_push_slab(pTHX);
283 #define REGCP_PAREN_ELEMS 3
284 #define REGCP_OTHER_ELEMS 3
285 #define REGCP_FRAME_ELEMS 1
286 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
287 * are needed for the regexp context stack bookkeeping. */
290 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
292 const int retval = PL_savestack_ix;
293 const int paren_elems_to_push =
294 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
295 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
296 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
298 GET_RE_DEBUG_FLAGS_DECL;
300 PERL_ARGS_ASSERT_REGCPPUSH;
302 if (paren_elems_to_push < 0)
303 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
304 (int)paren_elems_to_push, (int)maxopenparen,
305 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
307 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
308 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
309 " out of range (%lu-%ld)",
311 (unsigned long)maxopenparen,
314 SSGROW(total_elems + REGCP_FRAME_ELEMS);
317 if ((int)maxopenparen > (int)parenfloor)
318 PerlIO_printf(Perl_debug_log,
319 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
324 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
325 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
326 SSPUSHIV(rex->offs[p].end);
327 SSPUSHIV(rex->offs[p].start);
328 SSPUSHINT(rex->offs[p].start_tmp);
329 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
330 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
332 (IV)rex->offs[p].start,
333 (IV)rex->offs[p].start_tmp,
337 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
338 SSPUSHINT(maxopenparen);
339 SSPUSHINT(rex->lastparen);
340 SSPUSHINT(rex->lastcloseparen);
341 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
346 /* These are needed since we do not localize EVAL nodes: */
347 #define REGCP_SET(cp) \
349 PerlIO_printf(Perl_debug_log, \
350 " Setting an EVAL scope, savestack=%"IVdf"\n", \
351 (IV)PL_savestack_ix)); \
354 #define REGCP_UNWIND(cp) \
356 if (cp != PL_savestack_ix) \
357 PerlIO_printf(Perl_debug_log, \
358 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
359 (IV)(cp), (IV)PL_savestack_ix)); \
362 #define UNWIND_PAREN(lp, lcp) \
363 for (n = rex->lastparen; n > lp; n--) \
364 rex->offs[n].end = -1; \
365 rex->lastparen = n; \
366 rex->lastcloseparen = lcp;
370 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
374 GET_RE_DEBUG_FLAGS_DECL;
376 PERL_ARGS_ASSERT_REGCPPOP;
378 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
380 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
381 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
382 rex->lastcloseparen = SSPOPINT;
383 rex->lastparen = SSPOPINT;
384 *maxopenparen_p = SSPOPINT;
386 i -= REGCP_OTHER_ELEMS;
387 /* Now restore the parentheses context. */
389 if (i || rex->lastparen + 1 <= rex->nparens)
390 PerlIO_printf(Perl_debug_log,
391 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
396 paren = *maxopenparen_p;
397 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
399 rex->offs[paren].start_tmp = SSPOPINT;
400 rex->offs[paren].start = SSPOPIV;
402 if (paren <= rex->lastparen)
403 rex->offs[paren].end = tmps;
404 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
405 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
407 (IV)rex->offs[paren].start,
408 (IV)rex->offs[paren].start_tmp,
409 (IV)rex->offs[paren].end,
410 (paren > rex->lastparen ? "(skipped)" : ""));
415 /* It would seem that the similar code in regtry()
416 * already takes care of this, and in fact it is in
417 * a better location to since this code can #if 0-ed out
418 * but the code in regtry() is needed or otherwise tests
419 * requiring null fields (pat.t#187 and split.t#{13,14}
420 * (as of patchlevel 7877) will fail. Then again,
421 * this code seems to be necessary or otherwise
422 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
423 * --jhi updated by dapm */
424 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
425 if (i > *maxopenparen_p)
426 rex->offs[i].start = -1;
427 rex->offs[i].end = -1;
428 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
429 " \\%"UVuf": %s ..-1 undeffing\n",
431 (i > *maxopenparen_p) ? "-1" : " "
437 /* restore the parens and associated vars at savestack position ix,
438 * but without popping the stack */
441 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
443 I32 tmpix = PL_savestack_ix;
444 PL_savestack_ix = ix;
445 regcppop(rex, maxopenparen_p);
446 PL_savestack_ix = tmpix;
449 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
452 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
454 /* Returns a boolean as to whether or not 'character' is a member of the
455 * Posix character class given by 'classnum' that should be equivalent to a
456 * value in the typedef '_char_class_number'.
458 * Ideally this could be replaced by a just an array of function pointers
459 * to the C library functions that implement the macros this calls.
460 * However, to compile, the precise function signatures are required, and
461 * these may vary from platform to to platform. To avoid having to figure
462 * out what those all are on each platform, I (khw) am using this method,
463 * which adds an extra layer of function call overhead (unless the C
464 * optimizer strips it away). But we don't particularly care about
465 * performance with locales anyway. */
467 switch ((_char_class_number) classnum) {
468 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
469 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
470 case _CC_ENUM_ASCII: return isASCII_LC(character);
471 case _CC_ENUM_BLANK: return isBLANK_LC(character);
472 case _CC_ENUM_CASED: return isLOWER_LC(character)
473 || isUPPER_LC(character);
474 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
475 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
476 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
477 case _CC_ENUM_LOWER: return isLOWER_LC(character);
478 case _CC_ENUM_PRINT: return isPRINT_LC(character);
479 case _CC_ENUM_PSXSPC: return isPSXSPC_LC(character);
480 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
481 case _CC_ENUM_SPACE: return isSPACE_LC(character);
482 case _CC_ENUM_UPPER: return isUPPER_LC(character);
483 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
484 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
485 default: /* VERTSPACE should never occur in locales */
486 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
489 assert(0); /* NOTREACHED */
494 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
496 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
497 * 'character' is a member of the Posix character class given by 'classnum'
498 * that should be equivalent to a value in the typedef
499 * '_char_class_number'.
501 * This just calls isFOO_lc on the code point for the character if it is in
502 * the range 0-255. Outside that range, all characters avoid Unicode
503 * rules, ignoring any locale. So use the Unicode function if this class
504 * requires a swash, and use the Unicode macro otherwise. */
506 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
508 if (UTF8_IS_INVARIANT(*character)) {
509 return isFOO_lc(classnum, *character);
511 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
512 return isFOO_lc(classnum,
513 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
516 if (classnum < _FIRST_NON_SWASH_CC) {
518 /* Initialize the swash unless done already */
519 if (! PL_utf8_swash_ptrs[classnum]) {
520 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
521 PL_utf8_swash_ptrs[classnum] =
522 _core_swash_init("utf8",
525 PL_XPosix_ptrs[classnum], &flags);
528 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
530 TRUE /* is UTF */ ));
533 switch ((_char_class_number) classnum) {
535 case _CC_ENUM_PSXSPC: return is_XPERLSPACE_high(character);
537 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
538 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
539 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
540 default: return 0; /* Things like CNTRL are always
544 assert(0); /* NOTREACHED */
549 * pregexec and friends
552 #ifndef PERL_IN_XSUB_RE
554 - pregexec - match a regexp against a string
557 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
558 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
559 /* stringarg: the point in the string at which to begin matching */
560 /* strend: pointer to null at end of string */
561 /* strbeg: real beginning of string */
562 /* minend: end of match must be >= minend bytes after stringarg. */
563 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
564 * itself is accessed via the pointers above */
565 /* nosave: For optimizations. */
567 PERL_ARGS_ASSERT_PREGEXEC;
570 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
571 nosave ? 0 : REXEC_COPY_STR);
577 /* re_intuit_start():
579 * Based on some optimiser hints, try to find the earliest position in the
580 * string where the regex could match.
582 * rx: the regex to match against
583 * sv: the SV being matched: only used for utf8 flag; the string
584 * itself is accessed via the pointers below. Note that on
585 * something like an overloaded SV, SvPOK(sv) may be false
586 * and the string pointers may point to something unrelated to
588 * strbeg: real beginning of string
589 * strpos: the point in the string at which to begin matching
590 * strend: pointer to the byte following the last char of the string
591 * flags currently unused; set to 0
592 * data: currently unused; set to NULL
594 * The basic idea of re_intuit_start() is to use some known information
595 * about the pattern, namely:
597 * a) the longest known anchored substring (i.e. one that's at a
598 * constant offset from the beginning of the pattern; but not
599 * necessarily at a fixed offset from the beginning of the
601 * b) the longest floating substring (i.e. one that's not at a constant
602 * offset from the beginning of the pattern);
603 * c) Whether the pattern is anchored to the string; either
604 * an absolute anchor: /^../, or anchored to \n: /^.../m,
605 * or anchored to pos(): /\G/;
606 * d) A start class: a real or synthetic character class which
607 * represents which characters are legal at the start of the pattern;
609 * to either quickly reject the match, or to find the earliest position
610 * within the string at which the pattern might match, thus avoiding
611 * running the full NFA engine at those earlier locations, only to
612 * eventually fail and retry further along.
614 * Returns NULL if the pattern can't match, or returns the address within
615 * the string which is the earliest place the match could occur.
617 * The longest of the anchored and floating substrings is called 'check'
618 * and is checked first. The other is called 'other' and is checked
619 * second. The 'other' substring may not be present. For example,
621 * /(abc|xyz)ABC\d{0,3}DEFG/
625 * check substr (float) = "DEFG", offset 6..9 chars
626 * other substr (anchored) = "ABC", offset 3..3 chars
629 * Be aware that during the course of this function, sometimes 'anchored'
630 * refers to a substring being anchored relative to the start of the
631 * pattern, and sometimes to the pattern itself being anchored relative to
632 * the string. For example:
634 * /\dabc/: "abc" is anchored to the pattern;
635 * /^\dabc/: "abc" is anchored to the pattern and the string;
636 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
637 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
638 * but the pattern is anchored to the string.
642 Perl_re_intuit_start(pTHX_
645 const char * const strbeg,
649 re_scream_pos_data *data)
651 struct regexp *const prog = ReANY(rx);
652 SSize_t start_shift = prog->check_offset_min;
653 /* Should be nonnegative! */
654 SSize_t end_shift = 0;
655 /* current lowest pos in string where the regex can start matching */
656 char *rx_origin = strpos;
658 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
659 U8 other_ix = 1 - prog->substrs->check_ix;
661 char *other_last = strpos;/* latest pos 'other' substr already checked to */
662 char *check_at = NULL; /* check substr found at this pos */
663 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
664 RXi_GET_DECL(prog,progi);
665 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
666 regmatch_info *const reginfo = ®info_buf;
667 GET_RE_DEBUG_FLAGS_DECL;
669 PERL_ARGS_ASSERT_RE_INTUIT_START;
670 PERL_UNUSED_ARG(flags);
671 PERL_UNUSED_ARG(data);
673 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
674 "Intuit: trying to determine minimum start position...\n"));
676 /* for now, assume that all substr offsets are positive. If at some point
677 * in the future someone wants to do clever things with look-behind and
678 * -ve offsets, they'll need to fix up any code in this function
679 * which uses these offsets. See the thread beginning
680 * <20140113145929.GF27210@iabyn.com>
682 assert(prog->substrs->data[0].min_offset >= 0);
683 assert(prog->substrs->data[0].max_offset >= 0);
684 assert(prog->substrs->data[1].min_offset >= 0);
685 assert(prog->substrs->data[1].max_offset >= 0);
686 assert(prog->substrs->data[2].min_offset >= 0);
687 assert(prog->substrs->data[2].max_offset >= 0);
689 /* for now, assume that if both present, that the floating substring
690 * doesn't start before the anchored substring.
691 * If you break this assumption (e.g. doing better optimisations
692 * with lookahead/behind), then you'll need to audit the code in this
693 * function carefully first
696 ! ( (prog->anchored_utf8 || prog->anchored_substr)
697 && (prog->float_utf8 || prog->float_substr))
698 || (prog->float_min_offset >= prog->anchored_offset));
700 /* byte rather than char calculation for efficiency. It fails
701 * to quickly reject some cases that can't match, but will reject
702 * them later after doing full char arithmetic */
703 if (prog->minlen > strend - strpos) {
704 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
705 " String too short...\n"));
709 reginfo->is_utf8_target = cBOOL(utf8_target);
710 reginfo->info_aux = NULL;
711 reginfo->strbeg = strbeg;
712 reginfo->strend = strend;
713 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
715 /* not actually used within intuit, but zero for safety anyway */
716 reginfo->poscache_maxiter = 0;
719 if (!prog->check_utf8 && prog->check_substr)
720 to_utf8_substr(prog);
721 check = prog->check_utf8;
723 if (!prog->check_substr && prog->check_utf8) {
724 if (! to_byte_substr(prog)) {
725 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
728 check = prog->check_substr;
731 /* dump the various substring data */
732 DEBUG_OPTIMISE_MORE_r({
734 for (i=0; i<=2; i++) {
735 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
736 : prog->substrs->data[i].substr);
740 PerlIO_printf(Perl_debug_log,
741 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
742 " useful=%"IVdf" utf8=%d [%s]\n",
744 (IV)prog->substrs->data[i].min_offset,
745 (IV)prog->substrs->data[i].max_offset,
746 (IV)prog->substrs->data[i].end_shift,
753 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
755 /* ml_anch: check after \n?
757 * A note about IMPLICIT: on an un-anchored pattern beginning
758 * with /.*.../, these flags will have been added by the
760 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
761 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
763 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
764 && !(prog->intflags & PREGf_IMPLICIT);
766 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
767 /* we are only allowed to match at BOS or \G */
769 /* trivially reject if there's a BOS anchor and we're not at BOS.
771 * Note that we don't try to do a similar quick reject for
772 * \G, since generally the caller will have calculated strpos
773 * based on pos() and gofs, so the string is already correctly
774 * anchored by definition; and handling the exceptions would
775 * be too fiddly (e.g. REXEC_IGNOREPOS).
777 if ( strpos != strbeg
778 && (prog->intflags & (PREGf_ANCH_BOL|PREGf_ANCH_SBOL)))
780 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
781 " Not at start...\n"));
785 /* in the presence of an anchor, the anchored (relative to the
786 * start of the regex) substr must also be anchored relative
787 * to strpos. So quickly reject if substr isn't found there.
788 * This works for \G too, because the caller will already have
789 * subtracted gofs from pos, and gofs is the offset from the
790 * \G to the start of the regex. For example, in /.abc\Gdef/,
791 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
792 * caller will have set strpos=pos()-4; we look for the substr
793 * at position pos()-4+1, which lines up with the "a" */
795 if (prog->check_offset_min == prog->check_offset_max
796 && !(prog->intflags & PREGf_CANY_SEEN))
798 /* Substring at constant offset from beg-of-str... */
799 SSize_t slen = SvCUR(check);
800 char *s = HOP3c(strpos, prog->check_offset_min, strend);
802 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
803 " Looking for check substr at fixed offset %"IVdf"...\n",
804 (IV)prog->check_offset_min));
807 /* In this case, the regex is anchored at the end too.
808 * Unless it's a multiline match, the lengths must match
809 * exactly, give or take a \n. NB: slen >= 1 since
810 * the last char of check is \n */
812 && ( strend - s > slen
813 || strend - s < slen - 1
814 || (strend - s == slen && strend[-1] != '\n')))
816 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
817 " String too long...\n"));
820 /* Now should match s[0..slen-2] */
823 if (slen && (*SvPVX_const(check) != *s
824 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
826 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
827 " String not equal...\n"));
832 goto success_at_start;
837 end_shift = prog->check_end_shift;
839 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
841 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
842 (IV)end_shift, RX_PRECOMP(prog));
847 /* This is the (re)entry point of the main loop in this function.
848 * The goal of this loop is to:
849 * 1) find the "check" substring in the region rx_origin..strend
850 * (adjusted by start_shift / end_shift). If not found, reject
852 * 2) If it exists, look for the "other" substr too if defined; for
853 * example, if the check substr maps to the anchored substr, then
854 * check the floating substr, and vice-versa. If not found, go
855 * back to (1) with rx_origin suitably incremented.
856 * 3) If we find an rx_origin position that doesn't contradict
857 * either of the substrings, then check the possible additional
858 * constraints on rx_origin of /^.../m or a known start class.
859 * If these fail, then depending on which constraints fail, jump
860 * back to here, or to various other re-entry points further along
861 * that skip some of the first steps.
862 * 4) If we pass all those tests, update the BmUSEFUL() count on the
863 * substring. If the start position was determined to be at the
864 * beginning of the string - so, not rejected, but not optimised,
865 * since we have to run regmatch from position 0 - decrement the
866 * BmUSEFUL() count. Otherwise increment it.
870 /* first, look for the 'check' substring */
876 DEBUG_OPTIMISE_MORE_r({
877 PerlIO_printf(Perl_debug_log,
878 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
879 " Start shift: %"IVdf" End shift %"IVdf
880 " Real end Shift: %"IVdf"\n",
881 (IV)(rx_origin - strpos),
882 (IV)prog->check_offset_min,
885 (IV)prog->check_end_shift);
888 if (prog->intflags & PREGf_CANY_SEEN) {
889 start_point= (U8*)(rx_origin + start_shift);
890 end_point= (U8*)(strend - end_shift);
891 if (start_point > end_point)
894 end_point = HOP3(strend, -end_shift, strbeg);
895 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
901 /* If the regex is absolutely anchored to either the start of the
902 * string (BOL,SBOL) or to pos() (ANCH_GPOS), then
903 * check_offset_max represents an upper bound on the string where
904 * the substr could start. For the ANCH_GPOS case, we assume that
905 * the caller of intuit will have already set strpos to
906 * pos()-gofs, so in this case strpos + offset_max will still be
907 * an upper bound on the substr.
910 && prog->intflags & PREGf_ANCH
911 && prog->check_offset_max != SSize_t_MAX)
913 SSize_t len = SvCUR(check) - !!SvTAIL(check);
914 const char * const anchor =
915 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
917 /* do a bytes rather than chars comparison. It's conservative;
918 * so it skips doing the HOP if the result can't possibly end
919 * up earlier than the old value of end_point.
921 if ((char*)end_point - anchor > prog->check_offset_max) {
922 end_point = HOP3lim((U8*)anchor,
923 prog->check_offset_max,
929 DEBUG_OPTIMISE_MORE_r({
930 PerlIO_printf(Perl_debug_log, " fbm_instr len=%d str=<%.*s>\n",
931 (int)(end_point - start_point),
932 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
936 check_at = fbm_instr( start_point, end_point,
937 check, multiline ? FBMrf_MULTILINE : 0);
939 /* Update the count-of-usability, remove useless subpatterns,
943 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
944 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
945 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
946 (check_at ? "Found" : "Did not find"),
947 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
948 ? "anchored" : "floating"),
951 (check_at ? " at offset " : "...\n") );
956 /* Finish the diagnostic message */
957 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(check_at - strpos)) );
959 /* set rx_origin to the minimum position where the regex could start
960 * matching, given the constraint of the just-matched check substring.
961 * But don't set it lower than previously.
964 if (check_at - rx_origin > prog->check_offset_max)
965 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
969 /* now look for the 'other' substring if defined */
971 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
972 : prog->substrs->data[other_ix].substr)
974 /* Take into account the "other" substring. */
978 struct reg_substr_datum *other;
981 other = &prog->substrs->data[other_ix];
983 /* if "other" is anchored:
984 * we've previously found a floating substr starting at check_at.
985 * This means that the regex origin must lie somewhere
986 * between min (rx_origin): HOP3(check_at, -check_offset_max)
987 * and max: HOP3(check_at, -check_offset_min)
988 * (except that min will be >= strpos)
989 * So the fixed substr must lie somewhere between
990 * HOP3(min, anchored_offset)
991 * HOP3(max, anchored_offset) + SvCUR(substr)
994 /* if "other" is floating
995 * Calculate last1, the absolute latest point where the
996 * floating substr could start in the string, ignoring any
997 * constraints from the earlier fixed match. It is calculated
1000 * strend - prog->minlen (in chars) is the absolute latest
1001 * position within the string where the origin of the regex
1002 * could appear. The latest start point for the floating
1003 * substr is float_min_offset(*) on from the start of the
1004 * regex. last1 simply combines thee two offsets.
1006 * (*) You might think the latest start point should be
1007 * float_max_offset from the regex origin, and technically
1008 * you'd be correct. However, consider
1010 * Here, float min, max are 3,5 and minlen is 7.
1011 * This can match either
1015 * In the first case, the regex matches minlen chars; in the
1016 * second, minlen+1, in the third, minlen+2.
1017 * In the first case, the floating offset is 3 (which equals
1018 * float_min), in the second, 4, and in the third, 5 (which
1019 * equals float_max). In all cases, the floating string bcd
1020 * can never start more than 4 chars from the end of the
1021 * string, which equals minlen - float_min. As the substring
1022 * starts to match more than float_min from the start of the
1023 * regex, it makes the regex match more than minlen chars,
1024 * and the two cancel each other out. So we can always use
1025 * float_min - minlen, rather than float_max - minlen for the
1026 * latest position in the string.
1028 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1029 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1032 assert(prog->minlen >= other->min_offset);
1033 last1 = HOP3c(strend,
1034 other->min_offset - prog->minlen, strbeg);
1036 if (other_ix) {/* i.e. if (other-is-float) */
1037 /* last is the latest point where the floating substr could
1038 * start, *given* any constraints from the earlier fixed
1039 * match. This constraint is that the floating string starts
1040 * <= float_max_offset chars from the regex origin (rx_origin).
1041 * If this value is less than last1, use it instead.
1043 assert(rx_origin <= last1);
1045 /* this condition handles the offset==infinity case, and
1046 * is a short-cut otherwise. Although it's comparing a
1047 * byte offset to a char length, it does so in a safe way,
1048 * since 1 char always occupies 1 or more bytes,
1049 * so if a string range is (last1 - rx_origin) bytes,
1050 * it will be less than or equal to (last1 - rx_origin)
1051 * chars; meaning it errs towards doing the accurate HOP3
1052 * rather than just using last1 as a short-cut */
1053 (last1 - rx_origin) < other->max_offset
1055 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1058 assert(strpos + start_shift <= check_at);
1059 last = HOP4c(check_at, other->min_offset - start_shift,
1063 s = HOP3c(rx_origin, other->min_offset, strend);
1064 if (s < other_last) /* These positions already checked */
1067 must = utf8_target ? other->utf8_substr : other->substr;
1068 assert(SvPOK(must));
1071 (unsigned char*)last + SvCUR(must) - (SvTAIL(must)!=0),
1073 multiline ? FBMrf_MULTILINE : 0
1076 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1077 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1078 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1079 s ? "Found" : "Contradicts",
1080 other_ix ? "floating" : "anchored",
1081 quoted, RE_SV_TAIL(must));
1086 /* last1 is latest possible substr location. If we didn't
1087 * find it before there, we never will */
1088 if (last >= last1) {
1089 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1090 ", giving up...\n"));
1094 /* try to find the check substr again at a later
1095 * position. Maybe next time we'll find the "other" substr
1097 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1098 ", trying %s at offset %ld...\n",
1099 (other_ix ? "floating" : "anchored"),
1100 (long)(HOP3c(check_at, 1, strend) - strpos)));
1102 other_last = HOP3c(last, 1, strend) /* highest failure */;
1104 other_ix /* i.e. if other-is-float */
1105 ? HOP3c(rx_origin, 1, strend)
1106 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1110 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
1111 (long)(s - strpos)));
1113 if (other_ix) { /* if (other-is-float) */
1114 /* other_last is set to s, not s+1, since its possible for
1115 * a floating substr to fail first time, then succeed
1116 * second time at the same floating position; e.g.:
1117 * "-AB--AABZ" =~ /\wAB\d*Z/
1118 * The first time round, anchored and float match at
1119 * "-(AB)--AAB(Z)" then fail on the initial \w character
1120 * class. Second time round, they match at "-AB--A(AB)(Z)".
1125 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1126 other_last = HOP3c(s, 1, strend);
1131 DEBUG_OPTIMISE_MORE_r(
1132 PerlIO_printf(Perl_debug_log,
1133 " Check-only match: offset min:%"IVdf" max:%"IVdf
1134 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1135 " strend-strpos:%"IVdf"\n",
1136 (IV)prog->check_offset_min,
1137 (IV)prog->check_offset_max,
1138 (IV)(check_at-strpos),
1139 (IV)(rx_origin-strpos),
1140 (IV)(rx_origin-check_at),
1146 postprocess_substr_matches:
1148 /* handle the extra constraint of /^.../m if present */
1150 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1153 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1154 " looking for /^/m anchor"));
1156 /* we have failed the constraint of a \n before rx_origin.
1157 * Find the next \n, if any, even if it's beyond the current
1158 * anchored and/or floating substrings. Whether we should be
1159 * scanning ahead for the next \n or the next substr is debatable.
1160 * On the one hand you'd expect rare substrings to appear less
1161 * often than \n's. On the other hand, searching for \n means
1162 * we're effectively flipping been check_substr and "\n" on each
1163 * iteration as the current "rarest" string candidate, which
1164 * means for example that we'll quickly reject the whole string if
1165 * hasn't got a \n, rather than trying every substr position
1169 s = HOP3c(strend, - prog->minlen, strpos);
1170 if (s <= rx_origin ||
1171 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1173 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1174 " Did not find /%s^%s/m...\n",
1175 PL_colors[0], PL_colors[1]));
1179 /* earliest possible origin is 1 char after the \n.
1180 * (since *rx_origin == '\n', it's safe to ++ here rather than
1181 * HOP(rx_origin, 1)) */
1184 if (prog->substrs->check_ix == 0 /* check is anchored */
1185 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1187 /* Position contradicts check-string; either because
1188 * check was anchored (and thus has no wiggle room),
1189 * or check was float and rx_origin is above the float range */
1190 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1191 " Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
1192 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
1196 /* if we get here, the check substr must have been float,
1197 * is in range, and we may or may not have had an anchored
1198 * "other" substr which still contradicts */
1199 assert(prog->substrs->check_ix); /* check is float */
1201 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1202 /* whoops, the anchored "other" substr exists, so we still
1203 * contradict. On the other hand, the float "check" substr
1204 * didn't contradict, so just retry the anchored "other"
1206 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1207 " Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
1208 PL_colors[0], PL_colors[1],
1209 (long)(rx_origin - strpos),
1210 (long)(rx_origin - strpos + prog->anchored_offset)));
1211 goto do_other_substr;
1214 /* success: we don't contradict the found floating substring
1215 * (and there's no anchored substr). */
1216 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1217 " Found /%s^%s/m at offset %ld...\n",
1218 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
1221 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1222 " (multiline anchor test skipped)\n"));
1228 /* if we have a starting character class, then test that extra constraint.
1229 * (trie stclasses are too expensive to use here, we are better off to
1230 * leave it to regmatch itself) */
1232 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1233 const U8* const str = (U8*)STRING(progi->regstclass);
1235 /* XXX this value could be pre-computed */
1236 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1237 ? (reginfo->is_utf8_pat
1238 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1239 : STR_LEN(progi->regstclass))
1243 /* latest pos that a matching float substr constrains rx start to */
1244 char *rx_max_float = NULL;
1246 /* if the current rx_origin is anchored, either by satisfying an
1247 * anchored substring constraint, or a /^.../m constraint, then we
1248 * can reject the current origin if the start class isn't found
1249 * at the current position. If we have a float-only match, then
1250 * rx_origin is constrained to a range; so look for the start class
1251 * in that range. if neither, then look for the start class in the
1252 * whole rest of the string */
1254 /* XXX DAPM it's not clear what the minlen test is for, and why
1255 * it's not used in the floating case. Nothing in the test suite
1256 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1257 * Here are some old comments, which may or may not be correct:
1259 * minlen == 0 is possible if regstclass is \b or \B,
1260 * and the fixed substr is ''$.
1261 * Since minlen is already taken into account, rx_origin+1 is
1262 * before strend; accidentally, minlen >= 1 guaranties no false
1263 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1264 * 0) below assumes that regstclass does not come from lookahead...
1265 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1266 * This leaves EXACTF-ish only, which are dealt with in
1270 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1271 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1272 else if (prog->float_substr || prog->float_utf8) {
1273 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1274 endpos= HOP3c(rx_max_float, cl_l, strend);
1279 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1280 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1281 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1282 (IV)start_shift, (IV)(check_at - strbeg),
1283 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1285 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1288 if (endpos == strend) {
1289 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1290 " Could not match STCLASS...\n") );
1293 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1294 " This position contradicts STCLASS...\n") );
1295 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1296 && !(prog->intflags & PREGf_IMPLICIT))
1299 /* Contradict one of substrings */
1300 if (prog->anchored_substr || prog->anchored_utf8) {
1301 if (prog->substrs->check_ix == 1) { /* check is float */
1302 /* Have both, check_string is floating */
1303 assert(rx_origin + start_shift <= check_at);
1304 if (rx_origin + start_shift != check_at) {
1305 /* not at latest position float substr could match:
1306 * Recheck anchored substring, but not floating.
1307 * The condition above is in bytes rather than
1308 * chars for efficiency. It's conservative, in
1309 * that it errs on the side of doing 'goto
1310 * do_other_substr', where a more accurate
1311 * char-based calculation will be done */
1312 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1313 " Looking for anchored substr starting at offset %ld...\n",
1314 (long)(other_last - strpos)) );
1315 goto do_other_substr;
1323 /* In the presence of ml_anch, we might be able to
1324 * find another \n without breaking the current float
1327 /* strictly speaking this should be HOP3c(..., 1, ...),
1328 * but since we goto a block of code that's going to
1329 * search for the next \n if any, its safe here */
1331 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1332 " Looking for /%s^%s/m starting at offset %ld...\n",
1333 PL_colors[0], PL_colors[1],
1334 (long)(rx_origin - strpos)) );
1335 goto postprocess_substr_matches;
1338 /* strictly speaking this can never be true; but might
1339 * be if we ever allow intuit without substrings */
1340 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1343 rx_origin = rx_max_float;
1346 /* at this point, any matching substrings have been
1347 * contradicted. Start again... */
1349 rx_origin = HOP3c(rx_origin, 1, strend);
1351 /* uses bytes rather than char calculations for efficiency.
1352 * It's conservative: it errs on the side of doing 'goto restart',
1353 * where there is code that does a proper char-based test */
1354 if (rx_origin + start_shift + end_shift > strend) {
1355 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1356 " Could not match STCLASS...\n") );
1359 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1360 " Looking for %s substr starting at offset %ld...\n",
1361 (prog->substrs->check_ix ? "floating" : "anchored"),
1362 (long)(rx_origin + start_shift - strpos)) );
1368 if (rx_origin != s) {
1369 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1370 " By STCLASS: moving %ld --> %ld\n",
1371 (long)(rx_origin - strpos), (long)(s - strpos))
1375 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1376 " Does not contradict STCLASS...\n");
1381 /* Decide whether using the substrings helped */
1383 if (rx_origin != strpos) {
1384 /* Fixed substring is found far enough so that the match
1385 cannot start at strpos. */
1387 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1388 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1391 /* The found rx_origin position does not prohibit matching at
1392 * strpos, so calling intuit didn't gain us anything. Decrement
1393 * the BmUSEFUL() count on the check substring, and if we reach
1395 if (!(prog->intflags & PREGf_NAUGHTY)
1397 prog->check_utf8 /* Could be deleted already */
1398 && --BmUSEFUL(prog->check_utf8) < 0
1399 && (prog->check_utf8 == prog->float_utf8)
1401 prog->check_substr /* Could be deleted already */
1402 && --BmUSEFUL(prog->check_substr) < 0
1403 && (prog->check_substr == prog->float_substr)
1406 /* If flags & SOMETHING - do not do it many times on the same match */
1407 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1408 /* XXX Does the destruction order has to change with utf8_target? */
1409 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1410 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1411 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1412 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1413 check = NULL; /* abort */
1414 /* XXXX This is a remnant of the old implementation. It
1415 looks wasteful, since now INTUIT can use many
1416 other heuristics. */
1417 prog->extflags &= ~RXf_USE_INTUIT;
1421 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1422 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1423 PL_colors[4], PL_colors[5], (long)(rx_origin - strpos)) );
1427 fail_finish: /* Substring not found */
1428 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1429 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1431 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1432 PL_colors[4], PL_colors[5]));
1437 #define DECL_TRIE_TYPE(scan) \
1438 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1439 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold } \
1440 trie_type = ((scan->flags == EXACT) \
1441 ? (utf8_target ? trie_utf8 : trie_plain) \
1442 : (scan->flags == EXACTFA) \
1443 ? (utf8_target ? trie_utf8_exactfa_fold : trie_latin_utf8_exactfa_fold) \
1444 : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
1446 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1449 U8 flags = FOLD_FLAGS_FULL; \
1450 switch (trie_type) { \
1451 case trie_utf8_exactfa_fold: \
1452 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1454 case trie_utf8_fold: \
1455 if ( foldlen>0 ) { \
1456 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1461 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1462 len = UTF8SKIP(uc); \
1463 skiplen = UNISKIP( uvc ); \
1464 foldlen -= skiplen; \
1465 uscan = foldbuf + skiplen; \
1468 case trie_latin_utf8_exactfa_fold: \
1469 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1471 case trie_latin_utf8_fold: \
1472 if ( foldlen>0 ) { \
1473 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1479 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1480 skiplen = UNISKIP( uvc ); \
1481 foldlen -= skiplen; \
1482 uscan = foldbuf + skiplen; \
1486 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1493 charid = trie->charmap[ uvc ]; \
1497 if (widecharmap) { \
1498 SV** const svpp = hv_fetch(widecharmap, \
1499 (char*)&uvc, sizeof(UV), 0); \
1501 charid = (U16)SvIV(*svpp); \
1506 #define DUMP_EXEC_POS(li,s,doutf8) \
1507 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1510 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1514 && (ln == 1 || folder(s, pat_string, ln)) \
1515 && (reginfo->intuit || regtry(reginfo, &s)) )\
1521 #define REXEC_FBC_UTF8_SCAN(CODE) \
1523 while (s < strend) { \
1529 #define REXEC_FBC_SCAN(CODE) \
1531 while (s < strend) { \
1537 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1538 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1540 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1549 #define REXEC_FBC_CLASS_SCAN(COND) \
1550 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1552 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1561 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1562 if (utf8_target) { \
1563 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1566 REXEC_FBC_CLASS_SCAN(COND); \
1569 /* The three macros below are slightly different versions of the same logic.
1571 * The first is for /a and /aa when the target string is UTF-8. This can only
1572 * match ascii, but it must advance based on UTF-8. The other two handle the
1573 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1574 * for the boundary (or non-boundary) between a word and non-word character.
1575 * The utf8 and non-utf8 cases have the same logic, but the details must be
1576 * different. Find the "wordness" of the character just prior to this one, and
1577 * compare it with the wordness of this one. If they differ, we have a
1578 * boundary. At the beginning of the string, pretend that the previous
1579 * character was a new-line.
1581 * All these macros uncleanly have side-effects with each other and outside
1582 * variables. So far it's been too much trouble to clean-up
1584 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1585 * a word character or not.
1586 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1588 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1590 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1591 * are looking for a boundary or for a non-boundary. If we are looking for a
1592 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1593 * see if this tentative match actually works, and if so, to quit the loop
1594 * here. And vice-versa if we are looking for a non-boundary.
1596 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1597 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1598 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1599 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1600 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1601 * complement. But in that branch we complement tmp, meaning that at the
1602 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1603 * which means at the top of the loop in the next iteration, it is
1604 * TEST_NON_UTF8(s-1) */
1605 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1606 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1607 tmp = TEST_NON_UTF8(tmp); \
1608 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1609 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1611 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1618 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1619 * TEST_UTF8 is a macro that for the same input code points returns identically
1620 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1621 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1622 if (s == reginfo->strbeg) { \
1625 else { /* Back-up to the start of the previous character */ \
1626 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1627 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1628 0, UTF8_ALLOW_DEFAULT); \
1630 tmp = TEST_UV(tmp); \
1631 LOAD_UTF8_CHARCLASS_ALNUM(); \
1632 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1633 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1642 /* Like the above two macros. UTF8_CODE is the complete code for handling
1643 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1645 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1646 if (utf8_target) { \
1649 else { /* Not utf8 */ \
1650 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1651 tmp = TEST_NON_UTF8(tmp); \
1652 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1653 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1662 /* Here, things have been set up by the previous code so that tmp is the \
1663 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1664 * utf8ness of the target). We also have to check if this matches against \
1665 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1666 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1668 if (tmp == ! TEST_NON_UTF8('\n')) { \
1675 /* This is the macro to use when we want to see if something that looks like it
1676 * could match, actually does, and if so exits the loop */
1677 #define REXEC_FBC_TRYIT \
1678 if ((reginfo->intuit || regtry(reginfo, &s))) \
1681 /* The only difference between the BOUND and NBOUND cases is that
1682 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1683 * NBOUND. This is accomplished by passing it as either the if or else clause,
1684 * with the other one being empty (PLACEHOLDER is defined as empty).
1686 * The TEST_FOO parameters are for operating on different forms of input, but
1687 * all should be ones that return identically for the same underlying code
1689 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1691 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1692 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1694 #define FBC_BOUND_A(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1696 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1697 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1699 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1701 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1702 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1704 #define FBC_NBOUND_A(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1706 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1707 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1710 /* We know what class REx starts with. Try to find this position... */
1711 /* if reginfo->intuit, its a dryrun */
1712 /* annoyingly all the vars in this routine have different names from their counterparts
1713 in regmatch. /grrr */
1715 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1716 const char *strend, regmatch_info *reginfo)
1719 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1720 char *pat_string; /* The pattern's exactish string */
1721 char *pat_end; /* ptr to end char of pat_string */
1722 re_fold_t folder; /* Function for computing non-utf8 folds */
1723 const U8 *fold_array; /* array for folding ords < 256 */
1729 I32 tmp = 1; /* Scratch variable? */
1730 const bool utf8_target = reginfo->is_utf8_target;
1731 UV utf8_fold_flags = 0;
1732 const bool is_utf8_pat = reginfo->is_utf8_pat;
1733 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1734 with a result inverts that result, as 0^1 =
1736 _char_class_number classnum;
1738 RXi_GET_DECL(prog,progi);
1740 PERL_ARGS_ASSERT_FIND_BYCLASS;
1742 /* We know what class it must start with. */
1746 REXEC_FBC_UTF8_CLASS_SCAN(
1747 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1750 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1755 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
1762 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1763 assert(! is_utf8_pat);
1766 if (is_utf8_pat || utf8_target) {
1767 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1768 goto do_exactf_utf8;
1770 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1771 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1772 goto do_exactf_non_utf8; /* isn't dealt with by these */
1774 case EXACTF: /* This node only generated for non-utf8 patterns */
1775 assert(! is_utf8_pat);
1777 utf8_fold_flags = 0;
1778 goto do_exactf_utf8;
1780 fold_array = PL_fold;
1782 goto do_exactf_non_utf8;
1785 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1786 utf8_fold_flags = FOLDEQ_LOCALE;
1787 goto do_exactf_utf8;
1789 fold_array = PL_fold_locale;
1790 folder = foldEQ_locale;
1791 goto do_exactf_non_utf8;
1795 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1797 goto do_exactf_utf8;
1800 if (is_utf8_pat || utf8_target) {
1801 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1802 goto do_exactf_utf8;
1805 /* Any 'ss' in the pattern should have been replaced by regcomp,
1806 * so we don't have to worry here about this single special case
1807 * in the Latin1 range */
1808 fold_array = PL_fold_latin1;
1809 folder = foldEQ_latin1;
1813 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1814 are no glitches with fold-length differences
1815 between the target string and pattern */
1817 /* The idea in the non-utf8 EXACTF* cases is to first find the
1818 * first character of the EXACTF* node and then, if necessary,
1819 * case-insensitively compare the full text of the node. c1 is the
1820 * first character. c2 is its fold. This logic will not work for
1821 * Unicode semantics and the german sharp ss, which hence should
1822 * not be compiled into a node that gets here. */
1823 pat_string = STRING(c);
1824 ln = STR_LEN(c); /* length to match in octets/bytes */
1826 /* We know that we have to match at least 'ln' bytes (which is the
1827 * same as characters, since not utf8). If we have to match 3
1828 * characters, and there are only 2 availabe, we know without
1829 * trying that it will fail; so don't start a match past the
1830 * required minimum number from the far end */
1831 e = HOP3c(strend, -((SSize_t)ln), s);
1833 if (reginfo->intuit && e < s) {
1834 e = s; /* Due to minlen logic of intuit() */
1838 c2 = fold_array[c1];
1839 if (c1 == c2) { /* If char and fold are the same */
1840 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1843 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1851 /* If one of the operands is in utf8, we can't use the simpler folding
1852 * above, due to the fact that many different characters can have the
1853 * same fold, or portion of a fold, or different- length fold */
1854 pat_string = STRING(c);
1855 ln = STR_LEN(c); /* length to match in octets/bytes */
1856 pat_end = pat_string + ln;
1857 lnc = is_utf8_pat /* length to match in characters */
1858 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1861 /* We have 'lnc' characters to match in the pattern, but because of
1862 * multi-character folding, each character in the target can match
1863 * up to 3 characters (Unicode guarantees it will never exceed
1864 * this) if it is utf8-encoded; and up to 2 if not (based on the
1865 * fact that the Latin 1 folds are already determined, and the
1866 * only multi-char fold in that range is the sharp-s folding to
1867 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1868 * string character. Adjust lnc accordingly, rounding up, so that
1869 * if we need to match at least 4+1/3 chars, that really is 5. */
1870 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1871 lnc = (lnc + expansion - 1) / expansion;
1873 /* As in the non-UTF8 case, if we have to match 3 characters, and
1874 * only 2 are left, it's guaranteed to fail, so don't start a
1875 * match that would require us to go beyond the end of the string
1877 e = HOP3c(strend, -((SSize_t)lnc), s);
1879 if (reginfo->intuit && e < s) {
1880 e = s; /* Due to minlen logic of intuit() */
1883 /* XXX Note that we could recalculate e to stop the loop earlier,
1884 * as the worst case expansion above will rarely be met, and as we
1885 * go along we would usually find that e moves further to the left.
1886 * This would happen only after we reached the point in the loop
1887 * where if there were no expansion we should fail. Unclear if
1888 * worth the expense */
1891 char *my_strend= (char *)strend;
1892 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1893 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1894 && (reginfo->intuit || regtry(reginfo, &s)) )
1898 s += (utf8_target) ? UTF8SKIP(s) : 1;
1904 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
1907 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
1910 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
1913 FBC_BOUND_A(isWORDCHAR_A, isWORDCHAR_A, isWORDCHAR_A);
1916 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
1919 FBC_NBOUND_A(isWORDCHAR_A, isWORDCHAR_A, isWORDCHAR_A);
1922 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
1925 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
1928 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
1929 is_LNBREAK_latin1_safe(s, strend)
1933 /* The argument to all the POSIX node types is the class number to pass to
1934 * _generic_isCC() to build a mask for searching in PL_charclass[] */
1941 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
1942 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
1957 /* The complement of something that matches only ASCII matches all
1958 * non-ASCII, plus everything in ASCII that isn't in the class. */
1959 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
1960 || ! _generic_isCC_A(*s, FLAGS(c)));
1969 /* Don't need to worry about utf8, as it can match only a single
1970 * byte invariant character. */
1971 REXEC_FBC_CLASS_SCAN(
1972 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
1980 if (! utf8_target) {
1981 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
1987 classnum = (_char_class_number) FLAGS(c);
1988 if (classnum < _FIRST_NON_SWASH_CC) {
1989 while (s < strend) {
1991 /* We avoid loading in the swash as long as possible, but
1992 * should we have to, we jump to a separate loop. This
1993 * extra 'if' statement is what keeps this code from being
1994 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
1995 if (UTF8_IS_ABOVE_LATIN1(*s)) {
1996 goto found_above_latin1;
1998 if ((UTF8_IS_INVARIANT(*s)
1999 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2001 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2002 && to_complement ^ cBOOL(
2003 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2007 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2019 else switch (classnum) { /* These classes are implemented as
2021 case _CC_ENUM_SPACE: /* XXX would require separate code if we
2022 revert the change of \v matching this */
2025 case _CC_ENUM_PSXSPC:
2026 REXEC_FBC_UTF8_CLASS_SCAN(
2027 to_complement ^ cBOOL(isSPACE_utf8(s)));
2030 case _CC_ENUM_BLANK:
2031 REXEC_FBC_UTF8_CLASS_SCAN(
2032 to_complement ^ cBOOL(isBLANK_utf8(s)));
2035 case _CC_ENUM_XDIGIT:
2036 REXEC_FBC_UTF8_CLASS_SCAN(
2037 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2040 case _CC_ENUM_VERTSPACE:
2041 REXEC_FBC_UTF8_CLASS_SCAN(
2042 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2045 case _CC_ENUM_CNTRL:
2046 REXEC_FBC_UTF8_CLASS_SCAN(
2047 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2051 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2052 assert(0); /* NOTREACHED */
2057 found_above_latin1: /* Here we have to load a swash to get the result
2058 for the current code point */
2059 if (! PL_utf8_swash_ptrs[classnum]) {
2060 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2061 PL_utf8_swash_ptrs[classnum] =
2062 _core_swash_init("utf8",
2065 PL_XPosix_ptrs[classnum], &flags);
2068 /* This is a copy of the loop above for swash classes, though using the
2069 * FBC macro instead of being expanded out. Since we've loaded the
2070 * swash, we don't have to check for that each time through the loop */
2071 REXEC_FBC_UTF8_CLASS_SCAN(
2072 to_complement ^ cBOOL(_generic_utf8(
2075 swash_fetch(PL_utf8_swash_ptrs[classnum],
2083 /* what trie are we using right now */
2084 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2085 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2086 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2088 const char *last_start = strend - trie->minlen;
2090 const char *real_start = s;
2092 STRLEN maxlen = trie->maxlen;
2094 U8 **points; /* map of where we were in the input string
2095 when reading a given char. For ASCII this
2096 is unnecessary overhead as the relationship
2097 is always 1:1, but for Unicode, especially
2098 case folded Unicode this is not true. */
2099 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2103 GET_RE_DEBUG_FLAGS_DECL;
2105 /* We can't just allocate points here. We need to wrap it in
2106 * an SV so it gets freed properly if there is a croak while
2107 * running the match */
2110 sv_points=newSV(maxlen * sizeof(U8 *));
2111 SvCUR_set(sv_points,
2112 maxlen * sizeof(U8 *));
2113 SvPOK_on(sv_points);
2114 sv_2mortal(sv_points);
2115 points=(U8**)SvPV_nolen(sv_points );
2116 if ( trie_type != trie_utf8_fold
2117 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2120 bitmap=(U8*)trie->bitmap;
2122 bitmap=(U8*)ANYOF_BITMAP(c);
2124 /* this is the Aho-Corasick algorithm modified a touch
2125 to include special handling for long "unknown char" sequences.
2126 The basic idea being that we use AC as long as we are dealing
2127 with a possible matching char, when we encounter an unknown char
2128 (and we have not encountered an accepting state) we scan forward
2129 until we find a legal starting char.
2130 AC matching is basically that of trie matching, except that when
2131 we encounter a failing transition, we fall back to the current
2132 states "fail state", and try the current char again, a process
2133 we repeat until we reach the root state, state 1, or a legal
2134 transition. If we fail on the root state then we can either
2135 terminate if we have reached an accepting state previously, or
2136 restart the entire process from the beginning if we have not.
2139 while (s <= last_start) {
2140 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2148 U8 *uscan = (U8*)NULL;
2149 U8 *leftmost = NULL;
2151 U32 accepted_word= 0;
2155 while ( state && uc <= (U8*)strend ) {
2157 U32 word = aho->states[ state ].wordnum;
2161 DEBUG_TRIE_EXECUTE_r(
2162 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2163 dump_exec_pos( (char *)uc, c, strend, real_start,
2164 (char *)uc, utf8_target );
2165 PerlIO_printf( Perl_debug_log,
2166 " Scanning for legal start char...\n");
2170 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2174 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2180 if (uc >(U8*)last_start) break;
2184 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2185 if (!leftmost || lpos < leftmost) {
2186 DEBUG_r(accepted_word=word);
2192 points[pointpos++ % maxlen]= uc;
2193 if (foldlen || uc < (U8*)strend) {
2194 REXEC_TRIE_READ_CHAR(trie_type, trie,
2196 uscan, len, uvc, charid, foldlen,
2198 DEBUG_TRIE_EXECUTE_r({
2199 dump_exec_pos( (char *)uc, c, strend,
2200 real_start, s, utf8_target);
2201 PerlIO_printf(Perl_debug_log,
2202 " Charid:%3u CP:%4"UVxf" ",
2214 word = aho->states[ state ].wordnum;
2216 base = aho->states[ state ].trans.base;
2218 DEBUG_TRIE_EXECUTE_r({
2220 dump_exec_pos( (char *)uc, c, strend, real_start,
2222 PerlIO_printf( Perl_debug_log,
2223 "%sState: %4"UVxf", word=%"UVxf,
2224 failed ? " Fail transition to " : "",
2225 (UV)state, (UV)word);
2231 ( ((offset = base + charid
2232 - 1 - trie->uniquecharcount)) >= 0)
2233 && ((U32)offset < trie->lasttrans)
2234 && trie->trans[offset].check == state
2235 && (tmp=trie->trans[offset].next))
2237 DEBUG_TRIE_EXECUTE_r(
2238 PerlIO_printf( Perl_debug_log," - legal\n"));
2243 DEBUG_TRIE_EXECUTE_r(
2244 PerlIO_printf( Perl_debug_log," - fail\n"));
2246 state = aho->fail[state];
2250 /* we must be accepting here */
2251 DEBUG_TRIE_EXECUTE_r(
2252 PerlIO_printf( Perl_debug_log," - accepting\n"));
2261 if (!state) state = 1;
2264 if ( aho->states[ state ].wordnum ) {
2265 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2266 if (!leftmost || lpos < leftmost) {
2267 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2272 s = (char*)leftmost;
2273 DEBUG_TRIE_EXECUTE_r({
2275 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2276 (UV)accepted_word, (IV)(s - real_start)
2279 if (reginfo->intuit || regtry(reginfo, &s)) {
2285 DEBUG_TRIE_EXECUTE_r({
2286 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2289 DEBUG_TRIE_EXECUTE_r(
2290 PerlIO_printf( Perl_debug_log,"No match.\n"));
2299 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2306 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2307 * flags have same meanings as with regexec_flags() */
2310 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2317 struct regexp *const prog = ReANY(rx);
2319 if (flags & REXEC_COPY_STR) {
2323 PerlIO_printf(Perl_debug_log,
2324 "Copy on write: regexp capture, type %d\n",
2327 /* Create a new COW SV to share the match string and store
2328 * in saved_copy, unless the current COW SV in saved_copy
2329 * is valid and suitable for our purpose */
2330 if (( prog->saved_copy
2331 && SvIsCOW(prog->saved_copy)
2332 && SvPOKp(prog->saved_copy)
2335 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2337 /* just reuse saved_copy SV */
2338 if (RXp_MATCH_COPIED(prog)) {
2339 Safefree(prog->subbeg);
2340 RXp_MATCH_COPIED_off(prog);
2344 /* create new COW SV to share string */
2345 RX_MATCH_COPY_FREE(rx);
2346 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2348 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2349 assert (SvPOKp(prog->saved_copy));
2350 prog->sublen = strend - strbeg;
2351 prog->suboffset = 0;
2352 prog->subcoffset = 0;
2357 SSize_t max = strend - strbeg;
2360 if ( (flags & REXEC_COPY_SKIP_POST)
2361 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2362 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2363 ) { /* don't copy $' part of string */
2366 /* calculate the right-most part of the string covered
2367 * by a capture. Due to look-ahead, this may be to
2368 * the right of $&, so we have to scan all captures */
2369 while (n <= prog->lastparen) {
2370 if (prog->offs[n].end > max)
2371 max = prog->offs[n].end;
2375 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2376 ? prog->offs[0].start
2378 assert(max >= 0 && max <= strend - strbeg);
2381 if ( (flags & REXEC_COPY_SKIP_PRE)
2382 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2383 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2384 ) { /* don't copy $` part of string */
2387 /* calculate the left-most part of the string covered
2388 * by a capture. Due to look-behind, this may be to
2389 * the left of $&, so we have to scan all captures */
2390 while (min && n <= prog->lastparen) {
2391 if ( prog->offs[n].start != -1
2392 && prog->offs[n].start < min)
2394 min = prog->offs[n].start;
2398 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2399 && min > prog->offs[0].end
2401 min = prog->offs[0].end;
2405 assert(min >= 0 && min <= max && min <= strend - strbeg);
2408 if (RX_MATCH_COPIED(rx)) {
2409 if (sublen > prog->sublen)
2411 (char*)saferealloc(prog->subbeg, sublen+1);
2414 prog->subbeg = (char*)safemalloc(sublen+1);
2415 Copy(strbeg + min, prog->subbeg, sublen, char);
2416 prog->subbeg[sublen] = '\0';
2417 prog->suboffset = min;
2418 prog->sublen = sublen;
2419 RX_MATCH_COPIED_on(rx);
2421 prog->subcoffset = prog->suboffset;
2422 if (prog->suboffset && utf8_target) {
2423 /* Convert byte offset to chars.
2424 * XXX ideally should only compute this if @-/@+
2425 * has been seen, a la PL_sawampersand ??? */
2427 /* If there's a direct correspondence between the
2428 * string which we're matching and the original SV,
2429 * then we can use the utf8 len cache associated with
2430 * the SV. In particular, it means that under //g,
2431 * sv_pos_b2u() will use the previously cached
2432 * position to speed up working out the new length of
2433 * subcoffset, rather than counting from the start of
2434 * the string each time. This stops
2435 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2436 * from going quadratic */
2437 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2438 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2439 SV_GMAGIC|SV_CONST_RETURN);
2441 prog->subcoffset = utf8_length((U8*)strbeg,
2442 (U8*)(strbeg+prog->suboffset));
2446 RX_MATCH_COPY_FREE(rx);
2447 prog->subbeg = strbeg;
2448 prog->suboffset = 0;
2449 prog->subcoffset = 0;
2450 prog->sublen = strend - strbeg;
2458 - regexec_flags - match a regexp against a string
2461 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2462 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2463 /* stringarg: the point in the string at which to begin matching */
2464 /* strend: pointer to null at end of string */
2465 /* strbeg: real beginning of string */
2466 /* minend: end of match must be >= minend bytes after stringarg. */
2467 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2468 * itself is accessed via the pointers above */
2469 /* data: May be used for some additional optimizations.
2470 Currently unused. */
2471 /* flags: For optimizations. See REXEC_* in regexp.h */
2474 struct regexp *const prog = ReANY(rx);
2478 SSize_t minlen; /* must match at least this many chars */
2479 SSize_t dontbother = 0; /* how many characters not to try at end */
2480 const bool utf8_target = cBOOL(DO_UTF8(sv));
2482 RXi_GET_DECL(prog,progi);
2483 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2484 regmatch_info *const reginfo = ®info_buf;
2485 regexp_paren_pair *swap = NULL;
2487 GET_RE_DEBUG_FLAGS_DECL;
2489 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2490 PERL_UNUSED_ARG(data);
2492 /* Be paranoid... */
2493 if (prog == NULL || stringarg == NULL) {
2494 Perl_croak(aTHX_ "NULL regexp parameter");
2498 debug_start_match(rx, utf8_target, stringarg, strend,
2502 startpos = stringarg;
2504 if (prog->intflags & PREGf_GPOS_SEEN) {
2507 /* set reginfo->ganch, the position where \G can match */
2510 (flags & REXEC_IGNOREPOS)
2511 ? stringarg /* use start pos rather than pos() */
2512 : (sv && (mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2513 /* Defined pos(): */
2514 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2515 : strbeg; /* pos() not defined; use start of string */
2517 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2518 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2520 /* in the presence of \G, we may need to start looking earlier in
2521 * the string than the suggested start point of stringarg:
2522 * if prog->gofs is set, then that's a known, fixed minimum
2525 * /ab|c\G/: gofs = 1
2526 * or if the minimum offset isn't known, then we have to go back
2527 * to the start of the string, e.g. /w+\G/
2530 if (prog->intflags & PREGf_ANCH_GPOS) {
2531 startpos = reginfo->ganch - prog->gofs;
2533 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2535 DEBUG_r(PerlIO_printf(Perl_debug_log,
2536 "fail: ganch-gofs before earliest possible start\n"));
2540 else if (prog->gofs) {
2541 if (startpos - prog->gofs < strbeg)
2544 startpos -= prog->gofs;
2546 else if (prog->intflags & PREGf_GPOS_FLOAT)
2550 minlen = prog->minlen;
2551 if ((startpos + minlen) > strend || startpos < strbeg) {
2552 DEBUG_r(PerlIO_printf(Perl_debug_log,
2553 "Regex match can't succeed, so not even tried\n"));
2557 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2558 * which will call destuctors to reset PL_regmatch_state, free higher
2559 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2560 * regmatch_info_aux_eval */
2562 oldsave = PL_savestack_ix;
2566 if ((prog->extflags & RXf_USE_INTUIT)
2567 && !(flags & REXEC_CHECKED))
2569 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2574 if (prog->extflags & RXf_CHECK_ALL) {
2575 /* we can match based purely on the result of INTUIT.
2576 * Set up captures etc just for $& and $-[0]
2577 * (an intuit-only match wont have $1,$2,..) */
2578 assert(!prog->nparens);
2580 /* s/// doesn't like it if $& is earlier than where we asked it to
2581 * start searching (which can happen on something like /.\G/) */
2582 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2585 /* this should only be possible under \G */
2586 assert(prog->intflags & PREGf_GPOS_SEEN);
2587 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2588 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2592 /* match via INTUIT shouldn't have any captures.
2593 * Let @-, @+, $^N know */
2594 prog->lastparen = prog->lastcloseparen = 0;
2595 RX_MATCH_UTF8_set(rx, utf8_target);
2596 prog->offs[0].start = s - strbeg;
2597 prog->offs[0].end = utf8_target
2598 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2599 : s - strbeg + prog->minlenret;
2600 if ( !(flags & REXEC_NOT_FIRST) )
2601 S_reg_set_capture_string(aTHX_ rx,
2603 sv, flags, utf8_target);
2609 multiline = prog->extflags & RXf_PMf_MULTILINE;
2611 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2612 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2613 "String too short [regexec_flags]...\n"));
2617 /* Check validity of program. */
2618 if (UCHARAT(progi->program) != REG_MAGIC) {
2619 Perl_croak(aTHX_ "corrupted regexp program");
2622 RX_MATCH_TAINTED_off(rx);
2624 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2625 reginfo->intuit = 0;
2626 reginfo->is_utf8_target = cBOOL(utf8_target);
2627 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2628 reginfo->warned = FALSE;
2629 reginfo->strbeg = strbeg;
2631 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2632 reginfo->strend = strend;
2633 /* see how far we have to get to not match where we matched before */
2634 reginfo->till = stringarg + minend;
2636 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2637 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2638 S_cleanup_regmatch_info_aux has executed (registered by
2639 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2640 magic belonging to this SV.
2641 Not newSVsv, either, as it does not COW.
2643 assert(!IS_PADGV(sv));
2644 reginfo->sv = newSV(0);
2645 SvSetSV_nosteal(reginfo->sv, sv);
2646 SAVEFREESV(reginfo->sv);
2649 /* reserve next 2 or 3 slots in PL_regmatch_state:
2650 * slot N+0: may currently be in use: skip it
2651 * slot N+1: use for regmatch_info_aux struct
2652 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2653 * slot N+3: ready for use by regmatch()
2657 regmatch_state *old_regmatch_state;
2658 regmatch_slab *old_regmatch_slab;
2659 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2661 /* on first ever match, allocate first slab */
2662 if (!PL_regmatch_slab) {
2663 Newx(PL_regmatch_slab, 1, regmatch_slab);
2664 PL_regmatch_slab->prev = NULL;
2665 PL_regmatch_slab->next = NULL;
2666 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2669 old_regmatch_state = PL_regmatch_state;
2670 old_regmatch_slab = PL_regmatch_slab;
2672 for (i=0; i <= max; i++) {
2674 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2676 reginfo->info_aux_eval =
2677 reginfo->info_aux->info_aux_eval =
2678 &(PL_regmatch_state->u.info_aux_eval);
2680 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2681 PL_regmatch_state = S_push_slab(aTHX);
2684 /* note initial PL_regmatch_state position; at end of match we'll
2685 * pop back to there and free any higher slabs */
2687 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
2688 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
2689 reginfo->info_aux->poscache = NULL;
2691 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
2693 if ((prog->extflags & RXf_EVAL_SEEN))
2694 S_setup_eval_state(aTHX_ reginfo);
2696 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
2699 /* If there is a "must appear" string, look for it. */
2701 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2702 /* We have to be careful. If the previous successful match
2703 was from this regex we don't want a subsequent partially
2704 successful match to clobber the old results.
2705 So when we detect this possibility we add a swap buffer
2706 to the re, and switch the buffer each match. If we fail,
2707 we switch it back; otherwise we leave it swapped.
2710 /* do we need a save destructor here for eval dies? */
2711 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2712 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2713 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2720 /* Simplest case: anchored match need be tried only once. */
2721 /* [unless only anchor is BOL and multiline is set] */
2722 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
2723 if (s == startpos && regtry(reginfo, &s))
2725 else if (multiline || (prog->intflags & (PREGf_IMPLICIT | PREGf_ANCH_MBOL))) /* XXXX SBOL? */
2730 dontbother = minlen - 1;
2731 end = HOP3c(strend, -dontbother, strbeg) - 1;
2732 /* for multiline we only have to try after newlines */
2733 if (prog->check_substr || prog->check_utf8) {
2734 /* because of the goto we can not easily reuse the macros for bifurcating the
2735 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2738 goto after_try_utf8;
2740 if (regtry(reginfo, &s)) {
2747 if (prog->extflags & RXf_USE_INTUIT) {
2748 s = re_intuit_start(rx, sv, strbeg,
2749 s + UTF8SKIP(s), strend, flags, NULL);
2758 } /* end search for check string in unicode */
2760 if (s == startpos) {
2761 goto after_try_latin;
2764 if (regtry(reginfo, &s)) {
2771 if (prog->extflags & RXf_USE_INTUIT) {
2772 s = re_intuit_start(rx, sv, strbeg,
2773 s + 1, strend, flags, NULL);
2782 } /* end search for check string in latin*/
2783 } /* end search for check string */
2784 else { /* search for newline */
2786 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2789 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2790 while (s <= end) { /* note it could be possible to match at the end of the string */
2791 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2792 if (regtry(reginfo, &s))
2796 } /* end search for newline */
2797 } /* end anchored/multiline check string search */
2799 } else if (prog->intflags & PREGf_ANCH_GPOS)
2801 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
2802 assert(prog->intflags & PREGf_GPOS_SEEN);
2803 /* For anchored \G, the only position it can match from is
2804 * (ganch-gofs); we already set startpos to this above; if intuit
2805 * moved us on from there, we can't possibly succeed */
2806 assert(startpos == reginfo->ganch - prog->gofs);
2807 if (s == startpos && regtry(reginfo, &s))
2812 /* Messy cases: unanchored match. */
2813 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2814 /* we have /x+whatever/ */
2815 /* it must be a one character string (XXXX Except is_utf8_pat?) */
2821 if (! prog->anchored_utf8) {
2822 to_utf8_substr(prog);
2824 ch = SvPVX_const(prog->anchored_utf8)[0];
2827 DEBUG_EXECUTE_r( did_match = 1 );
2828 if (regtry(reginfo, &s)) goto got_it;
2830 while (s < strend && *s == ch)
2837 if (! prog->anchored_substr) {
2838 if (! to_byte_substr(prog)) {
2839 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2842 ch = SvPVX_const(prog->anchored_substr)[0];
2845 DEBUG_EXECUTE_r( did_match = 1 );
2846 if (regtry(reginfo, &s)) goto got_it;
2848 while (s < strend && *s == ch)
2853 DEBUG_EXECUTE_r(if (!did_match)
2854 PerlIO_printf(Perl_debug_log,
2855 "Did not find anchored character...\n")
2858 else if (prog->anchored_substr != NULL
2859 || prog->anchored_utf8 != NULL
2860 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2861 && prog->float_max_offset < strend - s)) {
2866 char *last1; /* Last position checked before */
2870 if (prog->anchored_substr || prog->anchored_utf8) {
2872 if (! prog->anchored_utf8) {
2873 to_utf8_substr(prog);
2875 must = prog->anchored_utf8;
2878 if (! prog->anchored_substr) {
2879 if (! to_byte_substr(prog)) {
2880 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2883 must = prog->anchored_substr;
2885 back_max = back_min = prog->anchored_offset;
2888 if (! prog->float_utf8) {
2889 to_utf8_substr(prog);
2891 must = prog->float_utf8;
2894 if (! prog->float_substr) {
2895 if (! to_byte_substr(prog)) {
2896 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2899 must = prog->float_substr;
2901 back_max = prog->float_max_offset;
2902 back_min = prog->float_min_offset;
2908 last = HOP3c(strend, /* Cannot start after this */
2909 -(SSize_t)(CHR_SVLEN(must)
2910 - (SvTAIL(must) != 0) + back_min), strbeg);
2912 if (s > reginfo->strbeg)
2913 last1 = HOPc(s, -1);
2915 last1 = s - 1; /* bogus */
2917 /* XXXX check_substr already used to find "s", can optimize if
2918 check_substr==must. */
2920 strend = HOPc(strend, -dontbother);
2921 while ( (s <= last) &&
2922 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
2923 (unsigned char*)strend, must,
2924 multiline ? FBMrf_MULTILINE : 0)) ) {
2925 DEBUG_EXECUTE_r( did_match = 1 );
2926 if (HOPc(s, -back_max) > last1) {
2927 last1 = HOPc(s, -back_min);
2928 s = HOPc(s, -back_max);
2931 char * const t = (last1 >= reginfo->strbeg)
2932 ? HOPc(last1, 1) : last1 + 1;
2934 last1 = HOPc(s, -back_min);
2938 while (s <= last1) {
2939 if (regtry(reginfo, &s))
2942 s++; /* to break out of outer loop */
2949 while (s <= last1) {
2950 if (regtry(reginfo, &s))
2956 DEBUG_EXECUTE_r(if (!did_match) {
2957 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2958 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2959 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2960 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2961 ? "anchored" : "floating"),
2962 quoted, RE_SV_TAIL(must));
2966 else if ( (c = progi->regstclass) ) {
2968 const OPCODE op = OP(progi->regstclass);
2969 /* don't bother with what can't match */
2970 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2971 strend = HOPc(strend, -(minlen - 1));
2974 SV * const prop = sv_newmortal();
2975 regprop(prog, prop, c, reginfo);
2977 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2979 PerlIO_printf(Perl_debug_log,
2980 "Matching stclass %.*s against %s (%d bytes)\n",
2981 (int)SvCUR(prop), SvPVX_const(prop),
2982 quoted, (int)(strend - s));
2985 if (find_byclass(prog, c, s, strend, reginfo))
2987 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2991 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2999 if (! prog->float_utf8) {
3000 to_utf8_substr(prog);
3002 float_real = prog->float_utf8;
3005 if (! prog->float_substr) {
3006 if (! to_byte_substr(prog)) {
3007 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3010 float_real = prog->float_substr;
3013 little = SvPV_const(float_real, len);
3014 if (SvTAIL(float_real)) {
3015 /* This means that float_real contains an artificial \n on
3016 * the end due to the presence of something like this:
3017 * /foo$/ where we can match both "foo" and "foo\n" at the
3018 * end of the string. So we have to compare the end of the
3019 * string first against the float_real without the \n and
3020 * then against the full float_real with the string. We
3021 * have to watch out for cases where the string might be
3022 * smaller than the float_real or the float_real without
3024 char *checkpos= strend - len;
3026 PerlIO_printf(Perl_debug_log,
3027 "%sChecking for float_real.%s\n",
3028 PL_colors[4], PL_colors[5]));
3029 if (checkpos + 1 < strbeg) {
3030 /* can't match, even if we remove the trailing \n
3031 * string is too short to match */
3033 PerlIO_printf(Perl_debug_log,
3034 "%sString shorter than required trailing substring, cannot match.%s\n",
3035 PL_colors[4], PL_colors[5]));
3037 } else if (memEQ(checkpos + 1, little, len - 1)) {
3038 /* can match, the end of the string matches without the
3040 last = checkpos + 1;
3041 } else if (checkpos < strbeg) {
3042 /* cant match, string is too short when the "\n" is
3045 PerlIO_printf(Perl_debug_log,
3046 "%sString does not contain required trailing substring, cannot match.%s\n",
3047 PL_colors[4], PL_colors[5]));
3049 } else if (!multiline) {
3050 /* non multiline match, so compare with the "\n" at the
3051 * end of the string */
3052 if (memEQ(checkpos, little, len)) {
3056 PerlIO_printf(Perl_debug_log,
3057 "%sString does not contain required trailing substring, cannot match.%s\n",
3058 PL_colors[4], PL_colors[5]));
3062 /* multiline match, so we have to search for a place
3063 * where the full string is located */
3069 last = rninstr(s, strend, little, little + len);
3071 last = strend; /* matching "$" */
3074 /* at one point this block contained a comment which was
3075 * probably incorrect, which said that this was a "should not
3076 * happen" case. Even if it was true when it was written I am
3077 * pretty sure it is not anymore, so I have removed the comment
3078 * and replaced it with this one. Yves */
3080 PerlIO_printf(Perl_debug_log,
3081 "String does not contain required substring, cannot match.\n"
3085 dontbother = strend - last + prog->float_min_offset;
3087 if (minlen && (dontbother < minlen))
3088 dontbother = minlen - 1;
3089 strend -= dontbother; /* this one's always in bytes! */
3090 /* We don't know much -- general case. */
3093 if (regtry(reginfo, &s))
3102 if (regtry(reginfo, &s))
3104 } while (s++ < strend);
3112 /* s/// doesn't like it if $& is earlier than where we asked it to
3113 * start searching (which can happen on something like /.\G/) */
3114 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3115 && (prog->offs[0].start < stringarg - strbeg))
3117 /* this should only be possible under \G */
3118 assert(prog->intflags & PREGf_GPOS_SEEN);
3119 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3120 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3126 PerlIO_printf(Perl_debug_log,
3127 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3134 /* clean up; this will trigger destructors that will free all slabs
3135 * above the current one, and cleanup the regmatch_info_aux
3136 * and regmatch_info_aux_eval sructs */
3138 LEAVE_SCOPE(oldsave);
3140 if (RXp_PAREN_NAMES(prog))
3141 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3143 RX_MATCH_UTF8_set(rx, utf8_target);
3145 /* make sure $`, $&, $', and $digit will work later */
3146 if ( !(flags & REXEC_NOT_FIRST) )
3147 S_reg_set_capture_string(aTHX_ rx,
3148 strbeg, reginfo->strend,
3149 sv, flags, utf8_target);
3154 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3155 PL_colors[4], PL_colors[5]));
3157 /* clean up; this will trigger destructors that will free all slabs
3158 * above the current one, and cleanup the regmatch_info_aux
3159 * and regmatch_info_aux_eval sructs */
3161 LEAVE_SCOPE(oldsave);
3164 /* we failed :-( roll it back */
3165 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3166 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3171 Safefree(prog->offs);
3178 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3179 * Do inc before dec, in case old and new rex are the same */
3180 #define SET_reg_curpm(Re2) \
3181 if (reginfo->info_aux_eval) { \
3182 (void)ReREFCNT_inc(Re2); \
3183 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3184 PM_SETRE((PL_reg_curpm), (Re2)); \
3189 - regtry - try match at specific point
3191 STATIC I32 /* 0 failure, 1 success */
3192 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3195 REGEXP *const rx = reginfo->prog;
3196 regexp *const prog = ReANY(rx);
3198 RXi_GET_DECL(prog,progi);
3199 GET_RE_DEBUG_FLAGS_DECL;
3201 PERL_ARGS_ASSERT_REGTRY;
3203 reginfo->cutpoint=NULL;
3205 prog->offs[0].start = *startposp - reginfo->strbeg;
3206 prog->lastparen = 0;
3207 prog->lastcloseparen = 0;
3209 /* XXXX What this code is doing here?!!! There should be no need
3210 to do this again and again, prog->lastparen should take care of
3213 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3214 * Actually, the code in regcppop() (which Ilya may be meaning by
3215 * prog->lastparen), is not needed at all by the test suite
3216 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3217 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3218 * Meanwhile, this code *is* needed for the
3219 * above-mentioned test suite tests to succeed. The common theme
3220 * on those tests seems to be returning null fields from matches.
3221 * --jhi updated by dapm */
3223 if (prog->nparens) {
3224 regexp_paren_pair *pp = prog->offs;
3226 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3234 result = regmatch(reginfo, *startposp, progi->program + 1);
3236 prog->offs[0].end = result;
3239 if (reginfo->cutpoint)
3240 *startposp= reginfo->cutpoint;
3241 REGCP_UNWIND(lastcp);
3246 #define sayYES goto yes
3247 #define sayNO goto no
3248 #define sayNO_SILENT goto no_silent
3250 /* we dont use STMT_START/END here because it leads to
3251 "unreachable code" warnings, which are bogus, but distracting. */
3252 #define CACHEsayNO \
3253 if (ST.cache_mask) \
3254 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3257 /* this is used to determine how far from the left messages like
3258 'failed...' are printed. It should be set such that messages
3259 are inline with the regop output that created them.
3261 #define REPORT_CODE_OFF 32
3264 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3265 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3266 #define CHRTEST_NOT_A_CP_1 -999
3267 #define CHRTEST_NOT_A_CP_2 -998
3269 /* grab a new slab and return the first slot in it */
3271 STATIC regmatch_state *
3274 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3277 regmatch_slab *s = PL_regmatch_slab->next;
3279 Newx(s, 1, regmatch_slab);
3280 s->prev = PL_regmatch_slab;
3282 PL_regmatch_slab->next = s;
3284 PL_regmatch_slab = s;
3285 return SLAB_FIRST(s);
3289 /* push a new state then goto it */
3291 #define PUSH_STATE_GOTO(state, node, input) \
3292 pushinput = input; \
3294 st->resume_state = state; \
3297 /* push a new state with success backtracking, then goto it */
3299 #define PUSH_YES_STATE_GOTO(state, node, input) \
3300 pushinput = input; \
3302 st->resume_state = state; \
3303 goto push_yes_state;
3310 regmatch() - main matching routine
3312 This is basically one big switch statement in a loop. We execute an op,
3313 set 'next' to point the next op, and continue. If we come to a point which
3314 we may need to backtrack to on failure such as (A|B|C), we push a
3315 backtrack state onto the backtrack stack. On failure, we pop the top
3316 state, and re-enter the loop at the state indicated. If there are no more
3317 states to pop, we return failure.
3319 Sometimes we also need to backtrack on success; for example /A+/, where
3320 after successfully matching one A, we need to go back and try to
3321 match another one; similarly for lookahead assertions: if the assertion
3322 completes successfully, we backtrack to the state just before the assertion
3323 and then carry on. In these cases, the pushed state is marked as
3324 'backtrack on success too'. This marking is in fact done by a chain of
3325 pointers, each pointing to the previous 'yes' state. On success, we pop to
3326 the nearest yes state, discarding any intermediate failure-only states.
3327 Sometimes a yes state is pushed just to force some cleanup code to be
3328 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3329 it to free the inner regex.
3331 Note that failure backtracking rewinds the cursor position, while
3332 success backtracking leaves it alone.
3334 A pattern is complete when the END op is executed, while a subpattern
3335 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3336 ops trigger the "pop to last yes state if any, otherwise return true"
3339 A common convention in this function is to use A and B to refer to the two
3340 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3341 the subpattern to be matched possibly multiple times, while B is the entire
3342 rest of the pattern. Variable and state names reflect this convention.
3344 The states in the main switch are the union of ops and failure/success of
3345 substates associated with with that op. For example, IFMATCH is the op
3346 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3347 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3348 successfully matched A and IFMATCH_A_fail is a state saying that we have
3349 just failed to match A. Resume states always come in pairs. The backtrack
3350 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3351 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3352 on success or failure.
3354 The struct that holds a backtracking state is actually a big union, with
3355 one variant for each major type of op. The variable st points to the
3356 top-most backtrack struct. To make the code clearer, within each
3357 block of code we #define ST to alias the relevant union.
3359 Here's a concrete example of a (vastly oversimplified) IFMATCH
3365 #define ST st->u.ifmatch
3367 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3368 ST.foo = ...; // some state we wish to save
3370 // push a yes backtrack state with a resume value of
3371 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3373 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3376 case IFMATCH_A: // we have successfully executed A; now continue with B
3378 bar = ST.foo; // do something with the preserved value
3381 case IFMATCH_A_fail: // A failed, so the assertion failed
3382 ...; // do some housekeeping, then ...
3383 sayNO; // propagate the failure
3390 For any old-timers reading this who are familiar with the old recursive
3391 approach, the code above is equivalent to:
3393 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3402 ...; // do some housekeeping, then ...
3403 sayNO; // propagate the failure
3406 The topmost backtrack state, pointed to by st, is usually free. If you
3407 want to claim it, populate any ST.foo fields in it with values you wish to
3408 save, then do one of
3410 PUSH_STATE_GOTO(resume_state, node, newinput);
3411 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3413 which sets that backtrack state's resume value to 'resume_state', pushes a
3414 new free entry to the top of the backtrack stack, then goes to 'node'.
3415 On backtracking, the free slot is popped, and the saved state becomes the
3416 new free state. An ST.foo field in this new top state can be temporarily
3417 accessed to retrieve values, but once the main loop is re-entered, it
3418 becomes available for reuse.
3420 Note that the depth of the backtrack stack constantly increases during the
3421 left-to-right execution of the pattern, rather than going up and down with
3422 the pattern nesting. For example the stack is at its maximum at Z at the
3423 end of the pattern, rather than at X in the following:
3425 /(((X)+)+)+....(Y)+....Z/
3427 The only exceptions to this are lookahead/behind assertions and the cut,
3428 (?>A), which pop all the backtrack states associated with A before
3431 Backtrack state structs are allocated in slabs of about 4K in size.
3432 PL_regmatch_state and st always point to the currently active state,
3433 and PL_regmatch_slab points to the slab currently containing
3434 PL_regmatch_state. The first time regmatch() is called, the first slab is
3435 allocated, and is never freed until interpreter destruction. When the slab
3436 is full, a new one is allocated and chained to the end. At exit from
3437 regmatch(), slabs allocated since entry are freed.
3442 #define DEBUG_STATE_pp(pp) \
3444 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3445 PerlIO_printf(Perl_debug_log, \
3446 " %*s"pp" %s%s%s%s%s\n", \
3448 PL_reg_name[st->resume_state], \
3449 ((st==yes_state||st==mark_state) ? "[" : ""), \
3450 ((st==yes_state) ? "Y" : ""), \
3451 ((st==mark_state) ? "M" : ""), \
3452 ((st==yes_state||st==mark_state) ? "]" : "") \
3457 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3462 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3463 const char *start, const char *end, const char *blurb)
3465 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3467 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3472 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3473 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3475 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3476 start, end - start, 60);
3478 PerlIO_printf(Perl_debug_log,
3479 "%s%s REx%s %s against %s\n",
3480 PL_colors[4], blurb, PL_colors[5], s0, s1);
3482 if (utf8_target||utf8_pat)
3483 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3484 utf8_pat ? "pattern" : "",
3485 utf8_pat && utf8_target ? " and " : "",
3486 utf8_target ? "string" : ""
3492 S_dump_exec_pos(pTHX_ const char *locinput,
3493 const regnode *scan,
3494 const char *loc_regeol,
3495 const char *loc_bostr,
3496 const char *loc_reg_starttry,
3497 const bool utf8_target)
3499 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3500 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3501 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3502 /* The part of the string before starttry has one color
3503 (pref0_len chars), between starttry and current
3504 position another one (pref_len - pref0_len chars),
3505 after the current position the third one.
3506 We assume that pref0_len <= pref_len, otherwise we
3507 decrease pref0_len. */
3508 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3509 ? (5 + taill) - l : locinput - loc_bostr;
3512 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3514 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3516 pref0_len = pref_len - (locinput - loc_reg_starttry);
3517 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3518 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3519 ? (5 + taill) - pref_len : loc_regeol - locinput);
3520 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3524 if (pref0_len > pref_len)
3525 pref0_len = pref_len;
3527 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3529 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3530 (locinput - pref_len),pref0_len, 60, 4, 5);
3532 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3533 (locinput - pref_len + pref0_len),
3534 pref_len - pref0_len, 60, 2, 3);
3536 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3537 locinput, loc_regeol - locinput, 10, 0, 1);
3539 const STRLEN tlen=len0+len1+len2;
3540 PerlIO_printf(Perl_debug_log,
3541 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3542 (IV)(locinput - loc_bostr),
3545 (docolor ? "" : "> <"),
3547 (int)(tlen > 19 ? 0 : 19 - tlen),
3554 /* reg_check_named_buff_matched()
3555 * Checks to see if a named buffer has matched. The data array of
3556 * buffer numbers corresponding to the buffer is expected to reside
3557 * in the regexp->data->data array in the slot stored in the ARG() of
3558 * node involved. Note that this routine doesn't actually care about the
3559 * name, that information is not preserved from compilation to execution.
3560 * Returns the index of the leftmost defined buffer with the given name
3561 * or 0 if non of the buffers matched.
3564 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3567 RXi_GET_DECL(rex,rexi);
3568 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3569 I32 *nums=(I32*)SvPVX(sv_dat);
3571 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3573 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3574 if ((I32)rex->lastparen >= nums[n] &&
3575 rex->offs[nums[n]].end != -1)
3585 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3586 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3588 /* This function determines if there are one or two characters that match
3589 * the first character of the passed-in EXACTish node <text_node>, and if
3590 * so, returns them in the passed-in pointers.
3592 * If it determines that no possible character in the target string can
3593 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3594 * the first character in <text_node> requires UTF-8 to represent, and the
3595 * target string isn't in UTF-8.)
3597 * If there are more than two characters that could match the beginning of
3598 * <text_node>, or if more context is required to determine a match or not,
3599 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3601 * The motiviation behind this function is to allow the caller to set up
3602 * tight loops for matching. If <text_node> is of type EXACT, there is
3603 * only one possible character that can match its first character, and so
3604 * the situation is quite simple. But things get much more complicated if
3605 * folding is involved. It may be that the first character of an EXACTFish
3606 * node doesn't participate in any possible fold, e.g., punctuation, so it
3607 * can be matched only by itself. The vast majority of characters that are
3608 * in folds match just two things, their lower and upper-case equivalents.
3609 * But not all are like that; some have multiple possible matches, or match
3610 * sequences of more than one character. This function sorts all that out.
3612 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3613 * loop of trying to match A*, we know we can't exit where the thing
3614 * following it isn't a B. And something can't be a B unless it is the
3615 * beginning of B. By putting a quick test for that beginning in a tight
3616 * loop, we can rule out things that can't possibly be B without having to
3617 * break out of the loop, thus avoiding work. Similarly, if A is a single
3618 * character, we can make a tight loop matching A*, using the outputs of
3621 * If the target string to match isn't in UTF-8, and there aren't
3622 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3623 * the one or two possible octets (which are characters in this situation)
3624 * that can match. In all cases, if there is only one character that can
3625 * match, *<c1p> and *<c2p> will be identical.
3627 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3628 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3629 * can match the beginning of <text_node>. They should be declared with at
3630 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3631 * undefined what these contain.) If one or both of the buffers are
3632 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3633 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3634 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3635 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3636 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3638 const bool utf8_target = reginfo->is_utf8_target;
3640 UV c1 = CHRTEST_NOT_A_CP_1;
3641 UV c2 = CHRTEST_NOT_A_CP_2;
3642 bool use_chrtest_void = FALSE;
3643 const bool is_utf8_pat = reginfo->is_utf8_pat;
3645 /* Used when we have both utf8 input and utf8 output, to avoid converting
3646 * to/from code points */
3647 bool utf8_has_been_setup = FALSE;
3651 U8 *pat = (U8*)STRING(text_node);
3652 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3654 if (OP(text_node) == EXACT) {
3656 /* In an exact node, only one thing can be matched, that first
3657 * character. If both the pat and the target are UTF-8, we can just
3658 * copy the input to the output, avoiding finding the code point of
3663 else if (utf8_target) {
3664 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3665 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3666 utf8_has_been_setup = TRUE;
3669 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3672 else { /* an EXACTFish node */
3673 U8 *pat_end = pat + STR_LEN(text_node);
3675 /* An EXACTFL node has at least some characters unfolded, because what
3676 * they match is not known until now. So, now is the time to fold
3677 * the first few of them, as many as are needed to determine 'c1' and
3678 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3679 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3680 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3681 * need to fold as many characters as a single character can fold to,
3682 * so that later we can check if the first ones are such a multi-char
3683 * fold. But, in such a pattern only locale-problematic characters
3684 * aren't folded, so we can skip this completely if the first character
3685 * in the node isn't one of the tricky ones */
3686 if (OP(text_node) == EXACTFL) {
3688 if (! is_utf8_pat) {
3689 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3691 folded[0] = folded[1] = 's';
3693 pat_end = folded + 2;
3696 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3701 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3703 *(d++) = (U8) toFOLD_LC(*s);
3708 _to_utf8_fold_flags(s,
3711 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
3722 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
3723 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
3725 /* Multi-character folds require more context to sort out. Also
3726 * PL_utf8_foldclosures used below doesn't handle them, so have to
3727 * be handled outside this routine */
3728 use_chrtest_void = TRUE;
3730 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
3731 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
3733 /* Load the folds hash, if not already done */
3735 if (! PL_utf8_foldclosures) {
3736 _load_PL_utf8_foldclosures();
3739 /* The fold closures data structure is a hash with the keys
3740 * being the UTF-8 of every character that is folded to, like
3741 * 'k', and the values each an array of all code points that
3742 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
3743 * Multi-character folds are not included */
3744 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
3749 /* Not found in the hash, therefore there are no folds
3750 * containing it, so there is only a single character that
3754 else { /* Does participate in folds */
3755 AV* list = (AV*) *listp;
3756 if (av_tindex(list) != 1) {
3758 /* If there aren't exactly two folds to this, it is
3759 * outside the scope of this function */
3760 use_chrtest_void = TRUE;
3762 else { /* There are two. Get them */
3763 SV** c_p = av_fetch(list, 0, FALSE);
3765 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3769 c_p = av_fetch(list, 1, FALSE);
3771 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3775 /* Folds that cross the 255/256 boundary are forbidden
3776 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
3777 * one is ASCIII. Since the pattern character is above
3778 * 255, and its only other match is below 256, the only
3779 * legal match will be to itself. We have thrown away
3780 * the original, so have to compute which is the one
3782 if ((c1 < 256) != (c2 < 256)) {
3783 if ((OP(text_node) == EXACTFL
3784 && ! IN_UTF8_CTYPE_LOCALE)
3785 || ((OP(text_node) == EXACTFA
3786 || OP(text_node) == EXACTFA_NO_TRIE)
3787 && (isASCII(c1) || isASCII(c2))))
3800 else /* Here, c1 is <= 255 */
3802 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
3803 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
3804 && ((OP(text_node) != EXACTFA
3805 && OP(text_node) != EXACTFA_NO_TRIE)
3808 /* Here, there could be something above Latin1 in the target
3809 * which folds to this character in the pattern. All such
3810 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
3811 * than two characters involved in their folds, so are outside
3812 * the scope of this function */
3813 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
3814 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
3817 use_chrtest_void = TRUE;
3820 else { /* Here nothing above Latin1 can fold to the pattern
3822 switch (OP(text_node)) {
3824 case EXACTFL: /* /l rules */
3825 c2 = PL_fold_locale[c1];
3828 case EXACTF: /* This node only generated for non-utf8
3830 assert(! is_utf8_pat);
3831 if (! utf8_target) { /* /d rules */
3836 /* /u rules for all these. This happens to work for
3837 * EXACTFA as nothing in Latin1 folds to ASCII */
3838 case EXACTFA_NO_TRIE: /* This node only generated for
3839 non-utf8 patterns */
3840 assert(! is_utf8_pat);
3845 c2 = PL_fold_latin1[c1];
3849 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
3850 assert(0); /* NOTREACHED */
3856 /* Here have figured things out. Set up the returns */
3857 if (use_chrtest_void) {
3858 *c2p = *c1p = CHRTEST_VOID;
3860 else if (utf8_target) {
3861 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
3862 uvchr_to_utf8(c1_utf8, c1);
3863 uvchr_to_utf8(c2_utf8, c2);
3866 /* Invariants are stored in both the utf8 and byte outputs; Use
3867 * negative numbers otherwise for the byte ones. Make sure that the
3868 * byte ones are the same iff the utf8 ones are the same */
3869 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
3870 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
3873 ? CHRTEST_NOT_A_CP_1
3874 : CHRTEST_NOT_A_CP_2;
3876 else if (c1 > 255) {
3877 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
3882 *c1p = *c2p = c2; /* c2 is the only representable value */
3884 else { /* c1 is representable; see about c2 */
3886 *c2p = (c2 < 256) ? c2 : c1;
3892 /* returns -1 on failure, $+[0] on success */
3894 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
3896 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3900 const bool utf8_target = reginfo->is_utf8_target;
3901 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3902 REGEXP *rex_sv = reginfo->prog;
3903 regexp *rex = ReANY(rex_sv);
3904 RXi_GET_DECL(rex,rexi);
3905 /* the current state. This is a cached copy of PL_regmatch_state */
3907 /* cache heavy used fields of st in registers */
3910 U32 n = 0; /* general value; init to avoid compiler warning */
3911 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
3912 char *locinput = startpos;
3913 char *pushinput; /* where to continue after a PUSH */
3914 I32 nextchr; /* is always set to UCHARAT(locinput) */
3916 bool result = 0; /* return value of S_regmatch */
3917 int depth = 0; /* depth of backtrack stack */
3918 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3919 const U32 max_nochange_depth =
3920 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3921 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3922 regmatch_state *yes_state = NULL; /* state to pop to on success of
3924 /* mark_state piggy backs on the yes_state logic so that when we unwind
3925 the stack on success we can update the mark_state as we go */
3926 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3927 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3928 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3930 bool no_final = 0; /* prevent failure from backtracking? */
3931 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3932 char *startpoint = locinput;
3933 SV *popmark = NULL; /* are we looking for a mark? */
3934 SV *sv_commit = NULL; /* last mark name seen in failure */
3935 SV *sv_yes_mark = NULL; /* last mark name we have seen
3936 during a successful match */
3937 U32 lastopen = 0; /* last open we saw */
3938 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3939 SV* const oreplsv = GvSVn(PL_replgv);
3940 /* these three flags are set by various ops to signal information to
3941 * the very next op. They have a useful lifetime of exactly one loop
3942 * iteration, and are not preserved or restored by state pushes/pops
3944 bool sw = 0; /* the condition value in (?(cond)a|b) */
3945 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3946 int logical = 0; /* the following EVAL is:
3950 or the following IFMATCH/UNLESSM is:
3951 false: plain (?=foo)
3952 true: used as a condition: (?(?=foo))
3954 PAD* last_pad = NULL;
3956 I32 gimme = G_SCALAR;
3957 CV *caller_cv = NULL; /* who called us */
3958 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
3959 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
3960 U32 maxopenparen = 0; /* max '(' index seen so far */
3961 int to_complement; /* Invert the result? */
3962 _char_class_number classnum;
3963 bool is_utf8_pat = reginfo->is_utf8_pat;
3966 GET_RE_DEBUG_FLAGS_DECL;
3969 /* protect against undef(*^R) */
3970 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
3972 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3973 multicall_oldcatch = 0;
3974 multicall_cv = NULL;
3976 PERL_UNUSED_VAR(multicall_cop);
3977 PERL_UNUSED_VAR(newsp);
3980 PERL_ARGS_ASSERT_REGMATCH;
3982 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3983 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3986 st = PL_regmatch_state;
3988 /* Note that nextchr is a byte even in UTF */
3991 while (scan != NULL) {
3994 SV * const prop = sv_newmortal();
3995 regnode *rnext=regnext(scan);
3996 DUMP_EXEC_POS( locinput, scan, utf8_target );
3997 regprop(rex, prop, scan, reginfo);
3999 PerlIO_printf(Perl_debug_log,
4000 "%3"IVdf":%*s%s(%"IVdf")\n",
4001 (IV)(scan - rexi->program), depth*2, "",
4003 (PL_regkind[OP(scan)] == END || !rnext) ?
4004 0 : (IV)(rnext - rexi->program));
4007 next = scan + NEXT_OFF(scan);
4010 state_num = OP(scan);
4012 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
4017 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
4019 switch (state_num) {
4020 case BOL: /* /^../ */
4021 case SBOL: /* /^../s */
4022 if (locinput == reginfo->strbeg)
4026 case MBOL: /* /^../m */
4027 if (locinput == reginfo->strbeg ||
4028 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4035 if (locinput == reginfo->ganch)
4039 case KEEPS: /* \K */
4040 /* update the startpoint */
4041 st->u.keeper.val = rex->offs[0].start;
4042 rex->offs[0].start = locinput - reginfo->strbeg;
4043 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4044 assert(0); /*NOTREACHED*/
4045 case KEEPS_next_fail:
4046 /* rollback the start point change */
4047 rex->offs[0].start = st->u.keeper.val;
4049 assert(0); /*NOTREACHED*/
4051 case MEOL: /* /..$/m */
4052 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4056 case EOL: /* /..$/ */
4058 case SEOL: /* /..$/s */
4059 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4061 if (reginfo->strend - locinput > 1)
4066 if (!NEXTCHR_IS_EOS)
4070 case SANY: /* /./s */
4073 goto increment_locinput;
4081 case REG_ANY: /* /./ */
4082 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4084 goto increment_locinput;
4088 #define ST st->u.trie
4089 case TRIEC: /* (ab|cd) with known charclass */
4090 /* In this case the charclass data is available inline so
4091 we can fail fast without a lot of extra overhead.
4093 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
4095 PerlIO_printf(Perl_debug_log,
4096 "%*s %sfailed to match trie start class...%s\n",
4097 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4100 assert(0); /* NOTREACHED */
4103 case TRIE: /* (ab|cd) */
4104 /* the basic plan of execution of the trie is:
4105 * At the beginning, run though all the states, and
4106 * find the longest-matching word. Also remember the position
4107 * of the shortest matching word. For example, this pattern:
4110 * when matched against the string "abcde", will generate
4111 * accept states for all words except 3, with the longest
4112 * matching word being 4, and the shortest being 2 (with
4113 * the position being after char 1 of the string).
4115 * Then for each matching word, in word order (i.e. 1,2,4,5),
4116 * we run the remainder of the pattern; on each try setting
4117 * the current position to the character following the word,
4118 * returning to try the next word on failure.
4120 * We avoid having to build a list of words at runtime by
4121 * using a compile-time structure, wordinfo[].prev, which
4122 * gives, for each word, the previous accepting word (if any).
4123 * In the case above it would contain the mappings 1->2, 2->0,
4124 * 3->0, 4->5, 5->1. We can use this table to generate, from
4125 * the longest word (4 above), a list of all words, by
4126 * following the list of prev pointers; this gives us the
4127 * unordered list 4,5,1,2. Then given the current word we have
4128 * just tried, we can go through the list and find the
4129 * next-biggest word to try (so if we just failed on word 2,
4130 * the next in the list is 4).
4132 * Since at runtime we don't record the matching position in
4133 * the string for each word, we have to work that out for
4134 * each word we're about to process. The wordinfo table holds
4135 * the character length of each word; given that we recorded
4136 * at the start: the position of the shortest word and its
4137 * length in chars, we just need to move the pointer the
4138 * difference between the two char lengths. Depending on
4139 * Unicode status and folding, that's cheap or expensive.
4141 * This algorithm is optimised for the case where are only a
4142 * small number of accept states, i.e. 0,1, or maybe 2.
4143 * With lots of accepts states, and having to try all of them,
4144 * it becomes quadratic on number of accept states to find all
4149 /* what type of TRIE am I? (utf8 makes this contextual) */
4150 DECL_TRIE_TYPE(scan);
4152 /* what trie are we using right now */
4153 reg_trie_data * const trie
4154 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
4155 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
4156 U32 state = trie->startstate;
4159 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
4161 if (trie->states[ state ].wordnum) {
4163 PerlIO_printf(Perl_debug_log,
4164 "%*s %smatched empty string...%s\n",
4165 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4171 PerlIO_printf(Perl_debug_log,
4172 "%*s %sfailed to match trie start class...%s\n",
4173 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4180 U8 *uc = ( U8* )locinput;
4184 U8 *uscan = (U8*)NULL;
4185 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
4186 U32 charcount = 0; /* how many input chars we have matched */
4187 U32 accepted = 0; /* have we seen any accepting states? */
4189 ST.jump = trie->jump;
4192 ST.longfold = FALSE; /* char longer if folded => it's harder */
4195 /* fully traverse the TRIE; note the position of the
4196 shortest accept state and the wordnum of the longest
4199 while ( state && uc <= (U8*)(reginfo->strend) ) {
4200 U32 base = trie->states[ state ].trans.base;
4204 wordnum = trie->states[ state ].wordnum;
4206 if (wordnum) { /* it's an accept state */
4209 /* record first match position */
4211 ST.firstpos = (U8*)locinput;
4216 ST.firstchars = charcount;
4219 if (!ST.nextword || wordnum < ST.nextword)
4220 ST.nextword = wordnum;
4221 ST.topword = wordnum;
4224 DEBUG_TRIE_EXECUTE_r({
4225 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
4226 PerlIO_printf( Perl_debug_log,
4227 "%*s %sState: %4"UVxf" Accepted: %c ",
4228 2+depth * 2, "", PL_colors[4],
4229 (UV)state, (accepted ? 'Y' : 'N'));
4232 /* read a char and goto next state */
4233 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
4235 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
4236 uscan, len, uvc, charid, foldlen,
4243 base + charid - 1 - trie->uniquecharcount)) >= 0)
4245 && ((U32)offset < trie->lasttrans)
4246 && trie->trans[offset].check == state)
4248 state = trie->trans[offset].next;
4259 DEBUG_TRIE_EXECUTE_r(
4260 PerlIO_printf( Perl_debug_log,
4261 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
4262 charid, uvc, (UV)state, PL_colors[5] );
4268 /* calculate total number of accept states */
4273 w = trie->wordinfo[w].prev;
4276 ST.accepted = accepted;
4280 PerlIO_printf( Perl_debug_log,
4281 "%*s %sgot %"IVdf" possible matches%s\n",
4282 REPORT_CODE_OFF + depth * 2, "",
4283 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
4285 goto trie_first_try; /* jump into the fail handler */
4287 assert(0); /* NOTREACHED */
4289 case TRIE_next_fail: /* we failed - try next alternative */
4293 REGCP_UNWIND(ST.cp);
4294 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
4296 if (!--ST.accepted) {
4298 PerlIO_printf( Perl_debug_log,
4299 "%*s %sTRIE failed...%s\n",
4300 REPORT_CODE_OFF+depth*2, "",
4307 /* Find next-highest word to process. Note that this code
4308 * is O(N^2) per trie run (O(N) per branch), so keep tight */
4311 U16 const nextword = ST.nextword;
4312 reg_trie_wordinfo * const wordinfo
4313 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
4314 for (word=ST.topword; word; word=wordinfo[word].prev) {
4315 if (word > nextword && (!min || word < min))
4328 ST.lastparen = rex->lastparen;
4329 ST.lastcloseparen = rex->lastcloseparen;
4333 /* find start char of end of current word */
4335 U32 chars; /* how many chars to skip */
4336 reg_trie_data * const trie
4337 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
4339 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
4341 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
4346 /* the hard option - fold each char in turn and find
4347 * its folded length (which may be different */
4348 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
4356 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
4364 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
4369 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
4385 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
4386 ? ST.jump[ST.nextword]
4390 PerlIO_printf( Perl_debug_log,
4391 "%*s %sTRIE matched word #%d, continuing%s\n",
4392 REPORT_CODE_OFF+depth*2, "",
4399 if (ST.accepted > 1 || has_cutgroup) {
4400 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
4401 assert(0); /* NOTREACHED */
4403 /* only one choice left - just continue */
4405 AV *const trie_words
4406 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
4407 SV ** const tmp = av_fetch( trie_words,
4409 SV *sv= tmp ? sv_newmortal() : NULL;
4411 PerlIO_printf( Perl_debug_log,
4412 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
4413 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
4415 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
4416 PL_colors[0], PL_colors[1],
4417 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
4419 : "not compiled under -Dr",
4423 locinput = (char*)uc;
4424 continue; /* execute rest of RE */
4425 assert(0); /* NOTREACHED */
4429 case EXACT: { /* /abc/ */
4430 char *s = STRING(scan);
4432 if (utf8_target != is_utf8_pat) {
4433 /* The target and the pattern have differing utf8ness. */
4435 const char * const e = s + ln;
4438 /* The target is utf8, the pattern is not utf8.
4439 * Above-Latin1 code points can't match the pattern;
4440 * invariants match exactly, and the other Latin1 ones need
4441 * to be downgraded to a single byte in order to do the
4442 * comparison. (If we could be confident that the target
4443 * is not malformed, this could be refactored to have fewer
4444 * tests by just assuming that if the first bytes match, it
4445 * is an invariant, but there are tests in the test suite
4446 * dealing with (??{...}) which violate this) */
4448 if (l >= reginfo->strend
4449 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
4453 if (UTF8_IS_INVARIANT(*(U8*)l)) {
4460 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
4470 /* The target is not utf8, the pattern is utf8. */
4472 if (l >= reginfo->strend
4473 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
4477 if (UTF8_IS_INVARIANT(*(U8*)s)) {
4484 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
4496 /* The target and the pattern have the same utf8ness. */
4497 /* Inline the first character, for speed. */
4498 if (reginfo->strend - locinput < ln
4499 || UCHARAT(s) != nextchr
4500 || (ln > 1 && memNE(s, locinput, ln)))
4509 case EXACTFL: { /* /abc/il */
4511 const U8 * fold_array;
4513 U32 fold_utf8_flags;
4515 folder = foldEQ_locale;
4516 fold_array = PL_fold_locale;
4517 fold_utf8_flags = FOLDEQ_LOCALE;
4520 case EXACTFU_SS: /* /\x{df}/iu */
4521 case EXACTFU: /* /abc/iu */
4522 folder = foldEQ_latin1;
4523 fold_array = PL_fold_latin1;
4524 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
4527 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
4529 assert(! is_utf8_pat);
4531 case EXACTFA: /* /abc/iaa */
4532 folder = foldEQ_latin1;
4533 fold_array = PL_fold_latin1;
4534 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4537 case EXACTF: /* /abc/i This node only generated for
4538 non-utf8 patterns */
4539 assert(! is_utf8_pat);
4541 fold_array = PL_fold;
4542 fold_utf8_flags = 0;
4550 || state_num == EXACTFU_SS
4551 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
4553 /* Either target or the pattern are utf8, or has the issue where
4554 * the fold lengths may differ. */
4555 const char * const l = locinput;
4556 char *e = reginfo->strend;
4558 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
4559 l, &e, 0, utf8_target, fold_utf8_flags))
4567 /* Neither the target nor the pattern are utf8 */
4568 if (UCHARAT(s) != nextchr
4570 && UCHARAT(s) != fold_array[nextchr])
4574 if (reginfo->strend - locinput < ln)
4576 if (ln > 1 && ! folder(s, locinput, ln))
4582 /* XXX Could improve efficiency by separating these all out using a
4583 * macro or in-line function. At that point regcomp.c would no longer
4584 * have to set the FLAGS fields of these */
4585 case BOUNDL: /* /\b/l */
4586 case NBOUNDL: /* /\B/l */
4587 case BOUND: /* /\b/ */
4588 case BOUNDU: /* /\b/u */
4589 case BOUNDA: /* /\b/a */
4590 case NBOUND: /* /\B/ */
4591 case NBOUNDU: /* /\B/u */
4592 case NBOUNDA: /* /\B/a */
4593 /* was last char in word? */
4595 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
4596 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
4598 if (locinput == reginfo->strbeg)
4601 const U8 * const r =
4602 reghop3((U8*)locinput, -1, (U8*)(reginfo->strbeg));
4604 ln = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,
4607 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
4608 ln = isWORDCHAR_uni(ln);
4612 LOAD_UTF8_CHARCLASS_ALNUM();
4613 n = swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)locinput,
4618 ln = isWORDCHAR_LC_uvchr(ln);
4619 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC_utf8((U8*)locinput);
4624 /* Here the string isn't utf8, or is utf8 and only ascii
4625 * characters are to match \w. In the latter case looking at
4626 * the byte just prior to the current one may be just the final
4627 * byte of a multi-byte character. This is ok. There are two
4629 * 1) it is a single byte character, and then the test is doing
4630 * just what it's supposed to.
4631 * 2) it is a multi-byte character, in which case the final
4632 * byte is never mistakable for ASCII, and so the test
4633 * will say it is not a word character, which is the
4634 * correct answer. */
4635 ln = (locinput != reginfo->strbeg) ?
4636 UCHARAT(locinput - 1) : '\n';
4637 switch (FLAGS(scan)) {
4638 case REGEX_UNICODE_CHARSET:
4639 ln = isWORDCHAR_L1(ln);
4640 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_L1(nextchr);
4642 case REGEX_LOCALE_CHARSET:
4643 ln = isWORDCHAR_LC(ln);
4644 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC(nextchr);
4646 case REGEX_DEPENDS_CHARSET:
4647 ln = isWORDCHAR(ln);
4648 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR(nextchr);
4650 case REGEX_ASCII_RESTRICTED_CHARSET:
4651 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
4652 ln = isWORDCHAR_A(ln);
4653 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_A(nextchr);
4656 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
4659 /* Note requires that all BOUNDs be lower than all NBOUNDs in
4661 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
4665 case ANYOF: /* /[abc]/ */
4669 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
4672 locinput += UTF8SKIP(locinput);
4675 if (!REGINCLASS(rex, scan, (U8*)locinput))
4681 /* The argument (FLAGS) to all the POSIX node types is the class number
4684 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
4688 case POSIXL: /* \w or [:punct:] etc. under /l */
4692 /* Use isFOO_lc() for characters within Latin1. (Note that
4693 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4694 * wouldn't be invariant) */
4695 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4696 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
4700 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4701 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
4702 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4703 *(locinput + 1))))))
4708 else { /* Here, must be an above Latin-1 code point */
4709 goto utf8_posix_not_eos;
4712 /* Here, must be utf8 */
4713 locinput += UTF8SKIP(locinput);
4716 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
4720 case POSIXD: /* \w or [:punct:] etc. under /d */
4726 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
4728 if (NEXTCHR_IS_EOS) {
4732 /* All UTF-8 variants match */
4733 if (! UTF8_IS_INVARIANT(nextchr)) {
4734 goto increment_locinput;
4740 case POSIXA: /* \w or [:punct:] etc. under /a */
4743 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
4744 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
4745 * character is a single byte */
4748 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
4754 /* Here we are either not in utf8, or we matched a utf8-invariant,
4755 * so the next char is the next byte */
4759 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
4763 case POSIXU: /* \w or [:punct:] etc. under /u */
4765 if (NEXTCHR_IS_EOS) {
4770 /* Use _generic_isCC() for characters within Latin1. (Note that
4771 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4772 * wouldn't be invariant) */
4773 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4774 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
4781 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4782 if (! (to_complement
4783 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4791 else { /* Handle above Latin-1 code points */
4792 classnum = (_char_class_number) FLAGS(scan);
4793 if (classnum < _FIRST_NON_SWASH_CC) {
4795 /* Here, uses a swash to find such code points. Load if if
4796 * not done already */
4797 if (! PL_utf8_swash_ptrs[classnum]) {
4798 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
4799 PL_utf8_swash_ptrs[classnum]
4800 = _core_swash_init("utf8",
4803 PL_XPosix_ptrs[classnum], &flags);
4805 if (! (to_complement
4806 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
4807 (U8 *) locinput, TRUE))))
4812 else { /* Here, uses macros to find above Latin-1 code points */
4814 case _CC_ENUM_SPACE: /* XXX would require separate
4815 code if we revert the change
4816 of \v matching this */
4817 case _CC_ENUM_PSXSPC:
4818 if (! (to_complement
4819 ^ cBOOL(is_XPERLSPACE_high(locinput))))
4824 case _CC_ENUM_BLANK:
4825 if (! (to_complement
4826 ^ cBOOL(is_HORIZWS_high(locinput))))
4831 case _CC_ENUM_XDIGIT:
4832 if (! (to_complement
4833 ^ cBOOL(is_XDIGIT_high(locinput))))
4838 case _CC_ENUM_VERTSPACE:
4839 if (! (to_complement
4840 ^ cBOOL(is_VERTWS_high(locinput))))
4845 default: /* The rest, e.g. [:cntrl:], can't match
4847 if (! to_complement) {
4853 locinput += UTF8SKIP(locinput);
4857 case CLUMP: /* Match \X: logical Unicode character. This is defined as
4858 a Unicode extended Grapheme Cluster */
4859 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
4860 extended Grapheme Cluster is:
4863 | Prepend* Begin Extend*
4866 Begin is: ( Special_Begin | ! Control )
4867 Special_Begin is: ( Regional-Indicator+ | Hangul-syllable )
4868 Extend is: ( Grapheme_Extend | Spacing_Mark )
4869 Control is: [ GCB_Control | CR | LF ]
4870 Hangul-syllable is: ( T+ | ( L* ( L | ( LVT | ( V | LV ) V* ) T* ) ))
4872 If we create a 'Regular_Begin' = Begin - Special_Begin, then
4875 Begin is ( Regular_Begin + Special Begin )
4877 It turns out that 98.4% of all Unicode code points match
4878 Regular_Begin. Doing it this way eliminates a table match in
4879 the previous implementation for almost all Unicode code points.
4881 There is a subtlety with Prepend* which showed up in testing.
4882 Note that the Begin, and only the Begin is required in:
4883 | Prepend* Begin Extend*
4884 Also, Begin contains '! Control'. A Prepend must be a
4885 '! Control', which means it must also be a Begin. What it
4886 comes down to is that if we match Prepend* and then find no
4887 suitable Begin afterwards, that if we backtrack the last
4888 Prepend, that one will be a suitable Begin.
4893 if (! utf8_target) {
4895 /* Match either CR LF or '.', as all the other possibilities
4897 locinput++; /* Match the . or CR */
4898 if (nextchr == '\r' /* And if it was CR, and the next is LF,
4900 && locinput < reginfo->strend
4901 && UCHARAT(locinput) == '\n')
4908 /* Utf8: See if is ( CR LF ); already know that locinput <
4909 * reginfo->strend, so locinput+1 is in bounds */
4910 if ( nextchr == '\r' && locinput+1 < reginfo->strend
4911 && UCHARAT(locinput + 1) == '\n')
4918 /* In case have to backtrack to beginning, then match '.' */
4919 char *starting = locinput;
4921 /* In case have to backtrack the last prepend */
4922 char *previous_prepend = NULL;
4924 LOAD_UTF8_CHARCLASS_GCB();
4926 /* Match (prepend)* */
4927 while (locinput < reginfo->strend
4928 && (len = is_GCB_Prepend_utf8(locinput)))
4930 previous_prepend = locinput;
4934 /* As noted above, if we matched a prepend character, but
4935 * the next thing won't match, back off the last prepend we
4936 * matched, as it is guaranteed to match the begin */
4937 if (previous_prepend
4938 && (locinput >= reginfo->strend
4939 || (! swash_fetch(PL_utf8_X_regular_begin,
4940 (U8*)locinput, utf8_target)
4941 && ! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)))
4944 locinput = previous_prepend;
4947 /* Note that here we know reginfo->strend > locinput, as we
4948 * tested that upon input to this switch case, and if we
4949 * moved locinput forward, we tested the result just above
4950 * and it either passed, or we backed off so that it will
4952 if (swash_fetch(PL_utf8_X_regular_begin,
4953 (U8*)locinput, utf8_target)) {
4954 locinput += UTF8SKIP(locinput);
4956 else if (! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)) {
4958 /* Here did not match the required 'Begin' in the
4959 * second term. So just match the very first
4960 * character, the '.' of the final term of the regex */
4961 locinput = starting + UTF8SKIP(starting);
4965 /* Here is a special begin. It can be composed of
4966 * several individual characters. One possibility is
4968 if ((len = is_GCB_RI_utf8(locinput))) {
4970 while (locinput < reginfo->strend
4971 && (len = is_GCB_RI_utf8(locinput)))
4975 } else if ((len = is_GCB_T_utf8(locinput))) {
4976 /* Another possibility is T+ */
4978 while (locinput < reginfo->strend
4979 && (len = is_GCB_T_utf8(locinput)))
4985 /* Here, neither RI+ nor T+; must be some other
4986 * Hangul. That means it is one of the others: L,
4987 * LV, LVT or V, and matches:
4988 * L* (L | LVT T* | V * V* T* | LV V* T*) */
4991 while (locinput < reginfo->strend
4992 && (len = is_GCB_L_utf8(locinput)))
4997 /* Here, have exhausted L*. If the next character
4998 * is not an LV, LVT nor V, it means we had to have
4999 * at least one L, so matches L+ in the original
5000 * equation, we have a complete hangul syllable.
5003 if (locinput < reginfo->strend
5004 && is_GCB_LV_LVT_V_utf8(locinput))
5006 /* Otherwise keep going. Must be LV, LVT or V.
5007 * See if LVT, by first ruling out V, then LV */
5008 if (! is_GCB_V_utf8(locinput)
5009 /* All but every TCount one is LV */
5010 && (valid_utf8_to_uvchr((U8 *) locinput,
5015 locinput += UTF8SKIP(locinput);
5018 /* Must be V or LV. Take it, then match
5020 locinput += UTF8SKIP(locinput);
5021 while (locinput < reginfo->strend
5022 && (len = is_GCB_V_utf8(locinput)))
5028 /* And any of LV, LVT, or V can be followed
5030 while (locinput < reginfo->strend
5031 && (len = is_GCB_T_utf8(locinput)))
5039 /* Match any extender */
5040 while (locinput < reginfo->strend
5041 && swash_fetch(PL_utf8_X_extend,
5042 (U8*)locinput, utf8_target))
5044 locinput += UTF8SKIP(locinput);
5048 if (locinput > reginfo->strend) sayNO;
5052 case NREFFL: /* /\g{name}/il */
5053 { /* The capture buffer cases. The ones beginning with N for the
5054 named buffers just convert to the equivalent numbered and
5055 pretend they were called as the corresponding numbered buffer
5057 /* don't initialize these in the declaration, it makes C++
5062 const U8 *fold_array;
5065 folder = foldEQ_locale;
5066 fold_array = PL_fold_locale;
5068 utf8_fold_flags = FOLDEQ_LOCALE;
5071 case NREFFA: /* /\g{name}/iaa */
5072 folder = foldEQ_latin1;
5073 fold_array = PL_fold_latin1;
5075 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5078 case NREFFU: /* /\g{name}/iu */
5079 folder = foldEQ_latin1;
5080 fold_array = PL_fold_latin1;
5082 utf8_fold_flags = 0;
5085 case NREFF: /* /\g{name}/i */
5087 fold_array = PL_fold;
5089 utf8_fold_flags = 0;
5092 case NREF: /* /\g{name}/ */
5096 utf8_fold_flags = 0;
5099 /* For the named back references, find the corresponding buffer
5101 n = reg_check_named_buff_matched(rex,scan);
5106 goto do_nref_ref_common;
5108 case REFFL: /* /\1/il */
5109 folder = foldEQ_locale;
5110 fold_array = PL_fold_locale;
5111 utf8_fold_flags = FOLDEQ_LOCALE;
5114 case REFFA: /* /\1/iaa */
5115 folder = foldEQ_latin1;
5116 fold_array = PL_fold_latin1;
5117 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5120 case REFFU: /* /\1/iu */
5121 folder = foldEQ_latin1;
5122 fold_array = PL_fold_latin1;
5123 utf8_fold_flags = 0;
5126 case REFF: /* /\1/i */
5128 fold_array = PL_fold;
5129 utf8_fold_flags = 0;
5132 case REF: /* /\1/ */
5135 utf8_fold_flags = 0;
5139 n = ARG(scan); /* which paren pair */
5142 ln = rex->offs[n].start;
5143 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5144 if (rex->lastparen < n || ln == -1)
5145 sayNO; /* Do not match unless seen CLOSEn. */
5146 if (ln == rex->offs[n].end)
5149 s = reginfo->strbeg + ln;
5150 if (type != REF /* REF can do byte comparison */
5151 && (utf8_target || type == REFFU || type == REFFL))
5153 char * limit = reginfo->strend;
5155 /* This call case insensitively compares the entire buffer
5156 * at s, with the current input starting at locinput, but
5157 * not going off the end given by reginfo->strend, and
5158 * returns in <limit> upon success, how much of the
5159 * current input was matched */
5160 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
5161 locinput, &limit, 0, utf8_target, utf8_fold_flags))
5169 /* Not utf8: Inline the first character, for speed. */
5170 if (!NEXTCHR_IS_EOS &&
5171 UCHARAT(s) != nextchr &&
5173 UCHARAT(s) != fold_array[nextchr]))
5175 ln = rex->offs[n].end - ln;
5176 if (locinput + ln > reginfo->strend)
5178 if (ln > 1 && (type == REF
5179 ? memNE(s, locinput, ln)
5180 : ! folder(s, locinput, ln)))
5186 case NOTHING: /* null op; e.g. the 'nothing' following
5187 * the '*' in m{(a+|b)*}' */
5189 case TAIL: /* placeholder while compiling (A|B|C) */
5192 case BACK: /* ??? doesn't appear to be used ??? */
5196 #define ST st->u.eval
5201 regexp_internal *rei;
5202 regnode *startpoint;
5204 case GOSTART: /* (?R) */
5205 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
5206 if (cur_eval && cur_eval->locinput==locinput) {
5207 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
5208 Perl_croak(aTHX_ "Infinite recursion in regex");
5209 if ( ++nochange_depth > max_nochange_depth )
5211 "Pattern subroutine nesting without pos change"
5212 " exceeded limit in regex");
5219 if (OP(scan)==GOSUB) {
5220 startpoint = scan + ARG2L(scan);
5221 ST.close_paren = ARG(scan);
5223 startpoint = rei->program+1;
5227 /* Save all the positions seen so far. */
5228 ST.cp = regcppush(rex, 0, maxopenparen);
5229 REGCP_SET(ST.lastcp);
5231 /* and then jump to the code we share with EVAL */
5232 goto eval_recurse_doit;
5234 assert(0); /* NOTREACHED */
5236 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
5237 if (cur_eval && cur_eval->locinput==locinput) {
5238 if ( ++nochange_depth > max_nochange_depth )
5239 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
5244 /* execute the code in the {...} */
5248 OP * const oop = PL_op;
5249 COP * const ocurcop = PL_curcop;
5253 /* save *all* paren positions */
5254 regcppush(rex, 0, maxopenparen);
5255 REGCP_SET(runops_cp);
5258 caller_cv = find_runcv(NULL);
5262 if (rexi->data->what[n] == 'r') { /* code from an external qr */
5264 (REGEXP*)(rexi->data->data[n])
5267 nop = (OP*)rexi->data->data[n+1];
5269 else if (rexi->data->what[n] == 'l') { /* literal code */
5271 nop = (OP*)rexi->data->data[n];
5272 assert(CvDEPTH(newcv));
5275 /* literal with own CV */
5276 assert(rexi->data->what[n] == 'L');
5277 newcv = rex->qr_anoncv;
5278 nop = (OP*)rexi->data->data[n];
5281 /* normally if we're about to execute code from the same
5282 * CV that we used previously, we just use the existing
5283 * CX stack entry. However, its possible that in the
5284 * meantime we may have backtracked, popped from the save
5285 * stack, and undone the SAVECOMPPAD(s) associated with
5286 * PUSH_MULTICALL; in which case PL_comppad no longer
5287 * points to newcv's pad. */
5288 if (newcv != last_pushed_cv || PL_comppad != last_pad)
5290 U8 flags = (CXp_SUB_RE |
5291 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
5292 if (last_pushed_cv) {
5293 CHANGE_MULTICALL_FLAGS(newcv, flags);
5296 PUSH_MULTICALL_FLAGS(newcv, flags);
5298 last_pushed_cv = newcv;
5301 /* these assignments are just to silence compiler
5303 multicall_cop = NULL;
5306 last_pad = PL_comppad;
5308 /* the initial nextstate you would normally execute
5309 * at the start of an eval (which would cause error
5310 * messages to come from the eval), may be optimised
5311 * away from the execution path in the regex code blocks;
5312 * so manually set PL_curcop to it initially */
5314 OP *o = cUNOPx(nop)->op_first;
5315 assert(o->op_type == OP_NULL);
5316 if (o->op_targ == OP_SCOPE) {
5317 o = cUNOPo->op_first;
5320 assert(o->op_targ == OP_LEAVE);
5321 o = cUNOPo->op_first;
5322 assert(o->op_type == OP_ENTER);
5326 if (o->op_type != OP_STUB) {
5327 assert( o->op_type == OP_NEXTSTATE
5328 || o->op_type == OP_DBSTATE
5329 || (o->op_type == OP_NULL
5330 && ( o->op_targ == OP_NEXTSTATE
5331 || o->op_targ == OP_DBSTATE
5335 PL_curcop = (COP*)o;
5340 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
5341 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
5343 rex->offs[0].end = locinput - reginfo->strbeg;
5344 if (reginfo->info_aux_eval->pos_magic)
5345 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
5346 reginfo->sv, reginfo->strbeg,
5347 locinput - reginfo->strbeg);
5350 SV *sv_mrk = get_sv("REGMARK", 1);
5351 sv_setsv(sv_mrk, sv_yes_mark);
5354 /* we don't use MULTICALL here as we want to call the
5355 * first op of the block of interest, rather than the
5356 * first op of the sub */
5357 before = (IV)(SP-PL_stack_base);
5359 CALLRUNOPS(aTHX); /* Scalar context. */
5361 if ((IV)(SP-PL_stack_base) == before)
5362 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
5368 /* before restoring everything, evaluate the returned
5369 * value, so that 'uninit' warnings don't use the wrong
5370 * PL_op or pad. Also need to process any magic vars
5371 * (e.g. $1) *before* parentheses are restored */
5376 if (logical == 0) /* (?{})/ */
5377 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
5378 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
5379 sw = cBOOL(SvTRUE(ret));
5382 else { /* /(??{}) */
5383 /* if its overloaded, let the regex compiler handle
5384 * it; otherwise extract regex, or stringify */
5385 if (SvGMAGICAL(ret))
5386 ret = sv_mortalcopy(ret);
5387 if (!SvAMAGIC(ret)) {
5391 if (SvTYPE(sv) == SVt_REGEXP)
5392 re_sv = (REGEXP*) sv;
5393 else if (SvSMAGICAL(ret)) {
5394 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
5396 re_sv = (REGEXP *) mg->mg_obj;
5399 /* force any undef warnings here */
5400 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
5401 ret = sv_mortalcopy(ret);
5402 (void) SvPV_force_nolen(ret);
5408 /* *** Note that at this point we don't restore
5409 * PL_comppad, (or pop the CxSUB) on the assumption it may
5410 * be used again soon. This is safe as long as nothing
5411 * in the regexp code uses the pad ! */
5413 PL_curcop = ocurcop;
5414 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
5415 PL_curpm = PL_reg_curpm;
5421 /* only /(??{})/ from now on */
5424 /* extract RE object from returned value; compiling if
5428 re_sv = reg_temp_copy(NULL, re_sv);
5433 if (SvUTF8(ret) && IN_BYTES) {
5434 /* In use 'bytes': make a copy of the octet
5435 * sequence, but without the flag on */
5437 const char *const p = SvPV(ret, len);
5438 ret = newSVpvn_flags(p, len, SVs_TEMP);
5440 if (rex->intflags & PREGf_USE_RE_EVAL)
5441 pm_flags |= PMf_USE_RE_EVAL;
5443 /* if we got here, it should be an engine which
5444 * supports compiling code blocks and stuff */
5445 assert(rex->engine && rex->engine->op_comp);
5446 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
5447 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
5448 rex->engine, NULL, NULL,
5449 /* copy /msix etc to inner pattern */
5454 & (SVs_TEMP | SVs_GMG | SVf_ROK))
5455 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
5456 /* This isn't a first class regexp. Instead, it's
5457 caching a regexp onto an existing, Perl visible
5459 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
5465 RXp_MATCH_COPIED_off(re);
5466 re->subbeg = rex->subbeg;
5467 re->sublen = rex->sublen;
5468 re->suboffset = rex->suboffset;
5469 re->subcoffset = rex->subcoffset;
5471 re->lastcloseparen = 0;
5474 debug_start_match(re_sv, utf8_target, locinput,
5475 reginfo->strend, "Matching embedded");
5477 startpoint = rei->program + 1;
5478 ST.close_paren = 0; /* only used for GOSUB */
5479 /* Save all the seen positions so far. */
5480 ST.cp = regcppush(rex, 0, maxopenparen);
5481 REGCP_SET(ST.lastcp);
5482 /* and set maxopenparen to 0, since we are starting a "fresh" match */
5484 /* run the pattern returned from (??{...}) */
5486 eval_recurse_doit: /* Share code with GOSUB below this line
5487 * At this point we expect the stack context to be
5488 * set up correctly */
5490 /* invalidate the S-L poscache. We're now executing a
5491 * different set of WHILEM ops (and their associated
5492 * indexes) against the same string, so the bits in the
5493 * cache are meaningless. Setting maxiter to zero forces
5494 * the cache to be invalidated and zeroed before reuse.
5495 * XXX This is too dramatic a measure. Ideally we should
5496 * save the old cache and restore when running the outer
5498 reginfo->poscache_maxiter = 0;
5500 /* the new regexp might have a different is_utf8_pat than we do */
5501 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
5503 ST.prev_rex = rex_sv;
5504 ST.prev_curlyx = cur_curlyx;
5506 SET_reg_curpm(rex_sv);
5511 ST.prev_eval = cur_eval;
5513 /* now continue from first node in postoned RE */
5514 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
5515 assert(0); /* NOTREACHED */
5518 case EVAL_AB: /* cleanup after a successful (??{A})B */
5519 /* note: this is called twice; first after popping B, then A */
5520 rex_sv = ST.prev_rex;
5521 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5522 SET_reg_curpm(rex_sv);
5523 rex = ReANY(rex_sv);
5524 rexi = RXi_GET(rex);
5526 /* preserve $^R across LEAVE's. See Bug 121070. */
5527 SV *save_sv= GvSV(PL_replgv);
5528 SvREFCNT_inc(save_sv);
5529 regcpblow(ST.cp); /* LEAVE in disguise */
5530 sv_setsv(GvSV(PL_replgv), save_sv);
5531 SvREFCNT_dec(save_sv);
5533 cur_eval = ST.prev_eval;
5534 cur_curlyx = ST.prev_curlyx;
5536 /* Invalidate cache. See "invalidate" comment above. */
5537 reginfo->poscache_maxiter = 0;
5538 if ( nochange_depth )
5543 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
5544 /* note: this is called twice; first after popping B, then A */
5545 rex_sv = ST.prev_rex;
5546 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5547 SET_reg_curpm(rex_sv);
5548 rex = ReANY(rex_sv);
5549 rexi = RXi_GET(rex);
5551 REGCP_UNWIND(ST.lastcp);
5552 regcppop(rex, &maxopenparen);
5553 cur_eval = ST.prev_eval;
5554 cur_curlyx = ST.prev_curlyx;
5555 /* Invalidate cache. See "invalidate" comment above. */
5556 reginfo->poscache_maxiter = 0;
5557 if ( nochange_depth )
5563 n = ARG(scan); /* which paren pair */
5564 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
5565 if (n > maxopenparen)
5567 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
5568 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
5572 (IV)rex->offs[n].start_tmp,
5578 /* XXX really need to log other places start/end are set too */
5579 #define CLOSE_CAPTURE \
5580 rex->offs[n].start = rex->offs[n].start_tmp; \
5581 rex->offs[n].end = locinput - reginfo->strbeg; \
5582 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
5583 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
5585 PTR2UV(rex->offs), \
5587 (IV)rex->offs[n].start, \
5588 (IV)rex->offs[n].end \
5592 n = ARG(scan); /* which paren pair */
5594 if (n > rex->lastparen)
5596 rex->lastcloseparen = n;
5597 if (cur_eval && cur_eval->u.eval.close_paren == n) {
5602 case ACCEPT: /* (*ACCEPT) */
5606 cursor && OP(cursor)!=END;
5607 cursor=regnext(cursor))
5609 if ( OP(cursor)==CLOSE ){
5611 if ( n <= lastopen ) {
5613 if (n > rex->lastparen)
5615 rex->lastcloseparen = n;
5616 if ( n == ARG(scan) || (cur_eval &&
5617 cur_eval->u.eval.close_paren == n))
5626 case GROUPP: /* (?(1)) */
5627 n = ARG(scan); /* which paren pair */
5628 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
5631 case NGROUPP: /* (?(<name>)) */
5632 /* reg_check_named_buff_matched returns 0 for no match */
5633 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
5636 case INSUBP: /* (?(R)) */
5638 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
5641 case DEFINEP: /* (?(DEFINE)) */
5645 case IFTHEN: /* (?(cond)A|B) */
5646 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5648 next = NEXTOPER(NEXTOPER(scan));
5650 next = scan + ARG(scan);
5651 if (OP(next) == IFTHEN) /* Fake one. */
5652 next = NEXTOPER(NEXTOPER(next));
5656 case LOGICAL: /* modifier for EVAL and IFMATCH */
5657 logical = scan->flags;
5660 /*******************************************************************
5662 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
5663 pattern, where A and B are subpatterns. (For simple A, CURLYM or
5664 STAR/PLUS/CURLY/CURLYN are used instead.)
5666 A*B is compiled as <CURLYX><A><WHILEM><B>
5668 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
5669 state, which contains the current count, initialised to -1. It also sets
5670 cur_curlyx to point to this state, with any previous value saved in the
5673 CURLYX then jumps straight to the WHILEM op, rather than executing A,
5674 since the pattern may possibly match zero times (i.e. it's a while {} loop
5675 rather than a do {} while loop).
5677 Each entry to WHILEM represents a successful match of A. The count in the
5678 CURLYX block is incremented, another WHILEM state is pushed, and execution
5679 passes to A or B depending on greediness and the current count.
5681 For example, if matching against the string a1a2a3b (where the aN are
5682 substrings that match /A/), then the match progresses as follows: (the
5683 pushed states are interspersed with the bits of strings matched so far):
5686 <CURLYX cnt=0><WHILEM>
5687 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
5688 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
5689 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
5690 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
5692 (Contrast this with something like CURLYM, which maintains only a single
5696 a1 <CURLYM cnt=1> a2
5697 a1 a2 <CURLYM cnt=2> a3
5698 a1 a2 a3 <CURLYM cnt=3> b
5701 Each WHILEM state block marks a point to backtrack to upon partial failure
5702 of A or B, and also contains some minor state data related to that
5703 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
5704 overall state, such as the count, and pointers to the A and B ops.
5706 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
5707 must always point to the *current* CURLYX block, the rules are:
5709 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
5710 and set cur_curlyx to point the new block.
5712 When popping the CURLYX block after a successful or unsuccessful match,
5713 restore the previous cur_curlyx.
5715 When WHILEM is about to execute B, save the current cur_curlyx, and set it
5716 to the outer one saved in the CURLYX block.
5718 When popping the WHILEM block after a successful or unsuccessful B match,
5719 restore the previous cur_curlyx.
5721 Here's an example for the pattern (AI* BI)*BO
5722 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
5725 curlyx backtrack stack
5726 ------ ---------------
5728 CO <CO prev=NULL> <WO>
5729 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5730 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5731 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
5733 At this point the pattern succeeds, and we work back down the stack to
5734 clean up, restoring as we go:
5736 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5737 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5738 CO <CO prev=NULL> <WO>
5741 *******************************************************************/
5743 #define ST st->u.curlyx
5745 case CURLYX: /* start of /A*B/ (for complex A) */
5747 /* No need to save/restore up to this paren */
5748 I32 parenfloor = scan->flags;
5750 assert(next); /* keep Coverity happy */
5751 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
5754 /* XXXX Probably it is better to teach regpush to support
5755 parenfloor > maxopenparen ... */
5756 if (parenfloor > (I32)rex->lastparen)
5757 parenfloor = rex->lastparen; /* Pessimization... */
5759 ST.prev_curlyx= cur_curlyx;
5761 ST.cp = PL_savestack_ix;
5763 /* these fields contain the state of the current curly.
5764 * they are accessed by subsequent WHILEMs */
5765 ST.parenfloor = parenfloor;
5770 ST.count = -1; /* this will be updated by WHILEM */
5771 ST.lastloc = NULL; /* this will be updated by WHILEM */
5773 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
5774 assert(0); /* NOTREACHED */
5777 case CURLYX_end: /* just finished matching all of A*B */
5778 cur_curlyx = ST.prev_curlyx;
5780 assert(0); /* NOTREACHED */
5782 case CURLYX_end_fail: /* just failed to match all of A*B */
5784 cur_curlyx = ST.prev_curlyx;
5786 assert(0); /* NOTREACHED */
5790 #define ST st->u.whilem
5792 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
5794 /* see the discussion above about CURLYX/WHILEM */
5799 assert(cur_curlyx); /* keep Coverity happy */
5801 min = ARG1(cur_curlyx->u.curlyx.me);
5802 max = ARG2(cur_curlyx->u.curlyx.me);
5803 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
5804 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
5805 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
5806 ST.cache_offset = 0;
5810 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5811 "%*s whilem: matched %ld out of %d..%d\n",
5812 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
5815 /* First just match a string of min A's. */
5818 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5820 cur_curlyx->u.curlyx.lastloc = locinput;
5821 REGCP_SET(ST.lastcp);
5823 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
5824 assert(0); /* NOTREACHED */
5827 /* If degenerate A matches "", assume A done. */
5829 if (locinput == cur_curlyx->u.curlyx.lastloc) {
5830 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5831 "%*s whilem: empty match detected, trying continuation...\n",
5832 REPORT_CODE_OFF+depth*2, "")
5834 goto do_whilem_B_max;
5837 /* super-linear cache processing.
5839 * The idea here is that for certain types of CURLYX/WHILEM -
5840 * principally those whose upper bound is infinity (and
5841 * excluding regexes that have things like \1 and other very
5842 * non-regular expresssiony things), then if a pattern like
5843 * /....A*.../ fails and we backtrack to the WHILEM, then we
5844 * make a note that this particular WHILEM op was at string
5845 * position 47 (say) when the rest of pattern failed. Then, if
5846 * we ever find ourselves back at that WHILEM, and at string
5847 * position 47 again, we can just fail immediately rather than
5848 * running the rest of the pattern again.
5850 * This is very handy when patterns start to go
5851 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
5852 * with a combinatorial explosion of backtracking.
5854 * The cache is implemented as a bit array, with one bit per
5855 * string byte position per WHILEM op (up to 16) - so its
5856 * between 0.25 and 2x the string size.
5858 * To avoid allocating a poscache buffer every time, we do an
5859 * initially countdown; only after we have executed a WHILEM
5860 * op (string-length x #WHILEMs) times do we allocate the
5863 * The top 4 bits of scan->flags byte say how many different
5864 * relevant CURLLYX/WHILEM op pairs there are, while the
5865 * bottom 4-bits is the identifying index number of this
5871 if (!reginfo->poscache_maxiter) {
5872 /* start the countdown: Postpone detection until we
5873 * know the match is not *that* much linear. */
5874 reginfo->poscache_maxiter
5875 = (reginfo->strend - reginfo->strbeg + 1)
5877 /* possible overflow for long strings and many CURLYX's */
5878 if (reginfo->poscache_maxiter < 0)
5879 reginfo->poscache_maxiter = I32_MAX;
5880 reginfo->poscache_iter = reginfo->poscache_maxiter;
5883 if (reginfo->poscache_iter-- == 0) {
5884 /* initialise cache */
5885 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
5886 regmatch_info_aux *const aux = reginfo->info_aux;
5887 if (aux->poscache) {
5888 if ((SSize_t)reginfo->poscache_size < size) {
5889 Renew(aux->poscache, size, char);
5890 reginfo->poscache_size = size;
5892 Zero(aux->poscache, size, char);
5895 reginfo->poscache_size = size;
5896 Newxz(aux->poscache, size, char);
5898 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5899 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
5900 PL_colors[4], PL_colors[5])
5904 if (reginfo->poscache_iter < 0) {
5905 /* have we already failed at this position? */
5906 SSize_t offset, mask;
5908 reginfo->poscache_iter = -1; /* stop eventual underflow */
5909 offset = (scan->flags & 0xf) - 1
5910 + (locinput - reginfo->strbeg)
5912 mask = 1 << (offset % 8);
5914 if (reginfo->info_aux->poscache[offset] & mask) {
5915 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5916 "%*s whilem: (cache) already tried at this position...\n",
5917 REPORT_CODE_OFF+depth*2, "")
5919 sayNO; /* cache records failure */
5921 ST.cache_offset = offset;
5922 ST.cache_mask = mask;
5926 /* Prefer B over A for minimal matching. */
5928 if (cur_curlyx->u.curlyx.minmod) {
5929 ST.save_curlyx = cur_curlyx;
5930 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5931 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
5933 REGCP_SET(ST.lastcp);
5934 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
5936 assert(0); /* NOTREACHED */
5939 /* Prefer A over B for maximal matching. */
5941 if (n < max) { /* More greed allowed? */
5942 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5944 cur_curlyx->u.curlyx.lastloc = locinput;
5945 REGCP_SET(ST.lastcp);
5946 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
5947 assert(0); /* NOTREACHED */
5949 goto do_whilem_B_max;
5951 assert(0); /* NOTREACHED */
5953 case WHILEM_B_min: /* just matched B in a minimal match */
5954 case WHILEM_B_max: /* just matched B in a maximal match */
5955 cur_curlyx = ST.save_curlyx;
5957 assert(0); /* NOTREACHED */
5959 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
5960 cur_curlyx = ST.save_curlyx;
5961 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5962 cur_curlyx->u.curlyx.count--;
5964 assert(0); /* NOTREACHED */
5966 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
5968 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
5969 REGCP_UNWIND(ST.lastcp);
5970 regcppop(rex, &maxopenparen);
5971 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5972 cur_curlyx->u.curlyx.count--;
5974 assert(0); /* NOTREACHED */
5976 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5977 REGCP_UNWIND(ST.lastcp);
5978 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
5979 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5980 "%*s whilem: failed, trying continuation...\n",
5981 REPORT_CODE_OFF+depth*2, "")
5984 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5985 && ckWARN(WARN_REGEXP)
5986 && !reginfo->warned)
5988 reginfo->warned = TRUE;
5989 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5990 "Complex regular subexpression recursion limit (%d) "
5996 ST.save_curlyx = cur_curlyx;
5997 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5998 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
6000 assert(0); /* NOTREACHED */
6002 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
6003 cur_curlyx = ST.save_curlyx;
6004 REGCP_UNWIND(ST.lastcp);
6005 regcppop(rex, &maxopenparen);
6007 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
6008 /* Maximum greed exceeded */
6009 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6010 && ckWARN(WARN_REGEXP)
6011 && !reginfo->warned)
6013 reginfo->warned = TRUE;
6014 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6015 "Complex regular subexpression recursion "
6016 "limit (%d) exceeded",
6019 cur_curlyx->u.curlyx.count--;
6023 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6024 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
6026 /* Try grabbing another A and see if it helps. */
6027 cur_curlyx->u.curlyx.lastloc = locinput;
6028 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6030 REGCP_SET(ST.lastcp);
6031 PUSH_STATE_GOTO(WHILEM_A_min,
6032 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6034 assert(0); /* NOTREACHED */
6037 #define ST st->u.branch
6039 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6040 next = scan + ARG(scan);
6043 scan = NEXTOPER(scan);
6046 case BRANCH: /* /(...|A|...)/ */
6047 scan = NEXTOPER(scan); /* scan now points to inner node */
6048 ST.lastparen = rex->lastparen;
6049 ST.lastcloseparen = rex->lastcloseparen;
6050 ST.next_branch = next;
6053 /* Now go into the branch */
6055 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
6057 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
6059 assert(0); /* NOTREACHED */
6061 case CUTGROUP: /* /(*THEN)/ */
6062 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
6063 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6064 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
6065 assert(0); /* NOTREACHED */
6067 case CUTGROUP_next_fail:
6070 if (st->u.mark.mark_name)
6071 sv_commit = st->u.mark.mark_name;
6073 assert(0); /* NOTREACHED */
6077 assert(0); /* NOTREACHED */
6079 case BRANCH_next_fail: /* that branch failed; try the next, if any */
6084 REGCP_UNWIND(ST.cp);
6085 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6086 scan = ST.next_branch;
6087 /* no more branches? */
6088 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
6090 PerlIO_printf( Perl_debug_log,
6091 "%*s %sBRANCH failed...%s\n",
6092 REPORT_CODE_OFF+depth*2, "",
6098 continue; /* execute next BRANCH[J] op */
6099 assert(0); /* NOTREACHED */
6101 case MINMOD: /* next op will be non-greedy, e.g. A*? */
6106 #define ST st->u.curlym
6108 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
6110 /* This is an optimisation of CURLYX that enables us to push
6111 * only a single backtracking state, no matter how many matches
6112 * there are in {m,n}. It relies on the pattern being constant
6113 * length, with no parens to influence future backrefs
6117 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6119 ST.lastparen = rex->lastparen;
6120 ST.lastcloseparen = rex->lastcloseparen;
6122 /* if paren positive, emulate an OPEN/CLOSE around A */
6124 U32 paren = ST.me->flags;
6125 if (paren > maxopenparen)
6126 maxopenparen = paren;
6127 scan += NEXT_OFF(scan); /* Skip former OPEN. */
6135 ST.c1 = CHRTEST_UNINIT;
6138 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
6141 curlym_do_A: /* execute the A in /A{m,n}B/ */
6142 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
6143 assert(0); /* NOTREACHED */
6145 case CURLYM_A: /* we've just matched an A */
6147 /* after first match, determine A's length: u.curlym.alen */
6148 if (ST.count == 1) {
6149 if (reginfo->is_utf8_target) {
6150 char *s = st->locinput;
6151 while (s < locinput) {
6157 ST.alen = locinput - st->locinput;
6160 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
6163 PerlIO_printf(Perl_debug_log,
6164 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
6165 (int)(REPORT_CODE_OFF+(depth*2)), "",
6166 (IV) ST.count, (IV)ST.alen)
6169 if (cur_eval && cur_eval->u.eval.close_paren &&
6170 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6174 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
6175 if ( max == REG_INFTY || ST.count < max )
6176 goto curlym_do_A; /* try to match another A */
6178 goto curlym_do_B; /* try to match B */
6180 case CURLYM_A_fail: /* just failed to match an A */
6181 REGCP_UNWIND(ST.cp);
6183 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
6184 || (cur_eval && cur_eval->u.eval.close_paren &&
6185 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
6188 curlym_do_B: /* execute the B in /A{m,n}B/ */
6189 if (ST.c1 == CHRTEST_UNINIT) {
6190 /* calculate c1 and c2 for possible match of 1st char
6191 * following curly */
6192 ST.c1 = ST.c2 = CHRTEST_VOID;
6194 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
6195 regnode *text_node = ST.B;
6196 if (! HAS_TEXT(text_node))
6197 FIND_NEXT_IMPT(text_node);
6200 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
6202 But the former is redundant in light of the latter.
6204 if this changes back then the macro for
6205 IS_TEXT and friends need to change.
6207 if (PL_regkind[OP(text_node)] == EXACT) {
6208 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6209 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6219 PerlIO_printf(Perl_debug_log,
6220 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
6221 (int)(REPORT_CODE_OFF+(depth*2)),
6224 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
6225 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
6226 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6227 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6229 /* simulate B failing */
6231 PerlIO_printf(Perl_debug_log,
6232 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
6233 (int)(REPORT_CODE_OFF+(depth*2)),"",
6234 valid_utf8_to_uvchr((U8 *) locinput, NULL),
6235 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
6236 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
6238 state_num = CURLYM_B_fail;
6239 goto reenter_switch;
6242 else if (nextchr != ST.c1 && nextchr != ST.c2) {
6243 /* simulate B failing */
6245 PerlIO_printf(Perl_debug_log,
6246 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
6247 (int)(REPORT_CODE_OFF+(depth*2)),"",
6248 (int) nextchr, ST.c1, ST.c2)
6250 state_num = CURLYM_B_fail;
6251 goto reenter_switch;
6256 /* emulate CLOSE: mark current A as captured */
6257 I32 paren = ST.me->flags;
6259 rex->offs[paren].start
6260 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
6261 rex->offs[paren].end = locinput - reginfo->strbeg;
6262 if ((U32)paren > rex->lastparen)
6263 rex->lastparen = paren;
6264 rex->lastcloseparen = paren;
6267 rex->offs[paren].end = -1;
6268 if (cur_eval && cur_eval->u.eval.close_paren &&
6269 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6278 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
6279 assert(0); /* NOTREACHED */
6281 case CURLYM_B_fail: /* just failed to match a B */
6282 REGCP_UNWIND(ST.cp);
6283 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6285 I32 max = ARG2(ST.me);
6286 if (max != REG_INFTY && ST.count == max)
6288 goto curlym_do_A; /* try to match a further A */
6290 /* backtrack one A */
6291 if (ST.count == ARG1(ST.me) /* min */)
6294 SET_locinput(HOPc(locinput, -ST.alen));
6295 goto curlym_do_B; /* try to match B */
6298 #define ST st->u.curly
6300 #define CURLY_SETPAREN(paren, success) \
6303 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
6304 rex->offs[paren].end = locinput - reginfo->strbeg; \
6305 if (paren > rex->lastparen) \
6306 rex->lastparen = paren; \
6307 rex->lastcloseparen = paren; \
6310 rex->offs[paren].end = -1; \
6311 rex->lastparen = ST.lastparen; \
6312 rex->lastcloseparen = ST.lastcloseparen; \
6316 case STAR: /* /A*B/ where A is width 1 char */
6320 scan = NEXTOPER(scan);
6323 case PLUS: /* /A+B/ where A is width 1 char */
6327 scan = NEXTOPER(scan);
6330 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
6331 ST.paren = scan->flags; /* Which paren to set */
6332 ST.lastparen = rex->lastparen;
6333 ST.lastcloseparen = rex->lastcloseparen;
6334 if (ST.paren > maxopenparen)
6335 maxopenparen = ST.paren;
6336 ST.min = ARG1(scan); /* min to match */
6337 ST.max = ARG2(scan); /* max to match */
6338 if (cur_eval && cur_eval->u.eval.close_paren &&
6339 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6343 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
6346 case CURLY: /* /A{m,n}B/ where A is width 1 char */
6348 ST.min = ARG1(scan); /* min to match */
6349 ST.max = ARG2(scan); /* max to match */
6350 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6353 * Lookahead to avoid useless match attempts
6354 * when we know what character comes next.
6356 * Used to only do .*x and .*?x, but now it allows
6357 * for )'s, ('s and (?{ ... })'s to be in the way
6358 * of the quantifier and the EXACT-like node. -- japhy
6361 assert(ST.min <= ST.max);
6362 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
6363 ST.c1 = ST.c2 = CHRTEST_VOID;
6366 regnode *text_node = next;
6368 if (! HAS_TEXT(text_node))
6369 FIND_NEXT_IMPT(text_node);
6371 if (! HAS_TEXT(text_node))
6372 ST.c1 = ST.c2 = CHRTEST_VOID;
6374 if ( PL_regkind[OP(text_node)] != EXACT ) {
6375 ST.c1 = ST.c2 = CHRTEST_VOID;
6379 /* Currently we only get here when
6381 PL_rekind[OP(text_node)] == EXACT
6383 if this changes back then the macro for IS_TEXT and
6384 friends need to change. */
6385 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6386 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6398 char *li = locinput;
6401 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
6407 if (ST.c1 == CHRTEST_VOID)
6408 goto curly_try_B_min;
6410 ST.oldloc = locinput;
6412 /* set ST.maxpos to the furthest point along the
6413 * string that could possibly match */
6414 if (ST.max == REG_INFTY) {
6415 ST.maxpos = reginfo->strend - 1;
6417 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
6420 else if (utf8_target) {
6421 int m = ST.max - ST.min;
6422 for (ST.maxpos = locinput;
6423 m >0 && ST.maxpos < reginfo->strend; m--)
6424 ST.maxpos += UTF8SKIP(ST.maxpos);
6427 ST.maxpos = locinput + ST.max - ST.min;
6428 if (ST.maxpos >= reginfo->strend)
6429 ST.maxpos = reginfo->strend - 1;
6431 goto curly_try_B_min_known;
6435 /* avoid taking address of locinput, so it can remain
6437 char *li = locinput;
6438 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
6439 if (ST.count < ST.min)
6442 if ((ST.count > ST.min)
6443 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
6445 /* A{m,n} must come at the end of the string, there's
6446 * no point in backing off ... */
6448 /* ...except that $ and \Z can match before *and* after
6449 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
6450 We may back off by one in this case. */
6451 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
6455 goto curly_try_B_max;
6457 assert(0); /* NOTREACHED */
6460 case CURLY_B_min_known_fail:
6461 /* failed to find B in a non-greedy match where c1,c2 valid */
6463 REGCP_UNWIND(ST.cp);
6465 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6467 /* Couldn't or didn't -- move forward. */
6468 ST.oldloc = locinput;
6470 locinput += UTF8SKIP(locinput);
6474 curly_try_B_min_known:
6475 /* find the next place where 'B' could work, then call B */
6479 n = (ST.oldloc == locinput) ? 0 : 1;
6480 if (ST.c1 == ST.c2) {
6481 /* set n to utf8_distance(oldloc, locinput) */
6482 while (locinput <= ST.maxpos
6483 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
6485 locinput += UTF8SKIP(locinput);
6490 /* set n to utf8_distance(oldloc, locinput) */
6491 while (locinput <= ST.maxpos
6492 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6493 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6495 locinput += UTF8SKIP(locinput);
6500 else { /* Not utf8_target */
6501 if (ST.c1 == ST.c2) {
6502 while (locinput <= ST.maxpos &&
6503 UCHARAT(locinput) != ST.c1)
6507 while (locinput <= ST.maxpos
6508 && UCHARAT(locinput) != ST.c1
6509 && UCHARAT(locinput) != ST.c2)
6512 n = locinput - ST.oldloc;
6514 if (locinput > ST.maxpos)
6517 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
6518 * at b; check that everything between oldloc and
6519 * locinput matches */
6520 char *li = ST.oldloc;
6522 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
6524 assert(n == REG_INFTY || locinput == li);
6526 CURLY_SETPAREN(ST.paren, ST.count);
6527 if (cur_eval && cur_eval->u.eval.close_paren &&
6528 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6531 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
6533 assert(0); /* NOTREACHED */
6536 case CURLY_B_min_fail:
6537 /* failed to find B in a non-greedy match where c1,c2 invalid */
6539 REGCP_UNWIND(ST.cp);
6541 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6543 /* failed -- move forward one */
6545 char *li = locinput;
6546 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
6553 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
6554 ST.count > 0)) /* count overflow ? */
6557 CURLY_SETPAREN(ST.paren, ST.count);
6558 if (cur_eval && cur_eval->u.eval.close_paren &&
6559 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6562 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
6566 assert(0); /* NOTREACHED */
6570 /* a successful greedy match: now try to match B */
6571 if (cur_eval && cur_eval->u.eval.close_paren &&
6572 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6576 bool could_match = locinput < reginfo->strend;
6578 /* If it could work, try it. */
6579 if (ST.c1 != CHRTEST_VOID && could_match) {
6580 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
6582 could_match = memEQ(locinput,
6587 UTF8SKIP(locinput));
6590 could_match = UCHARAT(locinput) == ST.c1
6591 || UCHARAT(locinput) == ST.c2;
6594 if (ST.c1 == CHRTEST_VOID || could_match) {
6595 CURLY_SETPAREN(ST.paren, ST.count);
6596 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
6597 assert(0); /* NOTREACHED */
6602 case CURLY_B_max_fail:
6603 /* failed to find B in a greedy match */
6605 REGCP_UNWIND(ST.cp);
6607 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6610 if (--ST.count < ST.min)
6612 locinput = HOPc(locinput, -1);
6613 goto curly_try_B_max;
6617 case END: /* last op of main pattern */
6620 /* we've just finished A in /(??{A})B/; now continue with B */
6622 st->u.eval.prev_rex = rex_sv; /* inner */
6624 /* Save *all* the positions. */
6625 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
6626 rex_sv = cur_eval->u.eval.prev_rex;
6627 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6628 SET_reg_curpm(rex_sv);
6629 rex = ReANY(rex_sv);
6630 rexi = RXi_GET(rex);
6631 cur_curlyx = cur_eval->u.eval.prev_curlyx;
6633 REGCP_SET(st->u.eval.lastcp);
6635 /* Restore parens of the outer rex without popping the
6637 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
6640 st->u.eval.prev_eval = cur_eval;
6641 cur_eval = cur_eval->u.eval.prev_eval;
6643 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
6644 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
6645 if ( nochange_depth )
6648 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
6649 locinput); /* match B */
6652 if (locinput < reginfo->till) {
6653 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6654 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
6656 (long)(locinput - startpos),
6657 (long)(reginfo->till - startpos),
6660 sayNO_SILENT; /* Cannot match: too short. */
6662 sayYES; /* Success! */
6664 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
6666 PerlIO_printf(Perl_debug_log,
6667 "%*s %ssubpattern success...%s\n",
6668 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
6669 sayYES; /* Success! */
6672 #define ST st->u.ifmatch
6677 case SUSPEND: /* (?>A) */
6679 newstart = locinput;
6682 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
6684 goto ifmatch_trivial_fail_test;
6686 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
6688 ifmatch_trivial_fail_test:
6690 char * const s = HOPBACKc(locinput, scan->flags);
6695 sw = 1 - cBOOL(ST.wanted);
6699 next = scan + ARG(scan);
6707 newstart = locinput;
6711 ST.logical = logical;
6712 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
6714 /* execute body of (?...A) */
6715 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
6716 assert(0); /* NOTREACHED */
6719 case IFMATCH_A_fail: /* body of (?...A) failed */
6720 ST.wanted = !ST.wanted;
6723 case IFMATCH_A: /* body of (?...A) succeeded */
6725 sw = cBOOL(ST.wanted);
6727 else if (!ST.wanted)
6730 if (OP(ST.me) != SUSPEND) {
6731 /* restore old position except for (?>...) */
6732 locinput = st->locinput;
6734 scan = ST.me + ARG(ST.me);
6737 continue; /* execute B */
6741 case LONGJMP: /* alternative with many branches compiles to
6742 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
6743 next = scan + ARG(scan);
6748 case COMMIT: /* (*COMMIT) */
6749 reginfo->cutpoint = reginfo->strend;
6752 case PRUNE: /* (*PRUNE) */
6754 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6755 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
6756 assert(0); /* NOTREACHED */
6758 case COMMIT_next_fail:
6762 case OPFAIL: /* (*FAIL) */
6764 assert(0); /* NOTREACHED */
6766 #define ST st->u.mark
6767 case MARKPOINT: /* (*MARK:foo) */
6768 ST.prev_mark = mark_state;
6769 ST.mark_name = sv_commit = sv_yes_mark
6770 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6772 ST.mark_loc = locinput;
6773 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
6774 assert(0); /* NOTREACHED */
6776 case MARKPOINT_next:
6777 mark_state = ST.prev_mark;
6779 assert(0); /* NOTREACHED */
6781 case MARKPOINT_next_fail:
6782 if (popmark && sv_eq(ST.mark_name,popmark))
6784 if (ST.mark_loc > startpoint)
6785 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6786 popmark = NULL; /* we found our mark */
6787 sv_commit = ST.mark_name;
6790 PerlIO_printf(Perl_debug_log,
6791 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
6792 REPORT_CODE_OFF+depth*2, "",
6793 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
6796 mark_state = ST.prev_mark;
6797 sv_yes_mark = mark_state ?
6798 mark_state->u.mark.mark_name : NULL;
6800 assert(0); /* NOTREACHED */
6802 case SKIP: /* (*SKIP) */
6804 /* (*SKIP) : if we fail we cut here*/
6805 ST.mark_name = NULL;
6806 ST.mark_loc = locinput;
6807 PUSH_STATE_GOTO(SKIP_next,next, locinput);
6809 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
6810 otherwise do nothing. Meaning we need to scan
6812 regmatch_state *cur = mark_state;
6813 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6816 if ( sv_eq( cur->u.mark.mark_name,
6819 ST.mark_name = find;
6820 PUSH_STATE_GOTO( SKIP_next, next, locinput);
6822 cur = cur->u.mark.prev_mark;
6825 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
6828 case SKIP_next_fail:
6830 /* (*CUT:NAME) - Set up to search for the name as we
6831 collapse the stack*/
6832 popmark = ST.mark_name;
6834 /* (*CUT) - No name, we cut here.*/
6835 if (ST.mark_loc > startpoint)
6836 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6837 /* but we set sv_commit to latest mark_name if there
6838 is one so they can test to see how things lead to this
6841 sv_commit=mark_state->u.mark.mark_name;
6845 assert(0); /* NOTREACHED */
6848 case LNBREAK: /* \R */
6849 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
6856 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
6857 PTR2UV(scan), OP(scan));
6858 Perl_croak(aTHX_ "regexp memory corruption");
6860 /* this is a point to jump to in order to increment
6861 * locinput by one character */
6863 assert(!NEXTCHR_IS_EOS);
6865 locinput += PL_utf8skip[nextchr];
6866 /* locinput is allowed to go 1 char off the end, but not 2+ */
6867 if (locinput > reginfo->strend)
6876 /* switch break jumps here */
6877 scan = next; /* prepare to execute the next op and ... */
6878 continue; /* ... jump back to the top, reusing st */
6879 assert(0); /* NOTREACHED */
6882 /* push a state that backtracks on success */
6883 st->u.yes.prev_yes_state = yes_state;
6887 /* push a new regex state, then continue at scan */
6889 regmatch_state *newst;
6892 regmatch_state *cur = st;
6893 regmatch_state *curyes = yes_state;
6895 regmatch_slab *slab = PL_regmatch_slab;
6896 for (;curd > -1;cur--,curd--) {
6897 if (cur < SLAB_FIRST(slab)) {
6899 cur = SLAB_LAST(slab);
6901 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
6902 REPORT_CODE_OFF + 2 + depth * 2,"",
6903 curd, PL_reg_name[cur->resume_state],
6904 (curyes == cur) ? "yes" : ""
6907 curyes = cur->u.yes.prev_yes_state;
6910 DEBUG_STATE_pp("push")
6913 st->locinput = locinput;
6915 if (newst > SLAB_LAST(PL_regmatch_slab))
6916 newst = S_push_slab(aTHX);
6917 PL_regmatch_state = newst;
6919 locinput = pushinput;
6922 assert(0); /* NOTREACHED */
6927 * We get here only if there's trouble -- normally "case END" is
6928 * the terminating point.
6930 Perl_croak(aTHX_ "corrupted regexp pointers");
6936 /* we have successfully completed a subexpression, but we must now
6937 * pop to the state marked by yes_state and continue from there */
6938 assert(st != yes_state);
6940 while (st != yes_state) {
6942 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6943 PL_regmatch_slab = PL_regmatch_slab->prev;
6944 st = SLAB_LAST(PL_regmatch_slab);
6948 DEBUG_STATE_pp("pop (no final)");
6950 DEBUG_STATE_pp("pop (yes)");
6956 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
6957 || yes_state > SLAB_LAST(PL_regmatch_slab))
6959 /* not in this slab, pop slab */
6960 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
6961 PL_regmatch_slab = PL_regmatch_slab->prev;
6962 st = SLAB_LAST(PL_regmatch_slab);
6964 depth -= (st - yes_state);
6967 yes_state = st->u.yes.prev_yes_state;
6968 PL_regmatch_state = st;
6971 locinput= st->locinput;
6972 state_num = st->resume_state + no_final;
6973 goto reenter_switch;
6976 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6977 PL_colors[4], PL_colors[5]));
6979 if (reginfo->info_aux_eval) {
6980 /* each successfully executed (?{...}) block does the equivalent of
6981 * local $^R = do {...}
6982 * When popping the save stack, all these locals would be undone;
6983 * bypass this by setting the outermost saved $^R to the latest
6985 /* I dont know if this is needed or works properly now.
6986 * see code related to PL_replgv elsewhere in this file.
6989 if (oreplsv != GvSV(PL_replgv))
6990 sv_setsv(oreplsv, GvSV(PL_replgv));
6997 PerlIO_printf(Perl_debug_log,
6998 "%*s %sfailed...%s\n",
6999 REPORT_CODE_OFF+depth*2, "",
7000 PL_colors[4], PL_colors[5])
7012 /* there's a previous state to backtrack to */
7014 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7015 PL_regmatch_slab = PL_regmatch_slab->prev;
7016 st = SLAB_LAST(PL_regmatch_slab);
7018 PL_regmatch_state = st;
7019 locinput= st->locinput;
7021 DEBUG_STATE_pp("pop");
7023 if (yes_state == st)
7024 yes_state = st->u.yes.prev_yes_state;
7026 state_num = st->resume_state + 1; /* failure = success + 1 */
7027 goto reenter_switch;
7032 if (rex->intflags & PREGf_VERBARG_SEEN) {
7033 SV *sv_err = get_sv("REGERROR", 1);
7034 SV *sv_mrk = get_sv("REGMARK", 1);
7036 sv_commit = &PL_sv_no;
7038 sv_yes_mark = &PL_sv_yes;
7041 sv_commit = &PL_sv_yes;
7042 sv_yes_mark = &PL_sv_no;
7046 sv_setsv(sv_err, sv_commit);
7047 sv_setsv(sv_mrk, sv_yes_mark);
7051 if (last_pushed_cv) {
7054 PERL_UNUSED_VAR(SP);
7057 assert(!result || locinput - reginfo->strbeg >= 0);
7058 return result ? locinput - reginfo->strbeg : -1;
7062 - regrepeat - repeatedly match something simple, report how many
7064 * What 'simple' means is a node which can be the operand of a quantifier like
7067 * startposp - pointer a pointer to the start position. This is updated
7068 * to point to the byte following the highest successful
7070 * p - the regnode to be repeatedly matched against.
7071 * reginfo - struct holding match state, such as strend
7072 * max - maximum number of things to match.
7073 * depth - (for debugging) backtracking depth.
7076 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
7077 regmatch_info *const reginfo, I32 max, int depth)
7079 char *scan; /* Pointer to current position in target string */
7081 char *loceol = reginfo->strend; /* local version */
7082 I32 hardcount = 0; /* How many matches so far */
7083 bool utf8_target = reginfo->is_utf8_target;
7084 int to_complement = 0; /* Invert the result? */
7086 _char_class_number classnum;
7088 PERL_UNUSED_ARG(depth);
7091 PERL_ARGS_ASSERT_REGREPEAT;
7094 if (max == REG_INFTY)
7096 else if (! utf8_target && loceol - scan > max)
7097 loceol = scan + max;
7099 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
7100 * to the maximum of how far we should go in it (leaving it set to the real
7101 * end, if the maximum permissible would take us beyond that). This allows
7102 * us to make the loop exit condition that we haven't gone past <loceol> to
7103 * also mean that we haven't exceeded the max permissible count, saving a
7104 * test each time through the loop. But it assumes that the OP matches a
7105 * single byte, which is true for most of the OPs below when applied to a
7106 * non-UTF-8 target. Those relatively few OPs that don't have this
7107 * characteristic will have to compensate.
7109 * There is no adjustment for UTF-8 targets, as the number of bytes per
7110 * character varies. OPs will have to test both that the count is less
7111 * than the max permissible (using <hardcount> to keep track), and that we
7112 * are still within the bounds of the string (using <loceol>. A few OPs
7113 * match a single byte no matter what the encoding. They can omit the max
7114 * test if, for the UTF-8 case, they do the adjustment that was skipped
7117 * Thus, the code above sets things up for the common case; and exceptional
7118 * cases need extra work; the common case is to make sure <scan> doesn't
7119 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
7120 * count doesn't exceed the maximum permissible */
7125 while (scan < loceol && hardcount < max && *scan != '\n') {
7126 scan += UTF8SKIP(scan);
7130 while (scan < loceol && *scan != '\n')
7136 while (scan < loceol && hardcount < max) {
7137 scan += UTF8SKIP(scan);
7144 case CANY: /* Move <scan> forward <max> bytes, unless goes off end */
7145 if (utf8_target && loceol - scan > max) {
7147 /* <loceol> hadn't been adjusted in the UTF-8 case */
7155 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7159 /* Can use a simple loop if the pattern char to match on is invariant
7160 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
7161 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
7162 * true iff it doesn't matter if the argument is in UTF-8 or not */
7163 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
7164 if (utf8_target && loceol - scan > max) {
7165 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
7166 * since here, to match at all, 1 char == 1 byte */
7167 loceol = scan + max;
7169 while (scan < loceol && UCHARAT(scan) == c) {
7173 else if (reginfo->is_utf8_pat) {
7175 STRLEN scan_char_len;
7177 /* When both target and pattern are UTF-8, we have to do
7179 while (hardcount < max
7181 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
7182 && memEQ(scan, STRING(p), scan_char_len))
7184 scan += scan_char_len;
7188 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
7190 /* Target isn't utf8; convert the character in the UTF-8
7191 * pattern to non-UTF8, and do a simple loop */
7192 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
7193 while (scan < loceol && UCHARAT(scan) == c) {
7196 } /* else pattern char is above Latin1, can't possibly match the
7201 /* Here, the string must be utf8; pattern isn't, and <c> is
7202 * different in utf8 than not, so can't compare them directly.
7203 * Outside the loop, find the two utf8 bytes that represent c, and
7204 * then look for those in sequence in the utf8 string */
7205 U8 high = UTF8_TWO_BYTE_HI(c);
7206 U8 low = UTF8_TWO_BYTE_LO(c);
7208 while (hardcount < max
7209 && scan + 1 < loceol
7210 && UCHARAT(scan) == high
7211 && UCHARAT(scan + 1) == low)
7219 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
7220 assert(! reginfo->is_utf8_pat);
7223 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7227 utf8_flags = FOLDEQ_LOCALE;
7230 case EXACTF: /* This node only generated for non-utf8 patterns */
7231 assert(! reginfo->is_utf8_pat);
7237 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
7241 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
7243 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7245 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
7248 if (c1 == CHRTEST_VOID) {
7249 /* Use full Unicode fold matching */
7250 char *tmpeol = reginfo->strend;
7251 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
7252 while (hardcount < max
7253 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
7254 STRING(p), NULL, pat_len,
7255 reginfo->is_utf8_pat, utf8_flags))
7258 tmpeol = reginfo->strend;
7262 else if (utf8_target) {
7264 while (scan < loceol
7266 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
7268 scan += UTF8SKIP(scan);
7273 while (scan < loceol
7275 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
7276 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
7278 scan += UTF8SKIP(scan);
7283 else if (c1 == c2) {
7284 while (scan < loceol && UCHARAT(scan) == c1) {
7289 while (scan < loceol &&
7290 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
7300 while (hardcount < max
7302 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
7304 scan += UTF8SKIP(scan);
7308 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
7313 /* The argument (FLAGS) to all the POSIX node types is the class number */
7320 if (! utf8_target) {
7321 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
7327 while (hardcount < max && scan < loceol
7328 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
7331 scan += UTF8SKIP(scan);
7344 if (utf8_target && loceol - scan > max) {
7346 /* We didn't adjust <loceol> at the beginning of this routine
7347 * because is UTF-8, but it is actually ok to do so, since here, to
7348 * match, 1 char == 1 byte. */
7349 loceol = scan + max;
7351 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
7364 if (! utf8_target) {
7365 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
7371 /* The complement of something that matches only ASCII matches all
7372 * non-ASCII, plus everything in ASCII that isn't in the class. */
7373 while (hardcount < max && scan < loceol
7374 && (! isASCII_utf8(scan)
7375 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
7377 scan += UTF8SKIP(scan);
7388 if (! utf8_target) {
7389 while (scan < loceol && to_complement
7390 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
7397 classnum = (_char_class_number) FLAGS(p);
7398 if (classnum < _FIRST_NON_SWASH_CC) {
7400 /* Here, a swash is needed for above-Latin1 code points.
7401 * Process as many Latin1 code points using the built-in rules.
7402 * Go to another loop to finish processing upon encountering
7403 * the first Latin1 code point. We could do that in this loop
7404 * as well, but the other way saves having to test if the swash
7405 * has been loaded every time through the loop: extra space to
7407 while (hardcount < max && scan < loceol) {
7408 if (UTF8_IS_INVARIANT(*scan)) {
7409 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
7416 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
7417 if (! (to_complement
7418 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
7427 goto found_above_latin1;
7434 /* For these character classes, the knowledge of how to handle
7435 * every code point is compiled in to Perl via a macro. This
7436 * code is written for making the loops as tight as possible.
7437 * It could be refactored to save space instead */
7439 case _CC_ENUM_SPACE: /* XXX would require separate code
7440 if we revert the change of \v
7443 case _CC_ENUM_PSXSPC:
7444 while (hardcount < max
7446 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
7448 scan += UTF8SKIP(scan);
7452 case _CC_ENUM_BLANK:
7453 while (hardcount < max
7455 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
7457 scan += UTF8SKIP(scan);
7461 case _CC_ENUM_XDIGIT:
7462 while (hardcount < max
7464 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
7466 scan += UTF8SKIP(scan);
7470 case _CC_ENUM_VERTSPACE:
7471 while (hardcount < max
7473 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
7475 scan += UTF8SKIP(scan);
7479 case _CC_ENUM_CNTRL:
7480 while (hardcount < max
7482 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
7484 scan += UTF8SKIP(scan);
7489 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
7495 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
7497 /* Load the swash if not already present */
7498 if (! PL_utf8_swash_ptrs[classnum]) {
7499 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7500 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
7504 PL_XPosix_ptrs[classnum], &flags);
7507 while (hardcount < max && scan < loceol
7508 && to_complement ^ cBOOL(_generic_utf8(
7511 swash_fetch(PL_utf8_swash_ptrs[classnum],
7515 scan += UTF8SKIP(scan);
7522 while (hardcount < max && scan < loceol &&
7523 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
7528 /* LNBREAK can match one or two latin chars, which is ok, but we
7529 * have to use hardcount in this situation, and throw away the
7530 * adjustment to <loceol> done before the switch statement */
7531 loceol = reginfo->strend;
7532 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
7553 /* These are all 0 width, so match right here or not at all. */
7557 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
7558 assert(0); /* NOTREACHED */
7565 c = scan - *startposp;
7569 GET_RE_DEBUG_FLAGS_DECL;
7571 SV * const prop = sv_newmortal();
7572 regprop(prog, prop, p, reginfo);
7573 PerlIO_printf(Perl_debug_log,
7574 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
7575 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
7583 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
7585 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
7586 create a copy so that changes the caller makes won't change the shared one.
7587 If <altsvp> is non-null, will return NULL in it, for back-compat.
7590 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
7592 PERL_ARGS_ASSERT_REGCLASS_SWASH;
7598 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL));
7602 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
7603 const regnode* node,
7606 SV** only_utf8_locale_ptr)
7608 /* For internal core use only.
7609 * Returns the swash for the input 'node' in the regex 'prog'.
7610 * If <doinit> is 'true', will attempt to create the swash if not already
7612 * If <listsvp> is non-null, will return the printable contents of the
7613 * swash. This can be used to get debugging information even before the
7614 * swash exists, by calling this function with 'doinit' set to false, in
7615 * which case the components that will be used to eventually create the
7616 * swash are returned (in a printable form).
7617 * Tied intimately to how regcomp.c sets up the data structure */
7620 SV *si = NULL; /* Input swash initialization string */
7623 RXi_GET_DECL(prog,progi);
7624 const struct reg_data * const data = prog ? progi->data : NULL;
7626 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
7628 assert(ANYOF_FLAGS(node)
7629 & (ANYOF_UTF8|ANYOF_NONBITMAP_NON_UTF8|ANYOF_LOC_FOLD));
7631 if (data && data->count) {
7632 const U32 n = ARG(node);
7634 if (data->what[n] == 's') {
7635 SV * const rv = MUTABLE_SV(data->data[n]);
7636 AV * const av = MUTABLE_AV(SvRV(rv));
7637 SV **const ary = AvARRAY(av);
7638 U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7640 si = *ary; /* ary[0] = the string to initialize the swash with */
7642 /* Elements 3 and 4 are either both present or both absent. [3] is
7643 * any inversion list generated at compile time; [4] indicates if
7644 * that inversion list has any user-defined properties in it. */
7645 if (av_tindex(av) >= 2) {
7646 if (only_utf8_locale_ptr
7648 && ary[2] != &PL_sv_undef)
7650 *only_utf8_locale_ptr = ary[2];
7653 assert(only_utf8_locale_ptr);
7654 *only_utf8_locale_ptr = NULL;
7657 if (av_tindex(av) >= 3) {
7660 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
7668 /* Element [1] is reserved for the set-up swash. If already there,
7669 * return it; if not, create it and store it there */
7670 if (ary[1] && SvROK(ary[1])) {
7673 else if (doinit && ((si && si != &PL_sv_undef)
7674 || (invlist && invlist != &PL_sv_undef))) {
7676 sw = _core_swash_init("utf8", /* the utf8 package */
7680 0, /* not from tr/// */
7683 (void)av_store(av, 1, sw);
7688 /* If requested, return a printable version of what this swash matches */
7690 SV* matches_string = newSVpvs("");
7692 /* The swash should be used, if possible, to get the data, as it
7693 * contains the resolved data. But this function can be called at
7694 * compile-time, before everything gets resolved, in which case we
7695 * return the currently best available information, which is the string
7696 * that will eventually be used to do that resolving, 'si' */
7697 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
7698 && (si && si != &PL_sv_undef))
7700 sv_catsv(matches_string, si);
7703 /* Add the inversion list to whatever we have. This may have come from
7704 * the swash, or from an input parameter */
7706 sv_catsv(matches_string, _invlist_contents(invlist));
7708 *listsvp = matches_string;
7713 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
7716 - reginclass - determine if a character falls into a character class
7718 n is the ANYOF regnode
7719 p is the target string
7720 p_end points to one byte beyond the end of the target string
7721 utf8_target tells whether p is in UTF-8.
7723 Returns true if matched; false otherwise.
7725 Note that this can be a synthetic start class, a combination of various
7726 nodes, so things you think might be mutually exclusive, such as locale,
7727 aren't. It can match both locale and non-locale
7732 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
7735 const char flags = ANYOF_FLAGS(n);
7739 PERL_ARGS_ASSERT_REGINCLASS;
7741 /* If c is not already the code point, get it. Note that
7742 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
7743 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
7745 c = utf8n_to_uvchr(p, p_end - p, &c_len,
7746 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
7747 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
7748 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
7749 * UTF8_ALLOW_FFFF */
7750 if (c_len == (STRLEN)-1)
7751 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
7754 /* If this character is potentially in the bitmap, check it */
7756 if (ANYOF_BITMAP_TEST(n, c))
7758 else if (flags & ANYOF_NON_UTF8_NON_ASCII_ALL
7764 else if (flags & ANYOF_LOCALE_FLAGS) {
7765 if (flags & ANYOF_LOC_FOLD) {
7766 if (ANYOF_BITMAP_TEST(n, PL_fold_locale[c])) {
7770 if (! match && ANYOF_POSIXL_TEST_ANY_SET(n)) {
7772 /* The data structure is arranged so bits 0, 2, 4, ... are set
7773 * if the class includes the Posix character class given by
7774 * bit/2; and 1, 3, 5, ... are set if the class includes the
7775 * complemented Posix class given by int(bit/2). So we loop
7776 * through the bits, each time changing whether we complement
7777 * the result or not. Suppose for the sake of illustration
7778 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
7779 * is set, it means there is a match for this ANYOF node if the
7780 * character is in the class given by the expression (0 / 2 = 0
7781 * = \w). If it is in that class, isFOO_lc() will return 1,
7782 * and since 'to_complement' is 0, the result will stay TRUE,
7783 * and we exit the loop. Suppose instead that bit 0 is 0, but
7784 * bit 1 is 1. That means there is a match if the character
7785 * matches \W. We won't bother to call isFOO_lc() on bit 0,
7786 * but will on bit 1. On the second iteration 'to_complement'
7787 * will be 1, so the exclusive or will reverse things, so we
7788 * are testing for \W. On the third iteration, 'to_complement'
7789 * will be 0, and we would be testing for \s; the fourth
7790 * iteration would test for \S, etc.
7792 * Note that this code assumes that all the classes are closed
7793 * under folding. For example, if a character matches \w, then
7794 * its fold does too; and vice versa. This should be true for
7795 * any well-behaved locale for all the currently defined Posix
7796 * classes, except for :lower: and :upper:, which are handled
7797 * by the pseudo-class :cased: which matches if either of the
7798 * other two does. To get rid of this assumption, an outer
7799 * loop could be used below to iterate over both the source
7800 * character, and its fold (if different) */
7803 int to_complement = 0;
7805 while (count < ANYOF_MAX) {
7806 if (ANYOF_POSIXL_TEST(n, count)
7807 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
7820 /* If the bitmap didn't (or couldn't) match, and something outside the
7821 * bitmap could match, try that. */
7823 if (c >= 256 && (flags & ANYOF_ABOVE_LATIN1_ALL)) {
7824 match = TRUE; /* Everything above 255 matches */
7826 else if ((flags & ANYOF_NONBITMAP_NON_UTF8)
7827 || (utf8_target && (flags & ANYOF_UTF8))
7828 || ((flags & ANYOF_LOC_FOLD)
7829 && IN_UTF8_CTYPE_LOCALE
7830 && ARG(n) != ANYOF_NONBITMAP_EMPTY))
7832 SV* only_utf8_locale = NULL;
7833 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
7840 } else { /* Convert to utf8 */
7841 utf8_p = utf8_buffer;
7842 append_utf8_from_native_byte(*p, &utf8_p);
7843 utf8_p = utf8_buffer;
7846 if (swash_fetch(sw, utf8_p, TRUE)) {
7850 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
7851 match = _invlist_contains_cp(only_utf8_locale, c);
7855 if (UNICODE_IS_SUPER(c)
7856 && (flags & ANYOF_WARN_SUPER)
7857 && ckWARN_d(WARN_NON_UNICODE))
7859 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7860 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
7864 #if ANYOF_INVERT != 1
7865 /* Depending on compiler optimization cBOOL takes time, so if don't have to
7867 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
7870 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
7871 return (flags & ANYOF_INVERT) ^ match;
7875 S_reghop3(U8 *s, SSize_t off, const U8* lim)
7877 /* return the position 'off' UTF-8 characters away from 's', forward if
7878 * 'off' >= 0, backwards if negative. But don't go outside of position
7879 * 'lim', which better be < s if off < 0 */
7881 PERL_ARGS_ASSERT_REGHOP3;
7884 while (off-- && s < lim) {
7885 /* XXX could check well-formedness here */
7890 while (off++ && s > lim) {
7892 if (UTF8_IS_CONTINUED(*s)) {
7893 while (s > lim && UTF8_IS_CONTINUATION(*s))
7896 /* XXX could check well-formedness here */
7903 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
7905 PERL_ARGS_ASSERT_REGHOP4;
7908 while (off-- && s < rlim) {
7909 /* XXX could check well-formedness here */
7914 while (off++ && s > llim) {
7916 if (UTF8_IS_CONTINUED(*s)) {
7917 while (s > llim && UTF8_IS_CONTINUATION(*s))
7920 /* XXX could check well-formedness here */
7926 /* like reghop3, but returns NULL on overrun, rather than returning last
7930 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
7932 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7935 while (off-- && s < lim) {
7936 /* XXX could check well-formedness here */
7943 while (off++ && s > lim) {
7945 if (UTF8_IS_CONTINUED(*s)) {
7946 while (s > lim && UTF8_IS_CONTINUATION(*s))
7949 /* XXX could check well-formedness here */
7958 /* when executing a regex that may have (?{}), extra stuff needs setting
7959 up that will be visible to the called code, even before the current
7960 match has finished. In particular:
7962 * $_ is localised to the SV currently being matched;
7963 * pos($_) is created if necessary, ready to be updated on each call-out
7965 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
7966 isn't set until the current pattern is successfully finished), so that
7967 $1 etc of the match-so-far can be seen;
7968 * save the old values of subbeg etc of the current regex, and set then
7969 to the current string (again, this is normally only done at the end
7974 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
7977 regexp *const rex = ReANY(reginfo->prog);
7978 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
7980 eval_state->rex = rex;
7983 /* Make $_ available to executed code. */
7984 if (reginfo->sv != DEFSV) {
7986 DEFSV_set(reginfo->sv);
7989 if (!(mg = mg_find_mglob(reginfo->sv))) {
7990 /* prepare for quick setting of pos */
7991 mg = sv_magicext_mglob(reginfo->sv);
7994 eval_state->pos_magic = mg;
7995 eval_state->pos = mg->mg_len;
7996 eval_state->pos_flags = mg->mg_flags;
7999 eval_state->pos_magic = NULL;
8001 if (!PL_reg_curpm) {
8002 /* PL_reg_curpm is a fake PMOP that we can attach the current
8003 * regex to and point PL_curpm at, so that $1 et al are visible
8004 * within a /(?{})/. It's just allocated once per interpreter the
8005 * first time its needed */
8006 Newxz(PL_reg_curpm, 1, PMOP);
8009 SV* const repointer = &PL_sv_undef;
8010 /* this regexp is also owned by the new PL_reg_curpm, which
8011 will try to free it. */
8012 av_push(PL_regex_padav, repointer);
8013 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
8014 PL_regex_pad = AvARRAY(PL_regex_padav);
8018 SET_reg_curpm(reginfo->prog);
8019 eval_state->curpm = PL_curpm;
8020 PL_curpm = PL_reg_curpm;
8021 if (RXp_MATCH_COPIED(rex)) {
8022 /* Here is a serious problem: we cannot rewrite subbeg,
8023 since it may be needed if this match fails. Thus
8024 $` inside (?{}) could fail... */
8025 eval_state->subbeg = rex->subbeg;
8026 eval_state->sublen = rex->sublen;
8027 eval_state->suboffset = rex->suboffset;
8028 eval_state->subcoffset = rex->subcoffset;
8030 eval_state->saved_copy = rex->saved_copy;
8032 RXp_MATCH_COPIED_off(rex);
8035 eval_state->subbeg = NULL;
8036 rex->subbeg = (char *)reginfo->strbeg;
8038 rex->subcoffset = 0;
8039 rex->sublen = reginfo->strend - reginfo->strbeg;
8043 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8046 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8048 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8049 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8052 Safefree(aux->poscache);
8056 /* undo the effects of S_setup_eval_state() */
8058 if (eval_state->subbeg) {
8059 regexp * const rex = eval_state->rex;
8060 rex->subbeg = eval_state->subbeg;
8061 rex->sublen = eval_state->sublen;
8062 rex->suboffset = eval_state->suboffset;
8063 rex->subcoffset = eval_state->subcoffset;
8065 rex->saved_copy = eval_state->saved_copy;
8067 RXp_MATCH_COPIED_on(rex);
8069 if (eval_state->pos_magic)
8071 eval_state->pos_magic->mg_len = eval_state->pos;
8072 eval_state->pos_magic->mg_flags =
8073 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8074 | (eval_state->pos_flags & MGf_BYTES);
8077 PL_curpm = eval_state->curpm;
8080 PL_regmatch_state = aux->old_regmatch_state;
8081 PL_regmatch_slab = aux->old_regmatch_slab;
8083 /* free all slabs above current one - this must be the last action
8084 * of this function, as aux and eval_state are allocated within
8085 * slabs and may be freed here */
8087 s = PL_regmatch_slab->next;
8089 PL_regmatch_slab->next = NULL;
8091 regmatch_slab * const osl = s;
8100 S_to_utf8_substr(pTHX_ regexp *prog)
8102 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8103 * on the converted value */
8107 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8110 if (prog->substrs->data[i].substr
8111 && !prog->substrs->data[i].utf8_substr) {
8112 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8113 prog->substrs->data[i].utf8_substr = sv;
8114 sv_utf8_upgrade(sv);
8115 if (SvVALID(prog->substrs->data[i].substr)) {
8116 if (SvTAIL(prog->substrs->data[i].substr)) {
8117 /* Trim the trailing \n that fbm_compile added last
8119 SvCUR_set(sv, SvCUR(sv) - 1);
8120 /* Whilst this makes the SV technically "invalid" (as its
8121 buffer is no longer followed by "\0") when fbm_compile()
8122 adds the "\n" back, a "\0" is restored. */
8123 fbm_compile(sv, FBMcf_TAIL);
8127 if (prog->substrs->data[i].substr == prog->check_substr)
8128 prog->check_utf8 = sv;
8134 S_to_byte_substr(pTHX_ regexp *prog)
8136 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8137 * on the converted value; returns FALSE if can't be converted. */
8141 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8144 if (prog->substrs->data[i].utf8_substr
8145 && !prog->substrs->data[i].substr) {
8146 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
8147 if (! sv_utf8_downgrade(sv, TRUE)) {
8150 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
8151 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
8152 /* Trim the trailing \n that fbm_compile added last
8154 SvCUR_set(sv, SvCUR(sv) - 1);
8155 fbm_compile(sv, FBMcf_TAIL);
8159 prog->substrs->data[i].substr = sv;
8160 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
8161 prog->check_substr = sv;
8170 * c-indentation-style: bsd
8172 * indent-tabs-mode: nil
8175 * ex: set ts=8 sts=4 sw=4 et: