5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "inline_invlist.c"
84 #include "unicode_constants.h"
87 /* At least one required character in the target string is expressible only in
89 static const char* const non_utf8_target_but_utf8_required
90 = "Can't match, because target string needs to be in UTF-8\n";
93 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
94 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
98 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
101 #define STATIC static
104 /* Valid only for non-utf8 strings: avoids the reginclass
105 * call if there are no complications: i.e., if everything matchable is
106 * straight forward in the bitmap */
107 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
108 : ANYOF_BITMAP_TEST(p,*(c)))
114 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
115 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
117 #define HOPc(pos,off) \
118 (char *)(reginfo->is_utf8_target \
119 ? reghop3((U8*)pos, off, \
120 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
123 #define HOPBACKc(pos, off) \
124 (char*)(reginfo->is_utf8_target \
125 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
126 : (pos - off >= reginfo->strbeg) \
130 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
131 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
133 /* lim must be +ve. Returns NULL on overshoot */
134 #define HOPMAYBE3(pos,off,lim) \
135 (reginfo->is_utf8_target \
136 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
137 : ((U8*)pos + off <= lim) \
141 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
142 * off must be >=0; args should be vars rather than expressions */
143 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
144 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
145 : (U8*)((pos + off) > lim ? lim : (pos + off)))
147 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
148 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
150 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
152 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
153 #define NEXTCHR_IS_EOS (nextchr < 0)
155 #define SET_nextchr \
156 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
158 #define SET_locinput(p) \
163 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
165 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
166 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
167 1, 0, invlist, &flags); \
172 /* If in debug mode, we test that a known character properly matches */
174 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
177 utf8_char_in_property) \
178 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
179 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
181 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
184 utf8_char_in_property) \
185 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
188 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
189 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
191 PL_XPosix_ptrs[_CC_WORDCHAR], \
192 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
194 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
196 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_regular_begin, \
197 "_X_regular_begin", \
199 LATIN_CAPITAL_LETTER_SHARP_S_UTF8); \
200 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_extend, \
203 COMBINING_GRAVE_ACCENT_UTF8); \
206 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
207 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
209 /* for use after a quantifier and before an EXACT-like node -- japhy */
210 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
212 * NOTE that *nothing* that affects backtracking should be in here, specifically
213 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
214 * node that is in between two EXACT like nodes when ascertaining what the required
215 * "follow" character is. This should probably be moved to regex compile time
216 * although it may be done at run time beause of the REF possibility - more
217 * investigation required. -- demerphq
219 #define JUMPABLE(rn) ( \
221 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
223 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
224 OP(rn) == PLUS || OP(rn) == MINMOD || \
226 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
228 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
230 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
233 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
234 we don't need this definition. */
235 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
236 #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 )
237 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
240 /* ... so we use this as its faster. */
241 #define IS_TEXT(rn) ( OP(rn)==EXACT )
242 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
243 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
244 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
249 Search for mandatory following text node; for lookahead, the text must
250 follow but for lookbehind (rn->flags != 0) we skip to the next step.
252 #define FIND_NEXT_IMPT(rn) STMT_START { \
253 while (JUMPABLE(rn)) { \
254 const OPCODE type = OP(rn); \
255 if (type == SUSPEND || PL_regkind[type] == CURLY) \
256 rn = NEXTOPER(NEXTOPER(rn)); \
257 else if (type == PLUS) \
259 else if (type == IFMATCH) \
260 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
261 else rn += NEXT_OFF(rn); \
265 /* These constants are for finding GCB=LV and GCB=LVT in the CLUMP regnode.
266 * These are for the pre-composed Hangul syllables, which are all in a
267 * contiguous block and arranged there in such a way so as to facilitate
268 * alorithmic determination of their characteristics. As such, they don't need
269 * a swash, but can be determined by simple arithmetic. Almost all are
270 * GCB=LVT, but every 28th one is a GCB=LV */
271 #define SBASE 0xAC00 /* Start of block */
272 #define SCount 11172 /* Length of block */
275 #define SLAB_FIRST(s) (&(s)->states[0])
276 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
278 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
279 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
280 static regmatch_state * S_push_slab(pTHX);
282 #define REGCP_PAREN_ELEMS 3
283 #define REGCP_OTHER_ELEMS 3
284 #define REGCP_FRAME_ELEMS 1
285 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
286 * are needed for the regexp context stack bookkeeping. */
289 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)
375 GET_RE_DEBUG_FLAGS_DECL;
377 PERL_ARGS_ASSERT_REGCPPOP;
379 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
381 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
382 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
383 rex->lastcloseparen = SSPOPINT;
384 rex->lastparen = SSPOPINT;
385 *maxopenparen_p = SSPOPINT;
387 i -= REGCP_OTHER_ELEMS;
388 /* Now restore the parentheses context. */
390 if (i || rex->lastparen + 1 <= rex->nparens)
391 PerlIO_printf(Perl_debug_log,
392 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
397 paren = *maxopenparen_p;
398 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
400 rex->offs[paren].start_tmp = SSPOPINT;
401 rex->offs[paren].start = SSPOPIV;
403 if (paren <= rex->lastparen)
404 rex->offs[paren].end = tmps;
405 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
406 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
408 (IV)rex->offs[paren].start,
409 (IV)rex->offs[paren].start_tmp,
410 (IV)rex->offs[paren].end,
411 (paren > rex->lastparen ? "(skipped)" : ""));
416 /* It would seem that the similar code in regtry()
417 * already takes care of this, and in fact it is in
418 * a better location to since this code can #if 0-ed out
419 * but the code in regtry() is needed or otherwise tests
420 * requiring null fields (pat.t#187 and split.t#{13,14}
421 * (as of patchlevel 7877) will fail. Then again,
422 * this code seems to be necessary or otherwise
423 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
424 * --jhi updated by dapm */
425 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
426 if (i > *maxopenparen_p)
427 rex->offs[i].start = -1;
428 rex->offs[i].end = -1;
429 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
430 " \\%"UVuf": %s ..-1 undeffing\n",
432 (i > *maxopenparen_p) ? "-1" : " "
438 /* restore the parens and associated vars at savestack position ix,
439 * but without popping the stack */
442 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
444 I32 tmpix = PL_savestack_ix;
445 PL_savestack_ix = ix;
446 regcppop(rex, maxopenparen_p);
447 PL_savestack_ix = tmpix;
450 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
453 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
455 /* Returns a boolean as to whether or not 'character' is a member of the
456 * Posix character class given by 'classnum' that should be equivalent to a
457 * value in the typedef '_char_class_number'.
459 * Ideally this could be replaced by a just an array of function pointers
460 * to the C library functions that implement the macros this calls.
461 * However, to compile, the precise function signatures are required, and
462 * these may vary from platform to to platform. To avoid having to figure
463 * out what those all are on each platform, I (khw) am using this method,
464 * which adds an extra layer of function call overhead (unless the C
465 * optimizer strips it away). But we don't particularly care about
466 * performance with locales anyway. */
468 switch ((_char_class_number) classnum) {
469 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
470 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
471 case _CC_ENUM_ASCII: return isASCII_LC(character);
472 case _CC_ENUM_BLANK: return isBLANK_LC(character);
473 case _CC_ENUM_CASED: return isLOWER_LC(character)
474 || isUPPER_LC(character);
475 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
476 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
477 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
478 case _CC_ENUM_LOWER: return isLOWER_LC(character);
479 case _CC_ENUM_PRINT: return isPRINT_LC(character);
480 case _CC_ENUM_PSXSPC: return isPSXSPC_LC(character);
481 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
482 case _CC_ENUM_SPACE: return isSPACE_LC(character);
483 case _CC_ENUM_UPPER: return isUPPER_LC(character);
484 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
485 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
486 default: /* VERTSPACE should never occur in locales */
487 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
490 assert(0); /* NOTREACHED */
495 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
497 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
498 * 'character' is a member of the Posix character class given by 'classnum'
499 * that should be equivalent to a value in the typedef
500 * '_char_class_number'.
502 * This just calls isFOO_lc on the code point for the character if it is in
503 * the range 0-255. Outside that range, all characters avoid Unicode
504 * rules, ignoring any locale. So use the Unicode function if this class
505 * requires a swash, and use the Unicode macro otherwise. */
507 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
509 if (UTF8_IS_INVARIANT(*character)) {
510 return isFOO_lc(classnum, *character);
512 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
513 return isFOO_lc(classnum,
514 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
517 if (classnum < _FIRST_NON_SWASH_CC) {
519 /* Initialize the swash unless done already */
520 if (! PL_utf8_swash_ptrs[classnum]) {
521 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
522 PL_utf8_swash_ptrs[classnum] =
523 _core_swash_init("utf8",
526 PL_XPosix_ptrs[classnum], &flags);
529 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
531 TRUE /* is UTF */ ));
534 switch ((_char_class_number) classnum) {
536 case _CC_ENUM_PSXSPC: return is_XPERLSPACE_high(character);
538 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
539 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
540 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
541 default: return 0; /* Things like CNTRL are always
545 assert(0); /* NOTREACHED */
550 * pregexec and friends
553 #ifndef PERL_IN_XSUB_RE
555 - pregexec - match a regexp against a string
558 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
559 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
560 /* stringarg: the point in the string at which to begin matching */
561 /* strend: pointer to null at end of string */
562 /* strbeg: real beginning of string */
563 /* minend: end of match must be >= minend bytes after stringarg. */
564 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
565 * itself is accessed via the pointers above */
566 /* nosave: For optimizations. */
568 PERL_ARGS_ASSERT_PREGEXEC;
571 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
572 nosave ? 0 : REXEC_COPY_STR);
578 /* re_intuit_start():
580 * Based on some optimiser hints, try to find the earliest position in the
581 * string where the regex could match.
583 * rx: the regex to match against
584 * sv: the SV being matched: only used for utf8 flag; the string
585 * itself is accessed via the pointers below. Note that on
586 * something like an overloaded SV, SvPOK(sv) may be false
587 * and the string pointers may point to something unrelated to
589 * strbeg: real beginning of string
590 * strpos: the point in the string at which to begin matching
591 * strend: pointer to the byte following the last char of the string
592 * flags currently unused; set to 0
593 * data: currently unused; set to NULL
595 * The basic idea of re_intuit_start() is to use some known information
596 * about the pattern, namely:
598 * a) the longest known anchored substring (i.e. one that's at a
599 * constant offset from the beginning of the pattern; but not
600 * necessarily at a fixed offset from the beginning of the
602 * b) the longest floating substring (i.e. one that's not at a constant
603 * offset from the beginning of the pattern);
604 * c) Whether the pattern is anchored to the string; either
605 * an absolute anchor: /^../, or anchored to \n: /^.../m,
606 * or anchored to pos(): /\G/;
607 * d) A start class: a real or synthetic character class which
608 * represents which characters are legal at the start of the pattern;
610 * to either quickly reject the match, or to find the earliest position
611 * within the string at which the pattern might match, thus avoiding
612 * running the full NFA engine at those earlier locations, only to
613 * eventually fail and retry further along.
615 * Returns NULL if the pattern can't match, or returns the address within
616 * the string which is the earliest place the match could occur.
618 * The longest of the anchored and floating substrings is called 'check'
619 * and is checked first. The other is called 'other' and is checked
620 * second. The 'other' substring may not be present. For example,
622 * /(abc|xyz)ABC\d{0,3}DEFG/
626 * check substr (float) = "DEFG", offset 6..9 chars
627 * other substr (anchored) = "ABC", offset 3..3 chars
630 * Be aware that during the course of this function, sometimes 'anchored'
631 * refers to a substring being anchored relative to the start of the
632 * pattern, and sometimes to the pattern itself being anchored relative to
633 * the string. For example:
635 * /\dabc/: "abc" is anchored to the pattern;
636 * /^\dabc/: "abc" is anchored to the pattern and the string;
637 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
638 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
639 * but the pattern is anchored to the string.
643 Perl_re_intuit_start(pTHX_
646 const char * const strbeg,
650 re_scream_pos_data *data)
653 struct regexp *const prog = ReANY(rx);
654 SSize_t start_shift = prog->check_offset_min;
655 /* Should be nonnegative! */
656 SSize_t end_shift = 0;
657 /* current lowest pos in string where the regex can start matching */
658 char *rx_origin = strpos;
660 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
661 U8 other_ix = 1 - prog->substrs->check_ix;
663 char *other_last = strpos;/* latest pos 'other' substr already checked to */
664 char *check_at = NULL; /* check substr found at this pos */
665 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
666 RXi_GET_DECL(prog,progi);
667 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
668 regmatch_info *const reginfo = ®info_buf;
669 GET_RE_DEBUG_FLAGS_DECL;
671 PERL_ARGS_ASSERT_RE_INTUIT_START;
672 PERL_UNUSED_ARG(flags);
673 PERL_UNUSED_ARG(data);
675 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
676 "Intuit: trying to determine minimum start position...\n"));
678 /* for now, assume that all substr offsets are positive. If at some point
679 * in the future someone wants to do clever things with look-behind and
680 * -ve offsets, they'll need to fix up any code in this function
681 * which uses these offsets. See the thread beginning
682 * <20140113145929.GF27210@iabyn.com>
684 assert(prog->substrs->data[0].min_offset >= 0);
685 assert(prog->substrs->data[0].max_offset >= 0);
686 assert(prog->substrs->data[1].min_offset >= 0);
687 assert(prog->substrs->data[1].max_offset >= 0);
688 assert(prog->substrs->data[2].min_offset >= 0);
689 assert(prog->substrs->data[2].max_offset >= 0);
691 /* for now, assume that if both present, that the floating substring
692 * doesn't start before the anchored substring.
693 * If you break this assumption (e.g. doing better optimisations
694 * with lookahead/behind), then you'll need to audit the code in this
695 * function carefully first
698 ! ( (prog->anchored_utf8 || prog->anchored_substr)
699 && (prog->float_utf8 || prog->float_substr))
700 || (prog->float_min_offset >= prog->anchored_offset));
702 /* byte rather than char calculation for efficiency. It fails
703 * to quickly reject some cases that can't match, but will reject
704 * them later after doing full char arithmetic */
705 if (prog->minlen > strend - strpos) {
706 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
707 " String too short...\n"));
711 reginfo->is_utf8_target = cBOOL(utf8_target);
712 reginfo->info_aux = NULL;
713 reginfo->strbeg = strbeg;
714 reginfo->strend = strend;
715 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
717 /* not actually used within intuit, but zero for safety anyway */
718 reginfo->poscache_maxiter = 0;
721 if (!prog->check_utf8 && prog->check_substr)
722 to_utf8_substr(prog);
723 check = prog->check_utf8;
725 if (!prog->check_substr && prog->check_utf8) {
726 if (! to_byte_substr(prog)) {
727 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
730 check = prog->check_substr;
733 /* dump the various substring data */
734 DEBUG_OPTIMISE_MORE_r({
736 for (i=0; i<=2; i++) {
737 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
738 : prog->substrs->data[i].substr);
742 PerlIO_printf(Perl_debug_log,
743 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
744 " useful=%"IVdf" utf8=%d [%s]\n",
746 (IV)prog->substrs->data[i].min_offset,
747 (IV)prog->substrs->data[i].max_offset,
748 (IV)prog->substrs->data[i].end_shift,
755 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
757 /* ml_anch: check after \n?
759 * A note about IMPLICIT: on an un-anchored pattern beginning
760 * with /.*.../, these flags will have been added by the
762 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
763 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
765 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
766 && !(prog->intflags & PREGf_IMPLICIT);
768 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
769 /* we are only allowed to match at BOS or \G */
771 /* trivially reject if there's a BOS anchor and we're not at BOS.
773 * Note that we don't try to do a similar quick reject for
774 * \G, since generally the caller will have calculated strpos
775 * based on pos() and gofs, so the string is already correctly
776 * anchored by definition; and handling the exceptions would
777 * be too fiddly (e.g. REXEC_IGNOREPOS).
779 if ( strpos != strbeg
780 && (prog->intflags & (PREGf_ANCH_BOL|PREGf_ANCH_SBOL)))
782 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
783 " Not at start...\n"));
787 /* in the presence of an anchor, the anchored (relative to the
788 * start of the regex) substr must also be anchored relative
789 * to strpos. So quickly reject if substr isn't found there.
790 * This works for \G too, because the caller will already have
791 * subtracted gofs from pos, and gofs is the offset from the
792 * \G to the start of the regex. For example, in /.abc\Gdef/,
793 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
794 * caller will have set strpos=pos()-4; we look for the substr
795 * at position pos()-4+1, which lines up with the "a" */
797 if (prog->check_offset_min == prog->check_offset_max
798 && !(prog->intflags & PREGf_CANY_SEEN))
800 /* Substring at constant offset from beg-of-str... */
801 SSize_t slen = SvCUR(check);
802 char *s = HOP3c(strpos, prog->check_offset_min, strend);
804 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
805 " Looking for check substr at fixed offset %"IVdf"...\n",
806 (IV)prog->check_offset_min));
809 /* In this case, the regex is anchored at the end too.
810 * Unless it's a multiline match, the lengths must match
811 * exactly, give or take a \n. NB: slen >= 1 since
812 * the last char of check is \n */
814 && ( strend - s > slen
815 || strend - s < slen - 1
816 || (strend - s == slen && strend[-1] != '\n')))
818 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
819 " String too long...\n"));
822 /* Now should match s[0..slen-2] */
825 if (slen && (*SvPVX_const(check) != *s
826 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
828 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
829 " String not equal...\n"));
834 goto success_at_start;
839 end_shift = prog->check_end_shift;
841 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
843 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
844 (IV)end_shift, RX_PRECOMP(prog));
849 /* This is the (re)entry point of the main loop in this function.
850 * The goal of this loop is to:
851 * 1) find the "check" substring in the region rx_origin..strend
852 * (adjusted by start_shift / end_shift). If not found, reject
854 * 2) If it exists, look for the "other" substr too if defined; for
855 * example, if the check substr maps to the anchored substr, then
856 * check the floating substr, and vice-versa. If not found, go
857 * back to (1) with rx_origin suitably incremented.
858 * 3) If we find an rx_origin position that doesn't contradict
859 * either of the substrings, then check the possible additional
860 * constraints on rx_origin of /^.../m or a known start class.
861 * If these fail, then depending on which constraints fail, jump
862 * back to here, or to various other re-entry points further along
863 * that skip some of the first steps.
864 * 4) If we pass all those tests, update the BmUSEFUL() count on the
865 * substring. If the start position was determined to be at the
866 * beginning of the string - so, not rejected, but not optimised,
867 * since we have to run regmatch from position 0 - decrement the
868 * BmUSEFUL() count. Otherwise increment it.
872 /* first, look for the 'check' substring */
878 DEBUG_OPTIMISE_MORE_r({
879 PerlIO_printf(Perl_debug_log,
880 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
881 " Start shift: %"IVdf" End shift %"IVdf
882 " Real end Shift: %"IVdf"\n",
883 (IV)(rx_origin - strpos),
884 (IV)prog->check_offset_min,
887 (IV)prog->check_end_shift);
890 if (prog->intflags & PREGf_CANY_SEEN) {
891 start_point= (U8*)(rx_origin + start_shift);
892 end_point= (U8*)(strend - end_shift);
893 if (start_point > end_point)
896 end_point = HOP3(strend, -end_shift, strbeg);
897 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
903 /* If the regex is absolutely anchored to either the start of the
904 * string (BOL,SBOL) or to pos() (ANCH_GPOS), then
905 * check_offset_max represents an upper bound on the string where
906 * the substr could start. For the ANCH_GPOS case, we assume that
907 * the caller of intuit will have already set strpos to
908 * pos()-gofs, so in this case strpos + offset_max will still be
909 * an upper bound on the substr.
912 && prog->intflags & PREGf_ANCH
913 && prog->check_offset_max != SSize_t_MAX)
915 SSize_t len = SvCUR(check) - !!SvTAIL(check);
916 const char * const anchor =
917 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
919 /* do a bytes rather than chars comparison. It's conservative;
920 * so it skips doing the HOP if the result can't possibly end
921 * up earlier than the old value of end_point.
923 if ((char*)end_point - anchor > prog->check_offset_max) {
924 end_point = HOP3lim((U8*)anchor,
925 prog->check_offset_max,
931 DEBUG_OPTIMISE_MORE_r({
932 PerlIO_printf(Perl_debug_log, " fbm_instr len=%d str=<%.*s>\n",
933 (int)(end_point - start_point),
934 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
938 check_at = fbm_instr( start_point, end_point,
939 check, multiline ? FBMrf_MULTILINE : 0);
941 /* Update the count-of-usability, remove useless subpatterns,
945 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
946 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
947 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
948 (check_at ? "Found" : "Did not find"),
949 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
950 ? "anchored" : "floating"),
953 (check_at ? " at offset " : "...\n") );
958 /* Finish the diagnostic message */
959 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(check_at - strpos)) );
961 /* set rx_origin to the minimum position where the regex could start
962 * matching, given the constraint of the just-matched check substring.
963 * But don't set it lower than previously.
966 if (check_at - rx_origin > prog->check_offset_max)
967 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
971 /* now look for the 'other' substring if defined */
973 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
974 : prog->substrs->data[other_ix].substr)
976 /* Take into account the "other" substring. */
980 struct reg_substr_datum *other;
983 other = &prog->substrs->data[other_ix];
985 /* if "other" is anchored:
986 * we've previously found a floating substr starting at check_at.
987 * This means that the regex origin must lie somewhere
988 * between min (rx_origin): HOP3(check_at, -check_offset_max)
989 * and max: HOP3(check_at, -check_offset_min)
990 * (except that min will be >= strpos)
991 * So the fixed substr must lie somewhere between
992 * HOP3(min, anchored_offset)
993 * HOP3(max, anchored_offset) + SvCUR(substr)
996 /* if "other" is floating
997 * Calculate last1, the absolute latest point where the
998 * floating substr could start in the string, ignoring any
999 * constraints from the earlier fixed match. It is calculated
1002 * strend - prog->minlen (in chars) is the absolute latest
1003 * position within the string where the origin of the regex
1004 * could appear. The latest start point for the floating
1005 * substr is float_min_offset(*) on from the start of the
1006 * regex. last1 simply combines thee two offsets.
1008 * (*) You might think the latest start point should be
1009 * float_max_offset from the regex origin, and technically
1010 * you'd be correct. However, consider
1012 * Here, float min, max are 3,5 and minlen is 7.
1013 * This can match either
1017 * In the first case, the regex matches minlen chars; in the
1018 * second, minlen+1, in the third, minlen+2.
1019 * In the first case, the floating offset is 3 (which equals
1020 * float_min), in the second, 4, and in the third, 5 (which
1021 * equals float_max). In all cases, the floating string bcd
1022 * can never start more than 4 chars from the end of the
1023 * string, which equals minlen - float_min. As the substring
1024 * starts to match more than float_min from the start of the
1025 * regex, it makes the regex match more than minlen chars,
1026 * and the two cancel each other out. So we can always use
1027 * float_min - minlen, rather than float_max - minlen for the
1028 * latest position in the string.
1030 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1031 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1034 assert(prog->minlen >= other->min_offset);
1035 last1 = HOP3c(strend,
1036 other->min_offset - prog->minlen, strbeg);
1038 if (other_ix) {/* i.e. if (other-is-float) */
1039 /* last is the latest point where the floating substr could
1040 * start, *given* any constraints from the earlier fixed
1041 * match. This constraint is that the floating string starts
1042 * <= float_max_offset chars from the regex origin (rx_origin).
1043 * If this value is less than last1, use it instead.
1045 assert(rx_origin <= last1);
1047 /* this condition handles the offset==infinity case, and
1048 * is a short-cut otherwise. Although it's comparing a
1049 * byte offset to a char length, it does so in a safe way,
1050 * since 1 char always occupies 1 or more bytes,
1051 * so if a string range is (last1 - rx_origin) bytes,
1052 * it will be less than or equal to (last1 - rx_origin)
1053 * chars; meaning it errs towards doing the accurate HOP3
1054 * rather than just using last1 as a short-cut */
1055 (last1 - rx_origin) < other->max_offset
1057 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1060 assert(strpos + start_shift <= check_at);
1061 last = HOP4c(check_at, other->min_offset - start_shift,
1065 s = HOP3c(rx_origin, other->min_offset, strend);
1066 if (s < other_last) /* These positions already checked */
1069 must = utf8_target ? other->utf8_substr : other->substr;
1070 assert(SvPOK(must));
1073 (unsigned char*)last + SvCUR(must) - (SvTAIL(must)!=0),
1075 multiline ? FBMrf_MULTILINE : 0
1078 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1079 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1080 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1081 s ? "Found" : "Contradicts",
1082 other_ix ? "floating" : "anchored",
1083 quoted, RE_SV_TAIL(must));
1088 /* last1 is latest possible substr location. If we didn't
1089 * find it before there, we never will */
1090 if (last >= last1) {
1091 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1092 ", giving up...\n"));
1096 /* try to find the check substr again at a later
1097 * position. Maybe next time we'll find the "other" substr
1099 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1100 ", trying %s at offset %ld...\n",
1101 (other_ix ? "floating" : "anchored"),
1102 (long)(HOP3c(check_at, 1, strend) - strpos)));
1104 other_last = HOP3c(last, 1, strend) /* highest failure */;
1106 other_ix /* i.e. if other-is-float */
1107 ? HOP3c(rx_origin, 1, strend)
1108 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1112 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
1113 (long)(s - strpos)));
1115 if (other_ix) { /* if (other-is-float) */
1116 /* other_last is set to s, not s+1, since its possible for
1117 * a floating substr to fail first time, then succeed
1118 * second time at the same floating position; e.g.:
1119 * "-AB--AABZ" =~ /\wAB\d*Z/
1120 * The first time round, anchored and float match at
1121 * "-(AB)--AAB(Z)" then fail on the initial \w character
1122 * class. Second time round, they match at "-AB--A(AB)(Z)".
1127 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1128 other_last = HOP3c(s, 1, strend);
1133 DEBUG_OPTIMISE_MORE_r(
1134 PerlIO_printf(Perl_debug_log,
1135 " Check-only match: offset min:%"IVdf" max:%"IVdf
1136 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1137 " strend-strpos:%"IVdf"\n",
1138 (IV)prog->check_offset_min,
1139 (IV)prog->check_offset_max,
1140 (IV)(check_at-strpos),
1141 (IV)(rx_origin-strpos),
1142 (IV)(rx_origin-check_at),
1148 postprocess_substr_matches:
1150 /* handle the extra constraint of /^.../m if present */
1152 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1155 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1156 " looking for /^/m anchor"));
1158 /* we have failed the constraint of a \n before rx_origin.
1159 * Find the next \n, if any, even if it's beyond the current
1160 * anchored and/or floating substrings. Whether we should be
1161 * scanning ahead for the next \n or the next substr is debatable.
1162 * On the one hand you'd expect rare substrings to appear less
1163 * often than \n's. On the other hand, searching for \n means
1164 * we're effectively flipping been check_substr and "\n" on each
1165 * iteration as the current "rarest" string candidate, which
1166 * means for example that we'll quickly reject the whole string if
1167 * hasn't got a \n, rather than trying every substr position
1171 s = HOP3c(strend, - prog->minlen, strpos);
1172 if (s <= rx_origin ||
1173 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1175 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1176 " Did not find /%s^%s/m...\n",
1177 PL_colors[0], PL_colors[1]));
1181 /* earliest possible origin is 1 char after the \n.
1182 * (since *rx_origin == '\n', it's safe to ++ here rather than
1183 * HOP(rx_origin, 1)) */
1186 if (prog->substrs->check_ix == 0 /* check is anchored */
1187 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1189 /* Position contradicts check-string; either because
1190 * check was anchored (and thus has no wiggle room),
1191 * or check was float and rx_origin is above the float range */
1192 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1193 " Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
1194 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
1198 /* if we get here, the check substr must have been float,
1199 * is in range, and we may or may not have had an anchored
1200 * "other" substr which still contradicts */
1201 assert(prog->substrs->check_ix); /* check is float */
1203 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1204 /* whoops, the anchored "other" substr exists, so we still
1205 * contradict. On the other hand, the float "check" substr
1206 * didn't contradict, so just retry the anchored "other"
1208 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1209 " Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
1210 PL_colors[0], PL_colors[1],
1211 (long)(rx_origin - strpos),
1212 (long)(rx_origin - strpos + prog->anchored_offset)));
1213 goto do_other_substr;
1216 /* success: we don't contradict the found floating substring
1217 * (and there's no anchored substr). */
1218 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1219 " Found /%s^%s/m at offset %ld...\n",
1220 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
1223 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1224 " (multiline anchor test skipped)\n"));
1230 /* if we have a starting character class, then test that extra constraint.
1231 * (trie stclasses are too expensive to use here, we are better off to
1232 * leave it to regmatch itself) */
1234 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1235 const U8* const str = (U8*)STRING(progi->regstclass);
1237 /* XXX this value could be pre-computed */
1238 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1239 ? (reginfo->is_utf8_pat
1240 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1241 : STR_LEN(progi->regstclass))
1245 /* latest pos that a matching float substr constrains rx start to */
1246 char *rx_max_float = NULL;
1248 /* if the current rx_origin is anchored, either by satisfying an
1249 * anchored substring constraint, or a /^.../m constraint, then we
1250 * can reject the current origin if the start class isn't found
1251 * at the current position. If we have a float-only match, then
1252 * rx_origin is constrained to a range; so look for the start class
1253 * in that range. if neither, then look for the start class in the
1254 * whole rest of the string */
1256 /* XXX DAPM it's not clear what the minlen test is for, and why
1257 * it's not used in the floating case. Nothing in the test suite
1258 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1259 * Here are some old comments, which may or may not be correct:
1261 * minlen == 0 is possible if regstclass is \b or \B,
1262 * and the fixed substr is ''$.
1263 * Since minlen is already taken into account, rx_origin+1 is
1264 * before strend; accidentally, minlen >= 1 guaranties no false
1265 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1266 * 0) below assumes that regstclass does not come from lookahead...
1267 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1268 * This leaves EXACTF-ish only, which are dealt with in
1272 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1273 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1274 else if (prog->float_substr || prog->float_utf8) {
1275 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1276 endpos= HOP3c(rx_max_float, cl_l, strend);
1281 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1282 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1283 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1284 (IV)start_shift, (IV)(check_at - strbeg),
1285 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1287 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1290 if (endpos == strend) {
1291 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1292 " Could not match STCLASS...\n") );
1295 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1296 " This position contradicts STCLASS...\n") );
1297 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1298 && !(prog->intflags & PREGf_IMPLICIT))
1301 /* Contradict one of substrings */
1302 if (prog->anchored_substr || prog->anchored_utf8) {
1303 if (prog->substrs->check_ix == 1) { /* check is float */
1304 /* Have both, check_string is floating */
1305 assert(rx_origin + start_shift <= check_at);
1306 if (rx_origin + start_shift != check_at) {
1307 /* not at latest position float substr could match:
1308 * Recheck anchored substring, but not floating.
1309 * The condition above is in bytes rather than
1310 * chars for efficiency. It's conservative, in
1311 * that it errs on the side of doing 'goto
1312 * do_other_substr', where a more accurate
1313 * char-based calculation will be done */
1314 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1315 " Looking for anchored substr starting at offset %ld...\n",
1316 (long)(other_last - strpos)) );
1317 goto do_other_substr;
1325 /* In the presence of ml_anch, we might be able to
1326 * find another \n without breaking the current float
1329 /* strictly speaking this should be HOP3c(..., 1, ...),
1330 * but since we goto a block of code that's going to
1331 * search for the next \n if any, its safe here */
1333 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1334 " Looking for /%s^%s/m starting at offset %ld...\n",
1335 PL_colors[0], PL_colors[1],
1336 (long)(rx_origin - strpos)) );
1337 goto postprocess_substr_matches;
1340 /* strictly speaking this can never be true; but might
1341 * be if we ever allow intuit without substrings */
1342 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1345 rx_origin = rx_max_float;
1348 /* at this point, any matching substrings have been
1349 * contradicted. Start again... */
1351 rx_origin = HOP3c(rx_origin, 1, strend);
1353 /* uses bytes rather than char calculations for efficiency.
1354 * It's conservative: it errs on the side of doing 'goto restart',
1355 * where there is code that does a proper char-based test */
1356 if (rx_origin + start_shift + end_shift > strend) {
1357 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1358 " Could not match STCLASS...\n") );
1361 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1362 " Looking for %s substr starting at offset %ld...\n",
1363 (prog->substrs->check_ix ? "floating" : "anchored"),
1364 (long)(rx_origin + start_shift - strpos)) );
1370 if (rx_origin != s) {
1371 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1372 " By STCLASS: moving %ld --> %ld\n",
1373 (long)(rx_origin - strpos), (long)(s - strpos))
1377 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1378 " Does not contradict STCLASS...\n");
1383 /* Decide whether using the substrings helped */
1385 if (rx_origin != strpos) {
1386 /* Fixed substring is found far enough so that the match
1387 cannot start at strpos. */
1389 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1390 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1393 /* The found rx_origin position does not prohibit matching at
1394 * strpos, so calling intuit didn't gain us anything. Decrement
1395 * the BmUSEFUL() count on the check substring, and if we reach
1397 if (!(prog->intflags & PREGf_NAUGHTY)
1399 prog->check_utf8 /* Could be deleted already */
1400 && --BmUSEFUL(prog->check_utf8) < 0
1401 && (prog->check_utf8 == prog->float_utf8)
1403 prog->check_substr /* Could be deleted already */
1404 && --BmUSEFUL(prog->check_substr) < 0
1405 && (prog->check_substr == prog->float_substr)
1408 /* If flags & SOMETHING - do not do it many times on the same match */
1409 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1410 /* XXX Does the destruction order has to change with utf8_target? */
1411 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1412 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1413 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1414 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1415 check = NULL; /* abort */
1416 /* XXXX This is a remnant of the old implementation. It
1417 looks wasteful, since now INTUIT can use many
1418 other heuristics. */
1419 prog->extflags &= ~RXf_USE_INTUIT;
1423 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1424 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1425 PL_colors[4], PL_colors[5], (long)(rx_origin - strpos)) );
1429 fail_finish: /* Substring not found */
1430 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1431 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1433 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1434 PL_colors[4], PL_colors[5]));
1439 #define DECL_TRIE_TYPE(scan) \
1440 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1441 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold } \
1442 trie_type = ((scan->flags == EXACT) \
1443 ? (utf8_target ? trie_utf8 : trie_plain) \
1444 : (scan->flags == EXACTFA) \
1445 ? (utf8_target ? trie_utf8_exactfa_fold : trie_latin_utf8_exactfa_fold) \
1446 : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
1448 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1451 U8 flags = FOLD_FLAGS_FULL; \
1452 switch (trie_type) { \
1453 case trie_utf8_exactfa_fold: \
1454 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1456 case trie_utf8_fold: \
1457 if ( foldlen>0 ) { \
1458 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1463 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1464 len = UTF8SKIP(uc); \
1465 skiplen = UNISKIP( uvc ); \
1466 foldlen -= skiplen; \
1467 uscan = foldbuf + skiplen; \
1470 case trie_latin_utf8_exactfa_fold: \
1471 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1473 case trie_latin_utf8_fold: \
1474 if ( foldlen>0 ) { \
1475 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1481 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1482 skiplen = UNISKIP( uvc ); \
1483 foldlen -= skiplen; \
1484 uscan = foldbuf + skiplen; \
1488 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1495 charid = trie->charmap[ uvc ]; \
1499 if (widecharmap) { \
1500 SV** const svpp = hv_fetch(widecharmap, \
1501 (char*)&uvc, sizeof(UV), 0); \
1503 charid = (U16)SvIV(*svpp); \
1508 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1512 && (ln == 1 || folder(s, pat_string, ln)) \
1513 && (reginfo->intuit || regtry(reginfo, &s)) )\
1519 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1521 while (s < strend) { \
1527 #define REXEC_FBC_SCAN(CoDe) \
1529 while (s < strend) { \
1535 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1536 REXEC_FBC_UTF8_SCAN( \
1538 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1547 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1550 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1559 #define REXEC_FBC_TRYIT \
1560 if ((reginfo->intuit || regtry(reginfo, &s))) \
1563 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1564 if (utf8_target) { \
1565 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1568 REXEC_FBC_CLASS_SCAN(CoNd); \
1571 #define DUMP_EXEC_POS(li,s,doutf8) \
1572 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1576 #define UTF8_NOLOAD(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1577 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1578 tmp = TEST_NON_UTF8(tmp); \
1579 REXEC_FBC_UTF8_SCAN( \
1580 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1589 #define UTF8_LOAD(TeSt1_UtF8, TeSt2_UtF8, IF_SUCCESS, IF_FAIL) \
1590 if (s == reginfo->strbeg) { \
1594 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1595 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1596 0, UTF8_ALLOW_DEFAULT); \
1599 LOAD_UTF8_CHARCLASS_ALNUM(); \
1600 REXEC_FBC_UTF8_SCAN( \
1601 if (tmp == ! (TeSt2_UtF8)) { \
1610 /* The only difference between the BOUND and NBOUND cases is that
1611 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1612 * NBOUND. This is accomplished by passing it in either the if or else clause,
1613 * with the other one being empty */
1614 #define FBC_BOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1615 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1617 #define FBC_BOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1618 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1620 #define FBC_NBOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1621 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1623 #define FBC_NBOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1624 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1627 /* Common to the BOUND and NBOUND cases. Unfortunately the UTF8 tests need to
1628 * be passed in completely with the variable name being tested, which isn't
1629 * such a clean interface, but this is easier to read than it was before. We
1630 * are looking for the boundary (or non-boundary between a word and non-word
1631 * character. The utf8 and non-utf8 cases have the same logic, but the details
1632 * must be different. Find the "wordness" of the character just prior to this
1633 * one, and compare it with the wordness of this one. If they differ, we have
1634 * a boundary. At the beginning of the string, pretend that the previous
1635 * character was a new-line */
1636 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1637 if (utf8_target) { \
1640 else { /* Not utf8 */ \
1641 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1642 tmp = TEST_NON_UTF8(tmp); \
1644 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1653 if ((!prog->minlen && tmp) && (reginfo->intuit || regtry(reginfo, &s))) \
1656 /* We know what class REx starts with. Try to find this position... */
1657 /* if reginfo->intuit, its a dryrun */
1658 /* annoyingly all the vars in this routine have different names from their counterparts
1659 in regmatch. /grrr */
1662 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1663 const char *strend, regmatch_info *reginfo)
1666 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1667 char *pat_string; /* The pattern's exactish string */
1668 char *pat_end; /* ptr to end char of pat_string */
1669 re_fold_t folder; /* Function for computing non-utf8 folds */
1670 const U8 *fold_array; /* array for folding ords < 256 */
1676 I32 tmp = 1; /* Scratch variable? */
1677 const bool utf8_target = reginfo->is_utf8_target;
1678 UV utf8_fold_flags = 0;
1679 const bool is_utf8_pat = reginfo->is_utf8_pat;
1680 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1681 with a result inverts that result, as 0^1 =
1683 _char_class_number classnum;
1685 RXi_GET_DECL(prog,progi);
1687 PERL_ARGS_ASSERT_FIND_BYCLASS;
1689 /* We know what class it must start with. */
1693 REXEC_FBC_UTF8_CLASS_SCAN(
1694 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1697 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1702 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
1709 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1710 assert(! is_utf8_pat);
1713 if (is_utf8_pat || utf8_target) {
1714 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1715 goto do_exactf_utf8;
1717 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1718 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1719 goto do_exactf_non_utf8; /* isn't dealt with by these */
1721 case EXACTF: /* This node only generated for non-utf8 patterns */
1722 assert(! is_utf8_pat);
1724 utf8_fold_flags = 0;
1725 goto do_exactf_utf8;
1727 fold_array = PL_fold;
1729 goto do_exactf_non_utf8;
1732 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1733 utf8_fold_flags = FOLDEQ_LOCALE;
1734 goto do_exactf_utf8;
1736 fold_array = PL_fold_locale;
1737 folder = foldEQ_locale;
1738 goto do_exactf_non_utf8;
1742 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1744 goto do_exactf_utf8;
1747 if (is_utf8_pat || utf8_target) {
1748 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1749 goto do_exactf_utf8;
1752 /* Any 'ss' in the pattern should have been replaced by regcomp,
1753 * so we don't have to worry here about this single special case
1754 * in the Latin1 range */
1755 fold_array = PL_fold_latin1;
1756 folder = foldEQ_latin1;
1760 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1761 are no glitches with fold-length differences
1762 between the target string and pattern */
1764 /* The idea in the non-utf8 EXACTF* cases is to first find the
1765 * first character of the EXACTF* node and then, if necessary,
1766 * case-insensitively compare the full text of the node. c1 is the
1767 * first character. c2 is its fold. This logic will not work for
1768 * Unicode semantics and the german sharp ss, which hence should
1769 * not be compiled into a node that gets here. */
1770 pat_string = STRING(c);
1771 ln = STR_LEN(c); /* length to match in octets/bytes */
1773 /* We know that we have to match at least 'ln' bytes (which is the
1774 * same as characters, since not utf8). If we have to match 3
1775 * characters, and there are only 2 availabe, we know without
1776 * trying that it will fail; so don't start a match past the
1777 * required minimum number from the far end */
1778 e = HOP3c(strend, -((SSize_t)ln), s);
1780 if (reginfo->intuit && e < s) {
1781 e = s; /* Due to minlen logic of intuit() */
1785 c2 = fold_array[c1];
1786 if (c1 == c2) { /* If char and fold are the same */
1787 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1790 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1798 /* If one of the operands is in utf8, we can't use the simpler folding
1799 * above, due to the fact that many different characters can have the
1800 * same fold, or portion of a fold, or different- length fold */
1801 pat_string = STRING(c);
1802 ln = STR_LEN(c); /* length to match in octets/bytes */
1803 pat_end = pat_string + ln;
1804 lnc = is_utf8_pat /* length to match in characters */
1805 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1808 /* We have 'lnc' characters to match in the pattern, but because of
1809 * multi-character folding, each character in the target can match
1810 * up to 3 characters (Unicode guarantees it will never exceed
1811 * this) if it is utf8-encoded; and up to 2 if not (based on the
1812 * fact that the Latin 1 folds are already determined, and the
1813 * only multi-char fold in that range is the sharp-s folding to
1814 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1815 * string character. Adjust lnc accordingly, rounding up, so that
1816 * if we need to match at least 4+1/3 chars, that really is 5. */
1817 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1818 lnc = (lnc + expansion - 1) / expansion;
1820 /* As in the non-UTF8 case, if we have to match 3 characters, and
1821 * only 2 are left, it's guaranteed to fail, so don't start a
1822 * match that would require us to go beyond the end of the string
1824 e = HOP3c(strend, -((SSize_t)lnc), s);
1826 if (reginfo->intuit && e < s) {
1827 e = s; /* Due to minlen logic of intuit() */
1830 /* XXX Note that we could recalculate e to stop the loop earlier,
1831 * as the worst case expansion above will rarely be met, and as we
1832 * go along we would usually find that e moves further to the left.
1833 * This would happen only after we reached the point in the loop
1834 * where if there were no expansion we should fail. Unclear if
1835 * worth the expense */
1838 char *my_strend= (char *)strend;
1839 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1840 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1841 && (reginfo->intuit || regtry(reginfo, &s)) )
1845 s += (utf8_target) ? UTF8SKIP(s) : 1;
1850 FBC_BOUND(isWORDCHAR_LC,
1851 isWORDCHAR_LC_uvchr(tmp),
1852 isWORDCHAR_LC_utf8((U8*)s));
1855 FBC_NBOUND(isWORDCHAR_LC,
1856 isWORDCHAR_LC_uvchr(tmp),
1857 isWORDCHAR_LC_utf8((U8*)s));
1860 FBC_BOUND(isWORDCHAR,
1861 isWORDCHAR_uni(tmp),
1862 cBOOL(swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)s, utf8_target)));
1865 FBC_BOUND_NOLOAD(isWORDCHAR_A,
1867 isWORDCHAR_A((U8*)s));
1870 FBC_NBOUND(isWORDCHAR,
1871 isWORDCHAR_uni(tmp),
1872 cBOOL(swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)s, utf8_target)));
1875 FBC_NBOUND_NOLOAD(isWORDCHAR_A,
1877 isWORDCHAR_A((U8*)s));
1880 FBC_BOUND(isWORDCHAR_L1,
1881 isWORDCHAR_uni(tmp),
1882 cBOOL(swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)s, utf8_target)));
1885 FBC_NBOUND(isWORDCHAR_L1,
1886 isWORDCHAR_uni(tmp),
1887 cBOOL(swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)s, utf8_target)));
1890 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
1891 is_LNBREAK_latin1_safe(s, strend)
1895 /* The argument to all the POSIX node types is the class number to pass to
1896 * _generic_isCC() to build a mask for searching in PL_charclass[] */
1903 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
1904 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
1919 /* The complement of something that matches only ASCII matches all
1920 * non-ASCII, plus everything in ASCII that isn't in the class. */
1921 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
1922 || ! _generic_isCC_A(*s, FLAGS(c)));
1931 /* Don't need to worry about utf8, as it can match only a single
1932 * byte invariant character. */
1933 REXEC_FBC_CLASS_SCAN(
1934 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
1942 if (! utf8_target) {
1943 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
1949 classnum = (_char_class_number) FLAGS(c);
1950 if (classnum < _FIRST_NON_SWASH_CC) {
1951 while (s < strend) {
1953 /* We avoid loading in the swash as long as possible, but
1954 * should we have to, we jump to a separate loop. This
1955 * extra 'if' statement is what keeps this code from being
1956 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
1957 if (UTF8_IS_ABOVE_LATIN1(*s)) {
1958 goto found_above_latin1;
1960 if ((UTF8_IS_INVARIANT(*s)
1961 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
1963 || (UTF8_IS_DOWNGRADEABLE_START(*s)
1964 && to_complement ^ cBOOL(
1965 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
1969 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
1981 else switch (classnum) { /* These classes are implemented as
1983 case _CC_ENUM_SPACE: /* XXX would require separate code if we
1984 revert the change of \v matching this */
1987 case _CC_ENUM_PSXSPC:
1988 REXEC_FBC_UTF8_CLASS_SCAN(
1989 to_complement ^ cBOOL(isSPACE_utf8(s)));
1992 case _CC_ENUM_BLANK:
1993 REXEC_FBC_UTF8_CLASS_SCAN(
1994 to_complement ^ cBOOL(isBLANK_utf8(s)));
1997 case _CC_ENUM_XDIGIT:
1998 REXEC_FBC_UTF8_CLASS_SCAN(
1999 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2002 case _CC_ENUM_VERTSPACE:
2003 REXEC_FBC_UTF8_CLASS_SCAN(
2004 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2007 case _CC_ENUM_CNTRL:
2008 REXEC_FBC_UTF8_CLASS_SCAN(
2009 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2013 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2014 assert(0); /* NOTREACHED */
2019 found_above_latin1: /* Here we have to load a swash to get the result
2020 for the current code point */
2021 if (! PL_utf8_swash_ptrs[classnum]) {
2022 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2023 PL_utf8_swash_ptrs[classnum] =
2024 _core_swash_init("utf8",
2027 PL_XPosix_ptrs[classnum], &flags);
2030 /* This is a copy of the loop above for swash classes, though using the
2031 * FBC macro instead of being expanded out. Since we've loaded the
2032 * swash, we don't have to check for that each time through the loop */
2033 REXEC_FBC_UTF8_CLASS_SCAN(
2034 to_complement ^ cBOOL(_generic_utf8(
2037 swash_fetch(PL_utf8_swash_ptrs[classnum],
2045 /* what trie are we using right now */
2046 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2047 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2048 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2050 const char *last_start = strend - trie->minlen;
2052 const char *real_start = s;
2054 STRLEN maxlen = trie->maxlen;
2056 U8 **points; /* map of where we were in the input string
2057 when reading a given char. For ASCII this
2058 is unnecessary overhead as the relationship
2059 is always 1:1, but for Unicode, especially
2060 case folded Unicode this is not true. */
2061 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2065 GET_RE_DEBUG_FLAGS_DECL;
2067 /* We can't just allocate points here. We need to wrap it in
2068 * an SV so it gets freed properly if there is a croak while
2069 * running the match */
2072 sv_points=newSV(maxlen * sizeof(U8 *));
2073 SvCUR_set(sv_points,
2074 maxlen * sizeof(U8 *));
2075 SvPOK_on(sv_points);
2076 sv_2mortal(sv_points);
2077 points=(U8**)SvPV_nolen(sv_points );
2078 if ( trie_type != trie_utf8_fold
2079 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2082 bitmap=(U8*)trie->bitmap;
2084 bitmap=(U8*)ANYOF_BITMAP(c);
2086 /* this is the Aho-Corasick algorithm modified a touch
2087 to include special handling for long "unknown char" sequences.
2088 The basic idea being that we use AC as long as we are dealing
2089 with a possible matching char, when we encounter an unknown char
2090 (and we have not encountered an accepting state) we scan forward
2091 until we find a legal starting char.
2092 AC matching is basically that of trie matching, except that when
2093 we encounter a failing transition, we fall back to the current
2094 states "fail state", and try the current char again, a process
2095 we repeat until we reach the root state, state 1, or a legal
2096 transition. If we fail on the root state then we can either
2097 terminate if we have reached an accepting state previously, or
2098 restart the entire process from the beginning if we have not.
2101 while (s <= last_start) {
2102 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2110 U8 *uscan = (U8*)NULL;
2111 U8 *leftmost = NULL;
2113 U32 accepted_word= 0;
2117 while ( state && uc <= (U8*)strend ) {
2119 U32 word = aho->states[ state ].wordnum;
2123 DEBUG_TRIE_EXECUTE_r(
2124 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2125 dump_exec_pos( (char *)uc, c, strend, real_start,
2126 (char *)uc, utf8_target );
2127 PerlIO_printf( Perl_debug_log,
2128 " Scanning for legal start char...\n");
2132 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2136 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2142 if (uc >(U8*)last_start) break;
2146 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2147 if (!leftmost || lpos < leftmost) {
2148 DEBUG_r(accepted_word=word);
2154 points[pointpos++ % maxlen]= uc;
2155 if (foldlen || uc < (U8*)strend) {
2156 REXEC_TRIE_READ_CHAR(trie_type, trie,
2158 uscan, len, uvc, charid, foldlen,
2160 DEBUG_TRIE_EXECUTE_r({
2161 dump_exec_pos( (char *)uc, c, strend,
2162 real_start, s, utf8_target);
2163 PerlIO_printf(Perl_debug_log,
2164 " Charid:%3u CP:%4"UVxf" ",
2176 word = aho->states[ state ].wordnum;
2178 base = aho->states[ state ].trans.base;
2180 DEBUG_TRIE_EXECUTE_r({
2182 dump_exec_pos( (char *)uc, c, strend, real_start,
2184 PerlIO_printf( Perl_debug_log,
2185 "%sState: %4"UVxf", word=%"UVxf,
2186 failed ? " Fail transition to " : "",
2187 (UV)state, (UV)word);
2193 ( ((offset = base + charid
2194 - 1 - trie->uniquecharcount)) >= 0)
2195 && ((U32)offset < trie->lasttrans)
2196 && trie->trans[offset].check == state
2197 && (tmp=trie->trans[offset].next))
2199 DEBUG_TRIE_EXECUTE_r(
2200 PerlIO_printf( Perl_debug_log," - legal\n"));
2205 DEBUG_TRIE_EXECUTE_r(
2206 PerlIO_printf( Perl_debug_log," - fail\n"));
2208 state = aho->fail[state];
2212 /* we must be accepting here */
2213 DEBUG_TRIE_EXECUTE_r(
2214 PerlIO_printf( Perl_debug_log," - accepting\n"));
2223 if (!state) state = 1;
2226 if ( aho->states[ state ].wordnum ) {
2227 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2228 if (!leftmost || lpos < leftmost) {
2229 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2234 s = (char*)leftmost;
2235 DEBUG_TRIE_EXECUTE_r({
2237 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2238 (UV)accepted_word, (IV)(s - real_start)
2241 if (reginfo->intuit || regtry(reginfo, &s)) {
2247 DEBUG_TRIE_EXECUTE_r({
2248 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2251 DEBUG_TRIE_EXECUTE_r(
2252 PerlIO_printf( Perl_debug_log,"No match.\n"));
2261 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2268 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2269 * flags have same meanings as with regexec_flags() */
2272 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2279 struct regexp *const prog = ReANY(rx);
2281 if (flags & REXEC_COPY_STR) {
2285 PerlIO_printf(Perl_debug_log,
2286 "Copy on write: regexp capture, type %d\n",
2289 /* Create a new COW SV to share the match string and store
2290 * in saved_copy, unless the current COW SV in saved_copy
2291 * is valid and suitable for our purpose */
2292 if (( prog->saved_copy
2293 && SvIsCOW(prog->saved_copy)
2294 && SvPOKp(prog->saved_copy)
2297 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2299 /* just reuse saved_copy SV */
2300 if (RXp_MATCH_COPIED(prog)) {
2301 Safefree(prog->subbeg);
2302 RXp_MATCH_COPIED_off(prog);
2306 /* create new COW SV to share string */
2307 RX_MATCH_COPY_FREE(rx);
2308 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2310 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2311 assert (SvPOKp(prog->saved_copy));
2312 prog->sublen = strend - strbeg;
2313 prog->suboffset = 0;
2314 prog->subcoffset = 0;
2319 SSize_t max = strend - strbeg;
2322 if ( (flags & REXEC_COPY_SKIP_POST)
2323 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2324 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2325 ) { /* don't copy $' part of string */
2328 /* calculate the right-most part of the string covered
2329 * by a capture. Due to look-ahead, this may be to
2330 * the right of $&, so we have to scan all captures */
2331 while (n <= prog->lastparen) {
2332 if (prog->offs[n].end > max)
2333 max = prog->offs[n].end;
2337 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2338 ? prog->offs[0].start
2340 assert(max >= 0 && max <= strend - strbeg);
2343 if ( (flags & REXEC_COPY_SKIP_PRE)
2344 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2345 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2346 ) { /* don't copy $` part of string */
2349 /* calculate the left-most part of the string covered
2350 * by a capture. Due to look-behind, this may be to
2351 * the left of $&, so we have to scan all captures */
2352 while (min && n <= prog->lastparen) {
2353 if ( prog->offs[n].start != -1
2354 && prog->offs[n].start < min)
2356 min = prog->offs[n].start;
2360 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2361 && min > prog->offs[0].end
2363 min = prog->offs[0].end;
2367 assert(min >= 0 && min <= max && min <= strend - strbeg);
2370 if (RX_MATCH_COPIED(rx)) {
2371 if (sublen > prog->sublen)
2373 (char*)saferealloc(prog->subbeg, sublen+1);
2376 prog->subbeg = (char*)safemalloc(sublen+1);
2377 Copy(strbeg + min, prog->subbeg, sublen, char);
2378 prog->subbeg[sublen] = '\0';
2379 prog->suboffset = min;
2380 prog->sublen = sublen;
2381 RX_MATCH_COPIED_on(rx);
2383 prog->subcoffset = prog->suboffset;
2384 if (prog->suboffset && utf8_target) {
2385 /* Convert byte offset to chars.
2386 * XXX ideally should only compute this if @-/@+
2387 * has been seen, a la PL_sawampersand ??? */
2389 /* If there's a direct correspondence between the
2390 * string which we're matching and the original SV,
2391 * then we can use the utf8 len cache associated with
2392 * the SV. In particular, it means that under //g,
2393 * sv_pos_b2u() will use the previously cached
2394 * position to speed up working out the new length of
2395 * subcoffset, rather than counting from the start of
2396 * the string each time. This stops
2397 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2398 * from going quadratic */
2399 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2400 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2401 SV_GMAGIC|SV_CONST_RETURN);
2403 prog->subcoffset = utf8_length((U8*)strbeg,
2404 (U8*)(strbeg+prog->suboffset));
2408 RX_MATCH_COPY_FREE(rx);
2409 prog->subbeg = strbeg;
2410 prog->suboffset = 0;
2411 prog->subcoffset = 0;
2412 prog->sublen = strend - strbeg;
2420 - regexec_flags - match a regexp against a string
2423 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2424 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2425 /* stringarg: the point in the string at which to begin matching */
2426 /* strend: pointer to null at end of string */
2427 /* strbeg: real beginning of string */
2428 /* minend: end of match must be >= minend bytes after stringarg. */
2429 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2430 * itself is accessed via the pointers above */
2431 /* data: May be used for some additional optimizations.
2432 Currently unused. */
2433 /* flags: For optimizations. See REXEC_* in regexp.h */
2437 struct regexp *const prog = ReANY(rx);
2441 SSize_t minlen; /* must match at least this many chars */
2442 SSize_t dontbother = 0; /* how many characters not to try at end */
2443 const bool utf8_target = cBOOL(DO_UTF8(sv));
2445 RXi_GET_DECL(prog,progi);
2446 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2447 regmatch_info *const reginfo = ®info_buf;
2448 regexp_paren_pair *swap = NULL;
2450 GET_RE_DEBUG_FLAGS_DECL;
2452 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2453 PERL_UNUSED_ARG(data);
2455 /* Be paranoid... */
2456 if (prog == NULL || stringarg == NULL) {
2457 Perl_croak(aTHX_ "NULL regexp parameter");
2461 debug_start_match(rx, utf8_target, stringarg, strend,
2465 startpos = stringarg;
2467 if (prog->intflags & PREGf_GPOS_SEEN) {
2470 /* set reginfo->ganch, the position where \G can match */
2473 (flags & REXEC_IGNOREPOS)
2474 ? stringarg /* use start pos rather than pos() */
2475 : (sv && (mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2476 /* Defined pos(): */
2477 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2478 : strbeg; /* pos() not defined; use start of string */
2480 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2481 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2483 /* in the presence of \G, we may need to start looking earlier in
2484 * the string than the suggested start point of stringarg:
2485 * if prog->gofs is set, then that's a known, fixed minimum
2488 * /ab|c\G/: gofs = 1
2489 * or if the minimum offset isn't known, then we have to go back
2490 * to the start of the string, e.g. /w+\G/
2493 if (prog->intflags & PREGf_ANCH_GPOS) {
2494 startpos = reginfo->ganch - prog->gofs;
2496 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2498 DEBUG_r(PerlIO_printf(Perl_debug_log,
2499 "fail: ganch-gofs before earliest possible start\n"));
2503 else if (prog->gofs) {
2504 if (startpos - prog->gofs < strbeg)
2507 startpos -= prog->gofs;
2509 else if (prog->intflags & PREGf_GPOS_FLOAT)
2513 minlen = prog->minlen;
2514 if ((startpos + minlen) > strend || startpos < strbeg) {
2515 DEBUG_r(PerlIO_printf(Perl_debug_log,
2516 "Regex match can't succeed, so not even tried\n"));
2520 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2521 * which will call destuctors to reset PL_regmatch_state, free higher
2522 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2523 * regmatch_info_aux_eval */
2525 oldsave = PL_savestack_ix;
2529 if ((prog->extflags & RXf_USE_INTUIT)
2530 && !(flags & REXEC_CHECKED))
2532 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2537 if (prog->extflags & RXf_CHECK_ALL) {
2538 /* we can match based purely on the result of INTUIT.
2539 * Set up captures etc just for $& and $-[0]
2540 * (an intuit-only match wont have $1,$2,..) */
2541 assert(!prog->nparens);
2543 /* s/// doesn't like it if $& is earlier than where we asked it to
2544 * start searching (which can happen on something like /.\G/) */
2545 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2548 /* this should only be possible under \G */
2549 assert(prog->intflags & PREGf_GPOS_SEEN);
2550 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2551 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2555 /* match via INTUIT shouldn't have any captures.
2556 * Let @-, @+, $^N know */
2557 prog->lastparen = prog->lastcloseparen = 0;
2558 RX_MATCH_UTF8_set(rx, utf8_target);
2559 prog->offs[0].start = s - strbeg;
2560 prog->offs[0].end = utf8_target
2561 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2562 : s - strbeg + prog->minlenret;
2563 if ( !(flags & REXEC_NOT_FIRST) )
2564 S_reg_set_capture_string(aTHX_ rx,
2566 sv, flags, utf8_target);
2572 multiline = prog->extflags & RXf_PMf_MULTILINE;
2574 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2575 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2576 "String too short [regexec_flags]...\n"));
2580 /* Check validity of program. */
2581 if (UCHARAT(progi->program) != REG_MAGIC) {
2582 Perl_croak(aTHX_ "corrupted regexp program");
2585 RX_MATCH_TAINTED_off(rx);
2587 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2588 reginfo->intuit = 0;
2589 reginfo->is_utf8_target = cBOOL(utf8_target);
2590 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2591 reginfo->warned = FALSE;
2592 reginfo->strbeg = strbeg;
2594 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2595 reginfo->strend = strend;
2596 /* see how far we have to get to not match where we matched before */
2597 reginfo->till = stringarg + minend;
2599 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2600 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2601 S_cleanup_regmatch_info_aux has executed (registered by
2602 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2603 magic belonging to this SV.
2604 Not newSVsv, either, as it does not COW.
2606 assert(!IS_PADGV(sv));
2607 reginfo->sv = newSV(0);
2608 SvSetSV_nosteal(reginfo->sv, sv);
2609 SAVEFREESV(reginfo->sv);
2612 /* reserve next 2 or 3 slots in PL_regmatch_state:
2613 * slot N+0: may currently be in use: skip it
2614 * slot N+1: use for regmatch_info_aux struct
2615 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2616 * slot N+3: ready for use by regmatch()
2620 regmatch_state *old_regmatch_state;
2621 regmatch_slab *old_regmatch_slab;
2622 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2624 /* on first ever match, allocate first slab */
2625 if (!PL_regmatch_slab) {
2626 Newx(PL_regmatch_slab, 1, regmatch_slab);
2627 PL_regmatch_slab->prev = NULL;
2628 PL_regmatch_slab->next = NULL;
2629 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2632 old_regmatch_state = PL_regmatch_state;
2633 old_regmatch_slab = PL_regmatch_slab;
2635 for (i=0; i <= max; i++) {
2637 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2639 reginfo->info_aux_eval =
2640 reginfo->info_aux->info_aux_eval =
2641 &(PL_regmatch_state->u.info_aux_eval);
2643 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2644 PL_regmatch_state = S_push_slab(aTHX);
2647 /* note initial PL_regmatch_state position; at end of match we'll
2648 * pop back to there and free any higher slabs */
2650 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
2651 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
2652 reginfo->info_aux->poscache = NULL;
2654 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
2656 if ((prog->extflags & RXf_EVAL_SEEN))
2657 S_setup_eval_state(aTHX_ reginfo);
2659 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
2662 /* If there is a "must appear" string, look for it. */
2664 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2665 /* We have to be careful. If the previous successful match
2666 was from this regex we don't want a subsequent partially
2667 successful match to clobber the old results.
2668 So when we detect this possibility we add a swap buffer
2669 to the re, and switch the buffer each match. If we fail,
2670 we switch it back; otherwise we leave it swapped.
2673 /* do we need a save destructor here for eval dies? */
2674 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2675 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2676 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2683 /* Simplest case: anchored match need be tried only once. */
2684 /* [unless only anchor is BOL and multiline is set] */
2685 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
2686 if (s == startpos && regtry(reginfo, &s))
2688 else if (multiline || (prog->intflags & (PREGf_IMPLICIT | PREGf_ANCH_MBOL))) /* XXXX SBOL? */
2693 dontbother = minlen - 1;
2694 end = HOP3c(strend, -dontbother, strbeg) - 1;
2695 /* for multiline we only have to try after newlines */
2696 if (prog->check_substr || prog->check_utf8) {
2697 /* because of the goto we can not easily reuse the macros for bifurcating the
2698 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2701 goto after_try_utf8;
2703 if (regtry(reginfo, &s)) {
2710 if (prog->extflags & RXf_USE_INTUIT) {
2711 s = re_intuit_start(rx, sv, strbeg,
2712 s + UTF8SKIP(s), strend, flags, NULL);
2721 } /* end search for check string in unicode */
2723 if (s == startpos) {
2724 goto after_try_latin;
2727 if (regtry(reginfo, &s)) {
2734 if (prog->extflags & RXf_USE_INTUIT) {
2735 s = re_intuit_start(rx, sv, strbeg,
2736 s + 1, strend, flags, NULL);
2745 } /* end search for check string in latin*/
2746 } /* end search for check string */
2747 else { /* search for newline */
2749 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2752 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2753 while (s <= end) { /* note it could be possible to match at the end of the string */
2754 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2755 if (regtry(reginfo, &s))
2759 } /* end search for newline */
2760 } /* end anchored/multiline check string search */
2762 } else if (prog->intflags & PREGf_ANCH_GPOS)
2764 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
2765 assert(prog->intflags & PREGf_GPOS_SEEN);
2766 /* For anchored \G, the only position it can match from is
2767 * (ganch-gofs); we already set startpos to this above; if intuit
2768 * moved us on from there, we can't possibly succeed */
2769 assert(startpos == reginfo->ganch - prog->gofs);
2770 if (s == startpos && regtry(reginfo, &s))
2775 /* Messy cases: unanchored match. */
2776 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2777 /* we have /x+whatever/ */
2778 /* it must be a one character string (XXXX Except is_utf8_pat?) */
2784 if (! prog->anchored_utf8) {
2785 to_utf8_substr(prog);
2787 ch = SvPVX_const(prog->anchored_utf8)[0];
2790 DEBUG_EXECUTE_r( did_match = 1 );
2791 if (regtry(reginfo, &s)) goto got_it;
2793 while (s < strend && *s == ch)
2800 if (! prog->anchored_substr) {
2801 if (! to_byte_substr(prog)) {
2802 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2805 ch = SvPVX_const(prog->anchored_substr)[0];
2808 DEBUG_EXECUTE_r( did_match = 1 );
2809 if (regtry(reginfo, &s)) goto got_it;
2811 while (s < strend && *s == ch)
2816 DEBUG_EXECUTE_r(if (!did_match)
2817 PerlIO_printf(Perl_debug_log,
2818 "Did not find anchored character...\n")
2821 else if (prog->anchored_substr != NULL
2822 || prog->anchored_utf8 != NULL
2823 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2824 && prog->float_max_offset < strend - s)) {
2829 char *last1; /* Last position checked before */
2833 if (prog->anchored_substr || prog->anchored_utf8) {
2835 if (! prog->anchored_utf8) {
2836 to_utf8_substr(prog);
2838 must = prog->anchored_utf8;
2841 if (! prog->anchored_substr) {
2842 if (! to_byte_substr(prog)) {
2843 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2846 must = prog->anchored_substr;
2848 back_max = back_min = prog->anchored_offset;
2851 if (! prog->float_utf8) {
2852 to_utf8_substr(prog);
2854 must = prog->float_utf8;
2857 if (! prog->float_substr) {
2858 if (! to_byte_substr(prog)) {
2859 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2862 must = prog->float_substr;
2864 back_max = prog->float_max_offset;
2865 back_min = prog->float_min_offset;
2871 last = HOP3c(strend, /* Cannot start after this */
2872 -(SSize_t)(CHR_SVLEN(must)
2873 - (SvTAIL(must) != 0) + back_min), strbeg);
2875 if (s > reginfo->strbeg)
2876 last1 = HOPc(s, -1);
2878 last1 = s - 1; /* bogus */
2880 /* XXXX check_substr already used to find "s", can optimize if
2881 check_substr==must. */
2883 strend = HOPc(strend, -dontbother);
2884 while ( (s <= last) &&
2885 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
2886 (unsigned char*)strend, must,
2887 multiline ? FBMrf_MULTILINE : 0)) ) {
2888 DEBUG_EXECUTE_r( did_match = 1 );
2889 if (HOPc(s, -back_max) > last1) {
2890 last1 = HOPc(s, -back_min);
2891 s = HOPc(s, -back_max);
2894 char * const t = (last1 >= reginfo->strbeg)
2895 ? HOPc(last1, 1) : last1 + 1;
2897 last1 = HOPc(s, -back_min);
2901 while (s <= last1) {
2902 if (regtry(reginfo, &s))
2905 s++; /* to break out of outer loop */
2912 while (s <= last1) {
2913 if (regtry(reginfo, &s))
2919 DEBUG_EXECUTE_r(if (!did_match) {
2920 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2921 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2922 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2923 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2924 ? "anchored" : "floating"),
2925 quoted, RE_SV_TAIL(must));
2929 else if ( (c = progi->regstclass) ) {
2931 const OPCODE op = OP(progi->regstclass);
2932 /* don't bother with what can't match */
2933 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2934 strend = HOPc(strend, -(minlen - 1));
2937 SV * const prop = sv_newmortal();
2938 regprop(prog, prop, c, reginfo);
2940 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2942 PerlIO_printf(Perl_debug_log,
2943 "Matching stclass %.*s against %s (%d bytes)\n",
2944 (int)SvCUR(prop), SvPVX_const(prop),
2945 quoted, (int)(strend - s));
2948 if (find_byclass(prog, c, s, strend, reginfo))
2950 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2954 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2962 if (! prog->float_utf8) {
2963 to_utf8_substr(prog);
2965 float_real = prog->float_utf8;
2968 if (! prog->float_substr) {
2969 if (! to_byte_substr(prog)) {
2970 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2973 float_real = prog->float_substr;
2976 little = SvPV_const(float_real, len);
2977 if (SvTAIL(float_real)) {
2978 /* This means that float_real contains an artificial \n on
2979 * the end due to the presence of something like this:
2980 * /foo$/ where we can match both "foo" and "foo\n" at the
2981 * end of the string. So we have to compare the end of the
2982 * string first against the float_real without the \n and
2983 * then against the full float_real with the string. We
2984 * have to watch out for cases where the string might be
2985 * smaller than the float_real or the float_real without
2987 char *checkpos= strend - len;
2989 PerlIO_printf(Perl_debug_log,
2990 "%sChecking for float_real.%s\n",
2991 PL_colors[4], PL_colors[5]));
2992 if (checkpos + 1 < strbeg) {
2993 /* can't match, even if we remove the trailing \n
2994 * string is too short to match */
2996 PerlIO_printf(Perl_debug_log,
2997 "%sString shorter than required trailing substring, cannot match.%s\n",
2998 PL_colors[4], PL_colors[5]));
3000 } else if (memEQ(checkpos + 1, little, len - 1)) {
3001 /* can match, the end of the string matches without the
3003 last = checkpos + 1;
3004 } else if (checkpos < strbeg) {
3005 /* cant match, string is too short when the "\n" is
3008 PerlIO_printf(Perl_debug_log,
3009 "%sString does not contain required trailing substring, cannot match.%s\n",
3010 PL_colors[4], PL_colors[5]));
3012 } else if (!multiline) {
3013 /* non multiline match, so compare with the "\n" at the
3014 * end of the string */
3015 if (memEQ(checkpos, little, len)) {
3019 PerlIO_printf(Perl_debug_log,
3020 "%sString does not contain required trailing substring, cannot match.%s\n",
3021 PL_colors[4], PL_colors[5]));
3025 /* multiline match, so we have to search for a place
3026 * where the full string is located */
3032 last = rninstr(s, strend, little, little + len);
3034 last = strend; /* matching "$" */
3037 /* at one point this block contained a comment which was
3038 * probably incorrect, which said that this was a "should not
3039 * happen" case. Even if it was true when it was written I am
3040 * pretty sure it is not anymore, so I have removed the comment
3041 * and replaced it with this one. Yves */
3043 PerlIO_printf(Perl_debug_log,
3044 "String does not contain required substring, cannot match.\n"
3048 dontbother = strend - last + prog->float_min_offset;
3050 if (minlen && (dontbother < minlen))
3051 dontbother = minlen - 1;
3052 strend -= dontbother; /* this one's always in bytes! */
3053 /* We don't know much -- general case. */
3056 if (regtry(reginfo, &s))
3065 if (regtry(reginfo, &s))
3067 } while (s++ < strend);
3075 /* s/// doesn't like it if $& is earlier than where we asked it to
3076 * start searching (which can happen on something like /.\G/) */
3077 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3078 && (prog->offs[0].start < stringarg - strbeg))
3080 /* this should only be possible under \G */
3081 assert(prog->intflags & PREGf_GPOS_SEEN);
3082 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3083 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3089 PerlIO_printf(Perl_debug_log,
3090 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3097 /* clean up; this will trigger destructors that will free all slabs
3098 * above the current one, and cleanup the regmatch_info_aux
3099 * and regmatch_info_aux_eval sructs */
3101 LEAVE_SCOPE(oldsave);
3103 if (RXp_PAREN_NAMES(prog))
3104 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3106 RX_MATCH_UTF8_set(rx, utf8_target);
3108 /* make sure $`, $&, $', and $digit will work later */
3109 if ( !(flags & REXEC_NOT_FIRST) )
3110 S_reg_set_capture_string(aTHX_ rx,
3111 strbeg, reginfo->strend,
3112 sv, flags, utf8_target);
3117 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3118 PL_colors[4], PL_colors[5]));
3120 /* clean up; this will trigger destructors that will free all slabs
3121 * above the current one, and cleanup the regmatch_info_aux
3122 * and regmatch_info_aux_eval sructs */
3124 LEAVE_SCOPE(oldsave);
3127 /* we failed :-( roll it back */
3128 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3129 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3134 Safefree(prog->offs);
3141 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3142 * Do inc before dec, in case old and new rex are the same */
3143 #define SET_reg_curpm(Re2) \
3144 if (reginfo->info_aux_eval) { \
3145 (void)ReREFCNT_inc(Re2); \
3146 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3147 PM_SETRE((PL_reg_curpm), (Re2)); \
3152 - regtry - try match at specific point
3154 STATIC I32 /* 0 failure, 1 success */
3155 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3159 REGEXP *const rx = reginfo->prog;
3160 regexp *const prog = ReANY(rx);
3162 RXi_GET_DECL(prog,progi);
3163 GET_RE_DEBUG_FLAGS_DECL;
3165 PERL_ARGS_ASSERT_REGTRY;
3167 reginfo->cutpoint=NULL;
3169 prog->offs[0].start = *startposp - reginfo->strbeg;
3170 prog->lastparen = 0;
3171 prog->lastcloseparen = 0;
3173 /* XXXX What this code is doing here?!!! There should be no need
3174 to do this again and again, prog->lastparen should take care of
3177 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3178 * Actually, the code in regcppop() (which Ilya may be meaning by
3179 * prog->lastparen), is not needed at all by the test suite
3180 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3181 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3182 * Meanwhile, this code *is* needed for the
3183 * above-mentioned test suite tests to succeed. The common theme
3184 * on those tests seems to be returning null fields from matches.
3185 * --jhi updated by dapm */
3187 if (prog->nparens) {
3188 regexp_paren_pair *pp = prog->offs;
3190 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3198 result = regmatch(reginfo, *startposp, progi->program + 1);
3200 prog->offs[0].end = result;
3203 if (reginfo->cutpoint)
3204 *startposp= reginfo->cutpoint;
3205 REGCP_UNWIND(lastcp);
3210 #define sayYES goto yes
3211 #define sayNO goto no
3212 #define sayNO_SILENT goto no_silent
3214 /* we dont use STMT_START/END here because it leads to
3215 "unreachable code" warnings, which are bogus, but distracting. */
3216 #define CACHEsayNO \
3217 if (ST.cache_mask) \
3218 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3221 /* this is used to determine how far from the left messages like
3222 'failed...' are printed. It should be set such that messages
3223 are inline with the regop output that created them.
3225 #define REPORT_CODE_OFF 32
3228 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3229 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3230 #define CHRTEST_NOT_A_CP_1 -999
3231 #define CHRTEST_NOT_A_CP_2 -998
3233 /* grab a new slab and return the first slot in it */
3235 STATIC regmatch_state *
3238 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3241 regmatch_slab *s = PL_regmatch_slab->next;
3243 Newx(s, 1, regmatch_slab);
3244 s->prev = PL_regmatch_slab;
3246 PL_regmatch_slab->next = s;
3248 PL_regmatch_slab = s;
3249 return SLAB_FIRST(s);
3253 /* push a new state then goto it */
3255 #define PUSH_STATE_GOTO(state, node, input) \
3256 pushinput = input; \
3258 st->resume_state = state; \
3261 /* push a new state with success backtracking, then goto it */
3263 #define PUSH_YES_STATE_GOTO(state, node, input) \
3264 pushinput = input; \
3266 st->resume_state = state; \
3267 goto push_yes_state;
3274 regmatch() - main matching routine
3276 This is basically one big switch statement in a loop. We execute an op,
3277 set 'next' to point the next op, and continue. If we come to a point which
3278 we may need to backtrack to on failure such as (A|B|C), we push a
3279 backtrack state onto the backtrack stack. On failure, we pop the top
3280 state, and re-enter the loop at the state indicated. If there are no more
3281 states to pop, we return failure.
3283 Sometimes we also need to backtrack on success; for example /A+/, where
3284 after successfully matching one A, we need to go back and try to
3285 match another one; similarly for lookahead assertions: if the assertion
3286 completes successfully, we backtrack to the state just before the assertion
3287 and then carry on. In these cases, the pushed state is marked as
3288 'backtrack on success too'. This marking is in fact done by a chain of
3289 pointers, each pointing to the previous 'yes' state. On success, we pop to
3290 the nearest yes state, discarding any intermediate failure-only states.
3291 Sometimes a yes state is pushed just to force some cleanup code to be
3292 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3293 it to free the inner regex.
3295 Note that failure backtracking rewinds the cursor position, while
3296 success backtracking leaves it alone.
3298 A pattern is complete when the END op is executed, while a subpattern
3299 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3300 ops trigger the "pop to last yes state if any, otherwise return true"
3303 A common convention in this function is to use A and B to refer to the two
3304 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3305 the subpattern to be matched possibly multiple times, while B is the entire
3306 rest of the pattern. Variable and state names reflect this convention.
3308 The states in the main switch are the union of ops and failure/success of
3309 substates associated with with that op. For example, IFMATCH is the op
3310 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3311 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3312 successfully matched A and IFMATCH_A_fail is a state saying that we have
3313 just failed to match A. Resume states always come in pairs. The backtrack
3314 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3315 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3316 on success or failure.
3318 The struct that holds a backtracking state is actually a big union, with
3319 one variant for each major type of op. The variable st points to the
3320 top-most backtrack struct. To make the code clearer, within each
3321 block of code we #define ST to alias the relevant union.
3323 Here's a concrete example of a (vastly oversimplified) IFMATCH
3329 #define ST st->u.ifmatch
3331 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3332 ST.foo = ...; // some state we wish to save
3334 // push a yes backtrack state with a resume value of
3335 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3337 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3340 case IFMATCH_A: // we have successfully executed A; now continue with B
3342 bar = ST.foo; // do something with the preserved value
3345 case IFMATCH_A_fail: // A failed, so the assertion failed
3346 ...; // do some housekeeping, then ...
3347 sayNO; // propagate the failure
3354 For any old-timers reading this who are familiar with the old recursive
3355 approach, the code above is equivalent to:
3357 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3366 ...; // do some housekeeping, then ...
3367 sayNO; // propagate the failure
3370 The topmost backtrack state, pointed to by st, is usually free. If you
3371 want to claim it, populate any ST.foo fields in it with values you wish to
3372 save, then do one of
3374 PUSH_STATE_GOTO(resume_state, node, newinput);
3375 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3377 which sets that backtrack state's resume value to 'resume_state', pushes a
3378 new free entry to the top of the backtrack stack, then goes to 'node'.
3379 On backtracking, the free slot is popped, and the saved state becomes the
3380 new free state. An ST.foo field in this new top state can be temporarily
3381 accessed to retrieve values, but once the main loop is re-entered, it
3382 becomes available for reuse.
3384 Note that the depth of the backtrack stack constantly increases during the
3385 left-to-right execution of the pattern, rather than going up and down with
3386 the pattern nesting. For example the stack is at its maximum at Z at the
3387 end of the pattern, rather than at X in the following:
3389 /(((X)+)+)+....(Y)+....Z/
3391 The only exceptions to this are lookahead/behind assertions and the cut,
3392 (?>A), which pop all the backtrack states associated with A before
3395 Backtrack state structs are allocated in slabs of about 4K in size.
3396 PL_regmatch_state and st always point to the currently active state,
3397 and PL_regmatch_slab points to the slab currently containing
3398 PL_regmatch_state. The first time regmatch() is called, the first slab is
3399 allocated, and is never freed until interpreter destruction. When the slab
3400 is full, a new one is allocated and chained to the end. At exit from
3401 regmatch(), slabs allocated since entry are freed.
3406 #define DEBUG_STATE_pp(pp) \
3408 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3409 PerlIO_printf(Perl_debug_log, \
3410 " %*s"pp" %s%s%s%s%s\n", \
3412 PL_reg_name[st->resume_state], \
3413 ((st==yes_state||st==mark_state) ? "[" : ""), \
3414 ((st==yes_state) ? "Y" : ""), \
3415 ((st==mark_state) ? "M" : ""), \
3416 ((st==yes_state||st==mark_state) ? "]" : "") \
3421 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3426 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3427 const char *start, const char *end, const char *blurb)
3429 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3431 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3436 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3437 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3439 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3440 start, end - start, 60);
3442 PerlIO_printf(Perl_debug_log,
3443 "%s%s REx%s %s against %s\n",
3444 PL_colors[4], blurb, PL_colors[5], s0, s1);
3446 if (utf8_target||utf8_pat)
3447 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3448 utf8_pat ? "pattern" : "",
3449 utf8_pat && utf8_target ? " and " : "",
3450 utf8_target ? "string" : ""
3456 S_dump_exec_pos(pTHX_ const char *locinput,
3457 const regnode *scan,
3458 const char *loc_regeol,
3459 const char *loc_bostr,
3460 const char *loc_reg_starttry,
3461 const bool utf8_target)
3463 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3464 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3465 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3466 /* The part of the string before starttry has one color
3467 (pref0_len chars), between starttry and current
3468 position another one (pref_len - pref0_len chars),
3469 after the current position the third one.
3470 We assume that pref0_len <= pref_len, otherwise we
3471 decrease pref0_len. */
3472 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3473 ? (5 + taill) - l : locinput - loc_bostr;
3476 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3478 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3480 pref0_len = pref_len - (locinput - loc_reg_starttry);
3481 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3482 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3483 ? (5 + taill) - pref_len : loc_regeol - locinput);
3484 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3488 if (pref0_len > pref_len)
3489 pref0_len = pref_len;
3491 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3493 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3494 (locinput - pref_len),pref0_len, 60, 4, 5);
3496 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3497 (locinput - pref_len + pref0_len),
3498 pref_len - pref0_len, 60, 2, 3);
3500 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3501 locinput, loc_regeol - locinput, 10, 0, 1);
3503 const STRLEN tlen=len0+len1+len2;
3504 PerlIO_printf(Perl_debug_log,
3505 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3506 (IV)(locinput - loc_bostr),
3509 (docolor ? "" : "> <"),
3511 (int)(tlen > 19 ? 0 : 19 - tlen),
3518 /* reg_check_named_buff_matched()
3519 * Checks to see if a named buffer has matched. The data array of
3520 * buffer numbers corresponding to the buffer is expected to reside
3521 * in the regexp->data->data array in the slot stored in the ARG() of
3522 * node involved. Note that this routine doesn't actually care about the
3523 * name, that information is not preserved from compilation to execution.
3524 * Returns the index of the leftmost defined buffer with the given name
3525 * or 0 if non of the buffers matched.
3528 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3531 RXi_GET_DECL(rex,rexi);
3532 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3533 I32 *nums=(I32*)SvPVX(sv_dat);
3535 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3537 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3538 if ((I32)rex->lastparen >= nums[n] &&
3539 rex->offs[nums[n]].end != -1)
3549 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3550 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3552 /* This function determines if there are one or two characters that match
3553 * the first character of the passed-in EXACTish node <text_node>, and if
3554 * so, returns them in the passed-in pointers.
3556 * If it determines that no possible character in the target string can
3557 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3558 * the first character in <text_node> requires UTF-8 to represent, and the
3559 * target string isn't in UTF-8.)
3561 * If there are more than two characters that could match the beginning of
3562 * <text_node>, or if more context is required to determine a match or not,
3563 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3565 * The motiviation behind this function is to allow the caller to set up
3566 * tight loops for matching. If <text_node> is of type EXACT, there is
3567 * only one possible character that can match its first character, and so
3568 * the situation is quite simple. But things get much more complicated if
3569 * folding is involved. It may be that the first character of an EXACTFish
3570 * node doesn't participate in any possible fold, e.g., punctuation, so it
3571 * can be matched only by itself. The vast majority of characters that are
3572 * in folds match just two things, their lower and upper-case equivalents.
3573 * But not all are like that; some have multiple possible matches, or match
3574 * sequences of more than one character. This function sorts all that out.
3576 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3577 * loop of trying to match A*, we know we can't exit where the thing
3578 * following it isn't a B. And something can't be a B unless it is the
3579 * beginning of B. By putting a quick test for that beginning in a tight
3580 * loop, we can rule out things that can't possibly be B without having to
3581 * break out of the loop, thus avoiding work. Similarly, if A is a single
3582 * character, we can make a tight loop matching A*, using the outputs of
3585 * If the target string to match isn't in UTF-8, and there aren't
3586 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3587 * the one or two possible octets (which are characters in this situation)
3588 * that can match. In all cases, if there is only one character that can
3589 * match, *<c1p> and *<c2p> will be identical.
3591 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3592 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3593 * can match the beginning of <text_node>. They should be declared with at
3594 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3595 * undefined what these contain.) If one or both of the buffers are
3596 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3597 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3598 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3599 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3600 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3602 const bool utf8_target = reginfo->is_utf8_target;
3604 UV c1 = CHRTEST_NOT_A_CP_1;
3605 UV c2 = CHRTEST_NOT_A_CP_2;
3606 bool use_chrtest_void = FALSE;
3607 const bool is_utf8_pat = reginfo->is_utf8_pat;
3609 /* Used when we have both utf8 input and utf8 output, to avoid converting
3610 * to/from code points */
3611 bool utf8_has_been_setup = FALSE;
3615 U8 *pat = (U8*)STRING(text_node);
3616 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3618 if (OP(text_node) == EXACT) {
3620 /* In an exact node, only one thing can be matched, that first
3621 * character. If both the pat and the target are UTF-8, we can just
3622 * copy the input to the output, avoiding finding the code point of
3627 else if (utf8_target) {
3628 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3629 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3630 utf8_has_been_setup = TRUE;
3633 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3636 else { /* an EXACTFish node */
3637 U8 *pat_end = pat + STR_LEN(text_node);
3639 /* An EXACTFL node has at least some characters unfolded, because what
3640 * they match is not known until now. So, now is the time to fold
3641 * the first few of them, as many as are needed to determine 'c1' and
3642 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3643 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3644 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3645 * need to fold as many characters as a single character can fold to,
3646 * so that later we can check if the first ones are such a multi-char
3647 * fold. But, in such a pattern only locale-problematic characters
3648 * aren't folded, so we can skip this completely if the first character
3649 * in the node isn't one of the tricky ones */
3650 if (OP(text_node) == EXACTFL) {
3652 if (! is_utf8_pat) {
3653 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3655 folded[0] = folded[1] = 's';
3657 pat_end = folded + 2;
3660 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3665 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3667 *(d++) = (U8) toFOLD_LC(*s);
3672 _to_utf8_fold_flags(s,
3675 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
3686 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
3687 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
3689 /* Multi-character folds require more context to sort out. Also
3690 * PL_utf8_foldclosures used below doesn't handle them, so have to
3691 * be handled outside this routine */
3692 use_chrtest_void = TRUE;
3694 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
3695 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
3697 /* Load the folds hash, if not already done */
3699 if (! PL_utf8_foldclosures) {
3700 _load_PL_utf8_foldclosures();
3703 /* The fold closures data structure is a hash with the keys
3704 * being the UTF-8 of every character that is folded to, like
3705 * 'k', and the values each an array of all code points that
3706 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
3707 * Multi-character folds are not included */
3708 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
3713 /* Not found in the hash, therefore there are no folds
3714 * containing it, so there is only a single character that
3718 else { /* Does participate in folds */
3719 AV* list = (AV*) *listp;
3720 if (av_tindex(list) != 1) {
3722 /* If there aren't exactly two folds to this, it is
3723 * outside the scope of this function */
3724 use_chrtest_void = TRUE;
3726 else { /* There are two. Get them */
3727 SV** c_p = av_fetch(list, 0, FALSE);
3729 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3733 c_p = av_fetch(list, 1, FALSE);
3735 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3739 /* Folds that cross the 255/256 boundary are forbidden
3740 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
3741 * one is ASCIII. Since the pattern character is above
3742 * 255, and its only other match is below 256, the only
3743 * legal match will be to itself. We have thrown away
3744 * the original, so have to compute which is the one
3746 if ((c1 < 256) != (c2 < 256)) {
3747 if ((OP(text_node) == EXACTFL
3748 && ! IN_UTF8_CTYPE_LOCALE)
3749 || ((OP(text_node) == EXACTFA
3750 || OP(text_node) == EXACTFA_NO_TRIE)
3751 && (isASCII(c1) || isASCII(c2))))
3764 else /* Here, c1 is <= 255 */
3766 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
3767 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
3768 && ((OP(text_node) != EXACTFA
3769 && OP(text_node) != EXACTFA_NO_TRIE)
3772 /* Here, there could be something above Latin1 in the target
3773 * which folds to this character in the pattern. All such
3774 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
3775 * than two characters involved in their folds, so are outside
3776 * the scope of this function */
3777 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
3778 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
3781 use_chrtest_void = TRUE;
3784 else { /* Here nothing above Latin1 can fold to the pattern
3786 switch (OP(text_node)) {
3788 case EXACTFL: /* /l rules */
3789 c2 = PL_fold_locale[c1];
3792 case EXACTF: /* This node only generated for non-utf8
3794 assert(! is_utf8_pat);
3795 if (! utf8_target) { /* /d rules */
3800 /* /u rules for all these. This happens to work for
3801 * EXACTFA as nothing in Latin1 folds to ASCII */
3802 case EXACTFA_NO_TRIE: /* This node only generated for
3803 non-utf8 patterns */
3804 assert(! is_utf8_pat);
3809 c2 = PL_fold_latin1[c1];
3813 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
3814 assert(0); /* NOTREACHED */
3820 /* Here have figured things out. Set up the returns */
3821 if (use_chrtest_void) {
3822 *c2p = *c1p = CHRTEST_VOID;
3824 else if (utf8_target) {
3825 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
3826 uvchr_to_utf8(c1_utf8, c1);
3827 uvchr_to_utf8(c2_utf8, c2);
3830 /* Invariants are stored in both the utf8 and byte outputs; Use
3831 * negative numbers otherwise for the byte ones. Make sure that the
3832 * byte ones are the same iff the utf8 ones are the same */
3833 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
3834 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
3837 ? CHRTEST_NOT_A_CP_1
3838 : CHRTEST_NOT_A_CP_2;
3840 else if (c1 > 255) {
3841 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
3846 *c1p = *c2p = c2; /* c2 is the only representable value */
3848 else { /* c1 is representable; see about c2 */
3850 *c2p = (c2 < 256) ? c2 : c1;
3856 /* returns -1 on failure, $+[0] on success */
3858 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
3860 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3864 const bool utf8_target = reginfo->is_utf8_target;
3865 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3866 REGEXP *rex_sv = reginfo->prog;
3867 regexp *rex = ReANY(rex_sv);
3868 RXi_GET_DECL(rex,rexi);
3869 /* the current state. This is a cached copy of PL_regmatch_state */
3871 /* cache heavy used fields of st in registers */
3874 U32 n = 0; /* general value; init to avoid compiler warning */
3875 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
3876 char *locinput = startpos;
3877 char *pushinput; /* where to continue after a PUSH */
3878 I32 nextchr; /* is always set to UCHARAT(locinput) */
3880 bool result = 0; /* return value of S_regmatch */
3881 int depth = 0; /* depth of backtrack stack */
3882 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3883 const U32 max_nochange_depth =
3884 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3885 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3886 regmatch_state *yes_state = NULL; /* state to pop to on success of
3888 /* mark_state piggy backs on the yes_state logic so that when we unwind
3889 the stack on success we can update the mark_state as we go */
3890 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3891 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3892 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3894 bool no_final = 0; /* prevent failure from backtracking? */
3895 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3896 char *startpoint = locinput;
3897 SV *popmark = NULL; /* are we looking for a mark? */
3898 SV *sv_commit = NULL; /* last mark name seen in failure */
3899 SV *sv_yes_mark = NULL; /* last mark name we have seen
3900 during a successful match */
3901 U32 lastopen = 0; /* last open we saw */
3902 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3903 SV* const oreplsv = GvSVn(PL_replgv);
3904 /* these three flags are set by various ops to signal information to
3905 * the very next op. They have a useful lifetime of exactly one loop
3906 * iteration, and are not preserved or restored by state pushes/pops
3908 bool sw = 0; /* the condition value in (?(cond)a|b) */
3909 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3910 int logical = 0; /* the following EVAL is:
3914 or the following IFMATCH/UNLESSM is:
3915 false: plain (?=foo)
3916 true: used as a condition: (?(?=foo))
3918 PAD* last_pad = NULL;
3920 I32 gimme = G_SCALAR;
3921 CV *caller_cv = NULL; /* who called us */
3922 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
3923 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
3924 U32 maxopenparen = 0; /* max '(' index seen so far */
3925 int to_complement; /* Invert the result? */
3926 _char_class_number classnum;
3927 bool is_utf8_pat = reginfo->is_utf8_pat;
3930 GET_RE_DEBUG_FLAGS_DECL;
3933 /* protect against undef(*^R) */
3934 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
3936 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3937 multicall_oldcatch = 0;
3938 multicall_cv = NULL;
3940 PERL_UNUSED_VAR(multicall_cop);
3941 PERL_UNUSED_VAR(newsp);
3944 PERL_ARGS_ASSERT_REGMATCH;
3946 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3947 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3950 st = PL_regmatch_state;
3952 /* Note that nextchr is a byte even in UTF */
3955 while (scan != NULL) {
3958 SV * const prop = sv_newmortal();
3959 regnode *rnext=regnext(scan);
3960 DUMP_EXEC_POS( locinput, scan, utf8_target );
3961 regprop(rex, prop, scan, reginfo);
3963 PerlIO_printf(Perl_debug_log,
3964 "%3"IVdf":%*s%s(%"IVdf")\n",
3965 (IV)(scan - rexi->program), depth*2, "",
3967 (PL_regkind[OP(scan)] == END || !rnext) ?
3968 0 : (IV)(rnext - rexi->program));
3971 next = scan + NEXT_OFF(scan);
3974 state_num = OP(scan);
3980 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
3982 switch (state_num) {
3983 case BOL: /* /^../ */
3984 case SBOL: /* /^../s */
3985 if (locinput == reginfo->strbeg)
3989 case MBOL: /* /^../m */
3990 if (locinput == reginfo->strbeg ||
3991 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
3998 if (locinput == reginfo->ganch)
4002 case KEEPS: /* \K */
4003 /* update the startpoint */
4004 st->u.keeper.val = rex->offs[0].start;
4005 rex->offs[0].start = locinput - reginfo->strbeg;
4006 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4007 assert(0); /*NOTREACHED*/
4008 case KEEPS_next_fail:
4009 /* rollback the start point change */
4010 rex->offs[0].start = st->u.keeper.val;
4012 assert(0); /*NOTREACHED*/
4014 case MEOL: /* /..$/m */
4015 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4019 case EOL: /* /..$/ */
4021 case SEOL: /* /..$/s */
4022 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4024 if (reginfo->strend - locinput > 1)
4029 if (!NEXTCHR_IS_EOS)
4033 case SANY: /* /./s */
4036 goto increment_locinput;
4044 case REG_ANY: /* /./ */
4045 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4047 goto increment_locinput;
4051 #define ST st->u.trie
4052 case TRIEC: /* (ab|cd) with known charclass */
4053 /* In this case the charclass data is available inline so
4054 we can fail fast without a lot of extra overhead.
4056 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
4058 PerlIO_printf(Perl_debug_log,
4059 "%*s %sfailed to match trie start class...%s\n",
4060 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4063 assert(0); /* NOTREACHED */
4066 case TRIE: /* (ab|cd) */
4067 /* the basic plan of execution of the trie is:
4068 * At the beginning, run though all the states, and
4069 * find the longest-matching word. Also remember the position
4070 * of the shortest matching word. For example, this pattern:
4073 * when matched against the string "abcde", will generate
4074 * accept states for all words except 3, with the longest
4075 * matching word being 4, and the shortest being 2 (with
4076 * the position being after char 1 of the string).
4078 * Then for each matching word, in word order (i.e. 1,2,4,5),
4079 * we run the remainder of the pattern; on each try setting
4080 * the current position to the character following the word,
4081 * returning to try the next word on failure.
4083 * We avoid having to build a list of words at runtime by
4084 * using a compile-time structure, wordinfo[].prev, which
4085 * gives, for each word, the previous accepting word (if any).
4086 * In the case above it would contain the mappings 1->2, 2->0,
4087 * 3->0, 4->5, 5->1. We can use this table to generate, from
4088 * the longest word (4 above), a list of all words, by
4089 * following the list of prev pointers; this gives us the
4090 * unordered list 4,5,1,2. Then given the current word we have
4091 * just tried, we can go through the list and find the
4092 * next-biggest word to try (so if we just failed on word 2,
4093 * the next in the list is 4).
4095 * Since at runtime we don't record the matching position in
4096 * the string for each word, we have to work that out for
4097 * each word we're about to process. The wordinfo table holds
4098 * the character length of each word; given that we recorded
4099 * at the start: the position of the shortest word and its
4100 * length in chars, we just need to move the pointer the
4101 * difference between the two char lengths. Depending on
4102 * Unicode status and folding, that's cheap or expensive.
4104 * This algorithm is optimised for the case where are only a
4105 * small number of accept states, i.e. 0,1, or maybe 2.
4106 * With lots of accepts states, and having to try all of them,
4107 * it becomes quadratic on number of accept states to find all
4112 /* what type of TRIE am I? (utf8 makes this contextual) */
4113 DECL_TRIE_TYPE(scan);
4115 /* what trie are we using right now */
4116 reg_trie_data * const trie
4117 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
4118 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
4119 U32 state = trie->startstate;
4122 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
4124 if (trie->states[ state ].wordnum) {
4126 PerlIO_printf(Perl_debug_log,
4127 "%*s %smatched empty string...%s\n",
4128 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4134 PerlIO_printf(Perl_debug_log,
4135 "%*s %sfailed to match trie start class...%s\n",
4136 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4143 U8 *uc = ( U8* )locinput;
4147 U8 *uscan = (U8*)NULL;
4148 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
4149 U32 charcount = 0; /* how many input chars we have matched */
4150 U32 accepted = 0; /* have we seen any accepting states? */
4152 ST.jump = trie->jump;
4155 ST.longfold = FALSE; /* char longer if folded => it's harder */
4158 /* fully traverse the TRIE; note the position of the
4159 shortest accept state and the wordnum of the longest
4162 while ( state && uc <= (U8*)(reginfo->strend) ) {
4163 U32 base = trie->states[ state ].trans.base;
4167 wordnum = trie->states[ state ].wordnum;
4169 if (wordnum) { /* it's an accept state */
4172 /* record first match position */
4174 ST.firstpos = (U8*)locinput;
4179 ST.firstchars = charcount;
4182 if (!ST.nextword || wordnum < ST.nextword)
4183 ST.nextword = wordnum;
4184 ST.topword = wordnum;
4187 DEBUG_TRIE_EXECUTE_r({
4188 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
4189 PerlIO_printf( Perl_debug_log,
4190 "%*s %sState: %4"UVxf" Accepted: %c ",
4191 2+depth * 2, "", PL_colors[4],
4192 (UV)state, (accepted ? 'Y' : 'N'));
4195 /* read a char and goto next state */
4196 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
4198 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
4199 uscan, len, uvc, charid, foldlen,
4206 base + charid - 1 - trie->uniquecharcount)) >= 0)
4208 && ((U32)offset < trie->lasttrans)
4209 && trie->trans[offset].check == state)
4211 state = trie->trans[offset].next;
4222 DEBUG_TRIE_EXECUTE_r(
4223 PerlIO_printf( Perl_debug_log,
4224 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
4225 charid, uvc, (UV)state, PL_colors[5] );
4231 /* calculate total number of accept states */
4236 w = trie->wordinfo[w].prev;
4239 ST.accepted = accepted;
4243 PerlIO_printf( Perl_debug_log,
4244 "%*s %sgot %"IVdf" possible matches%s\n",
4245 REPORT_CODE_OFF + depth * 2, "",
4246 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
4248 goto trie_first_try; /* jump into the fail handler */
4250 assert(0); /* NOTREACHED */
4252 case TRIE_next_fail: /* we failed - try next alternative */
4256 REGCP_UNWIND(ST.cp);
4257 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
4259 if (!--ST.accepted) {
4261 PerlIO_printf( Perl_debug_log,
4262 "%*s %sTRIE failed...%s\n",
4263 REPORT_CODE_OFF+depth*2, "",
4270 /* Find next-highest word to process. Note that this code
4271 * is O(N^2) per trie run (O(N) per branch), so keep tight */
4274 U16 const nextword = ST.nextword;
4275 reg_trie_wordinfo * const wordinfo
4276 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
4277 for (word=ST.topword; word; word=wordinfo[word].prev) {
4278 if (word > nextword && (!min || word < min))
4291 ST.lastparen = rex->lastparen;
4292 ST.lastcloseparen = rex->lastcloseparen;
4296 /* find start char of end of current word */
4298 U32 chars; /* how many chars to skip */
4299 reg_trie_data * const trie
4300 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
4302 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
4304 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
4309 /* the hard option - fold each char in turn and find
4310 * its folded length (which may be different */
4311 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
4319 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
4327 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
4332 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
4348 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
4349 ? ST.jump[ST.nextword]
4353 PerlIO_printf( Perl_debug_log,
4354 "%*s %sTRIE matched word #%d, continuing%s\n",
4355 REPORT_CODE_OFF+depth*2, "",
4362 if (ST.accepted > 1 || has_cutgroup) {
4363 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
4364 assert(0); /* NOTREACHED */
4366 /* only one choice left - just continue */
4368 AV *const trie_words
4369 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
4370 SV ** const tmp = av_fetch( trie_words,
4372 SV *sv= tmp ? sv_newmortal() : NULL;
4374 PerlIO_printf( Perl_debug_log,
4375 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
4376 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
4378 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
4379 PL_colors[0], PL_colors[1],
4380 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
4382 : "not compiled under -Dr",
4386 locinput = (char*)uc;
4387 continue; /* execute rest of RE */
4388 assert(0); /* NOTREACHED */
4392 case EXACT: { /* /abc/ */
4393 char *s = STRING(scan);
4395 if (utf8_target != is_utf8_pat) {
4396 /* The target and the pattern have differing utf8ness. */
4398 const char * const e = s + ln;
4401 /* The target is utf8, the pattern is not utf8.
4402 * Above-Latin1 code points can't match the pattern;
4403 * invariants match exactly, and the other Latin1 ones need
4404 * to be downgraded to a single byte in order to do the
4405 * comparison. (If we could be confident that the target
4406 * is not malformed, this could be refactored to have fewer
4407 * tests by just assuming that if the first bytes match, it
4408 * is an invariant, but there are tests in the test suite
4409 * dealing with (??{...}) which violate this) */
4411 if (l >= reginfo->strend
4412 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
4416 if (UTF8_IS_INVARIANT(*(U8*)l)) {
4423 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
4433 /* The target is not utf8, the pattern is utf8. */
4435 if (l >= reginfo->strend
4436 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
4440 if (UTF8_IS_INVARIANT(*(U8*)s)) {
4447 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
4459 /* The target and the pattern have the same utf8ness. */
4460 /* Inline the first character, for speed. */
4461 if (reginfo->strend - locinput < ln
4462 || UCHARAT(s) != nextchr
4463 || (ln > 1 && memNE(s, locinput, ln)))
4472 case EXACTFL: { /* /abc/il */
4474 const U8 * fold_array;
4476 U32 fold_utf8_flags;
4478 folder = foldEQ_locale;
4479 fold_array = PL_fold_locale;
4480 fold_utf8_flags = FOLDEQ_LOCALE;
4483 case EXACTFU_SS: /* /\x{df}/iu */
4484 case EXACTFU: /* /abc/iu */
4485 folder = foldEQ_latin1;
4486 fold_array = PL_fold_latin1;
4487 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
4490 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
4492 assert(! is_utf8_pat);
4494 case EXACTFA: /* /abc/iaa */
4495 folder = foldEQ_latin1;
4496 fold_array = PL_fold_latin1;
4497 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4500 case EXACTF: /* /abc/i This node only generated for
4501 non-utf8 patterns */
4502 assert(! is_utf8_pat);
4504 fold_array = PL_fold;
4505 fold_utf8_flags = 0;
4513 || state_num == EXACTFU_SS
4514 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
4516 /* Either target or the pattern are utf8, or has the issue where
4517 * the fold lengths may differ. */
4518 const char * const l = locinput;
4519 char *e = reginfo->strend;
4521 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
4522 l, &e, 0, utf8_target, fold_utf8_flags))
4530 /* Neither the target nor the pattern are utf8 */
4531 if (UCHARAT(s) != nextchr
4533 && UCHARAT(s) != fold_array[nextchr])
4537 if (reginfo->strend - locinput < ln)
4539 if (ln > 1 && ! folder(s, locinput, ln))
4545 /* XXX Could improve efficiency by separating these all out using a
4546 * macro or in-line function. At that point regcomp.c would no longer
4547 * have to set the FLAGS fields of these */
4548 case BOUNDL: /* /\b/l */
4549 case NBOUNDL: /* /\B/l */
4550 case BOUND: /* /\b/ */
4551 case BOUNDU: /* /\b/u */
4552 case BOUNDA: /* /\b/a */
4553 case NBOUND: /* /\B/ */
4554 case NBOUNDU: /* /\B/u */
4555 case NBOUNDA: /* /\B/a */
4556 /* was last char in word? */
4558 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
4559 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
4561 if (locinput == reginfo->strbeg)
4564 const U8 * const r =
4565 reghop3((U8*)locinput, -1, (U8*)(reginfo->strbeg));
4567 ln = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,
4570 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
4571 ln = isWORDCHAR_uni(ln);
4575 LOAD_UTF8_CHARCLASS_ALNUM();
4576 n = swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)locinput,
4581 ln = isWORDCHAR_LC_uvchr(ln);
4582 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC_utf8((U8*)locinput);
4587 /* Here the string isn't utf8, or is utf8 and only ascii
4588 * characters are to match \w. In the latter case looking at
4589 * the byte just prior to the current one may be just the final
4590 * byte of a multi-byte character. This is ok. There are two
4592 * 1) it is a single byte character, and then the test is doing
4593 * just what it's supposed to.
4594 * 2) it is a multi-byte character, in which case the final
4595 * byte is never mistakable for ASCII, and so the test
4596 * will say it is not a word character, which is the
4597 * correct answer. */
4598 ln = (locinput != reginfo->strbeg) ?
4599 UCHARAT(locinput - 1) : '\n';
4600 switch (FLAGS(scan)) {
4601 case REGEX_UNICODE_CHARSET:
4602 ln = isWORDCHAR_L1(ln);
4603 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_L1(nextchr);
4605 case REGEX_LOCALE_CHARSET:
4606 ln = isWORDCHAR_LC(ln);
4607 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC(nextchr);
4609 case REGEX_DEPENDS_CHARSET:
4610 ln = isWORDCHAR(ln);
4611 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR(nextchr);
4613 case REGEX_ASCII_RESTRICTED_CHARSET:
4614 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
4615 ln = isWORDCHAR_A(ln);
4616 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_A(nextchr);
4619 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
4622 /* Note requires that all BOUNDs be lower than all NBOUNDs in
4624 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
4628 case ANYOF: /* /[abc]/ */
4632 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
4635 locinput += UTF8SKIP(locinput);
4638 if (!REGINCLASS(rex, scan, (U8*)locinput))
4644 /* The argument (FLAGS) to all the POSIX node types is the class number
4647 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
4651 case POSIXL: /* \w or [:punct:] etc. under /l */
4655 /* Use isFOO_lc() for characters within Latin1. (Note that
4656 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4657 * wouldn't be invariant) */
4658 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4659 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
4663 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4664 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
4665 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4666 *(locinput + 1))))))
4671 else { /* Here, must be an above Latin-1 code point */
4672 goto utf8_posix_not_eos;
4675 /* Here, must be utf8 */
4676 locinput += UTF8SKIP(locinput);
4679 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
4683 case POSIXD: /* \w or [:punct:] etc. under /d */
4689 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
4691 if (NEXTCHR_IS_EOS) {
4695 /* All UTF-8 variants match */
4696 if (! UTF8_IS_INVARIANT(nextchr)) {
4697 goto increment_locinput;
4703 case POSIXA: /* \w or [:punct:] etc. under /a */
4706 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
4707 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
4708 * character is a single byte */
4711 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
4717 /* Here we are either not in utf8, or we matched a utf8-invariant,
4718 * so the next char is the next byte */
4722 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
4726 case POSIXU: /* \w or [:punct:] etc. under /u */
4728 if (NEXTCHR_IS_EOS) {
4733 /* Use _generic_isCC() for characters within Latin1. (Note that
4734 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4735 * wouldn't be invariant) */
4736 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4737 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
4744 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4745 if (! (to_complement
4746 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4754 else { /* Handle above Latin-1 code points */
4755 classnum = (_char_class_number) FLAGS(scan);
4756 if (classnum < _FIRST_NON_SWASH_CC) {
4758 /* Here, uses a swash to find such code points. Load if if
4759 * not done already */
4760 if (! PL_utf8_swash_ptrs[classnum]) {
4761 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
4762 PL_utf8_swash_ptrs[classnum]
4763 = _core_swash_init("utf8",
4766 PL_XPosix_ptrs[classnum], &flags);
4768 if (! (to_complement
4769 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
4770 (U8 *) locinput, TRUE))))
4775 else { /* Here, uses macros to find above Latin-1 code points */
4777 case _CC_ENUM_SPACE: /* XXX would require separate
4778 code if we revert the change
4779 of \v matching this */
4780 case _CC_ENUM_PSXSPC:
4781 if (! (to_complement
4782 ^ cBOOL(is_XPERLSPACE_high(locinput))))
4787 case _CC_ENUM_BLANK:
4788 if (! (to_complement
4789 ^ cBOOL(is_HORIZWS_high(locinput))))
4794 case _CC_ENUM_XDIGIT:
4795 if (! (to_complement
4796 ^ cBOOL(is_XDIGIT_high(locinput))))
4801 case _CC_ENUM_VERTSPACE:
4802 if (! (to_complement
4803 ^ cBOOL(is_VERTWS_high(locinput))))
4808 default: /* The rest, e.g. [:cntrl:], can't match
4810 if (! to_complement) {
4816 locinput += UTF8SKIP(locinput);
4820 case CLUMP: /* Match \X: logical Unicode character. This is defined as
4821 a Unicode extended Grapheme Cluster */
4822 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
4823 extended Grapheme Cluster is:
4826 | Prepend* Begin Extend*
4829 Begin is: ( Special_Begin | ! Control )
4830 Special_Begin is: ( Regional-Indicator+ | Hangul-syllable )
4831 Extend is: ( Grapheme_Extend | Spacing_Mark )
4832 Control is: [ GCB_Control | CR | LF ]
4833 Hangul-syllable is: ( T+ | ( L* ( L | ( LVT | ( V | LV ) V* ) T* ) ))
4835 If we create a 'Regular_Begin' = Begin - Special_Begin, then
4838 Begin is ( Regular_Begin + Special Begin )
4840 It turns out that 98.4% of all Unicode code points match
4841 Regular_Begin. Doing it this way eliminates a table match in
4842 the previous implementation for almost all Unicode code points.
4844 There is a subtlety with Prepend* which showed up in testing.
4845 Note that the Begin, and only the Begin is required in:
4846 | Prepend* Begin Extend*
4847 Also, Begin contains '! Control'. A Prepend must be a
4848 '! Control', which means it must also be a Begin. What it
4849 comes down to is that if we match Prepend* and then find no
4850 suitable Begin afterwards, that if we backtrack the last
4851 Prepend, that one will be a suitable Begin.
4856 if (! utf8_target) {
4858 /* Match either CR LF or '.', as all the other possibilities
4860 locinput++; /* Match the . or CR */
4861 if (nextchr == '\r' /* And if it was CR, and the next is LF,
4863 && locinput < reginfo->strend
4864 && UCHARAT(locinput) == '\n')
4871 /* Utf8: See if is ( CR LF ); already know that locinput <
4872 * reginfo->strend, so locinput+1 is in bounds */
4873 if ( nextchr == '\r' && locinput+1 < reginfo->strend
4874 && UCHARAT(locinput + 1) == '\n')
4881 /* In case have to backtrack to beginning, then match '.' */
4882 char *starting = locinput;
4884 /* In case have to backtrack the last prepend */
4885 char *previous_prepend = NULL;
4887 LOAD_UTF8_CHARCLASS_GCB();
4889 /* Match (prepend)* */
4890 while (locinput < reginfo->strend
4891 && (len = is_GCB_Prepend_utf8(locinput)))
4893 previous_prepend = locinput;
4897 /* As noted above, if we matched a prepend character, but
4898 * the next thing won't match, back off the last prepend we
4899 * matched, as it is guaranteed to match the begin */
4900 if (previous_prepend
4901 && (locinput >= reginfo->strend
4902 || (! swash_fetch(PL_utf8_X_regular_begin,
4903 (U8*)locinput, utf8_target)
4904 && ! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)))
4907 locinput = previous_prepend;
4910 /* Note that here we know reginfo->strend > locinput, as we
4911 * tested that upon input to this switch case, and if we
4912 * moved locinput forward, we tested the result just above
4913 * and it either passed, or we backed off so that it will
4915 if (swash_fetch(PL_utf8_X_regular_begin,
4916 (U8*)locinput, utf8_target)) {
4917 locinput += UTF8SKIP(locinput);
4919 else if (! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)) {
4921 /* Here did not match the required 'Begin' in the
4922 * second term. So just match the very first
4923 * character, the '.' of the final term of the regex */
4924 locinput = starting + UTF8SKIP(starting);
4928 /* Here is a special begin. It can be composed of
4929 * several individual characters. One possibility is
4931 if ((len = is_GCB_RI_utf8(locinput))) {
4933 while (locinput < reginfo->strend
4934 && (len = is_GCB_RI_utf8(locinput)))
4938 } else if ((len = is_GCB_T_utf8(locinput))) {
4939 /* Another possibility is T+ */
4941 while (locinput < reginfo->strend
4942 && (len = is_GCB_T_utf8(locinput)))
4948 /* Here, neither RI+ nor T+; must be some other
4949 * Hangul. That means it is one of the others: L,
4950 * LV, LVT or V, and matches:
4951 * L* (L | LVT T* | V * V* T* | LV V* T*) */
4954 while (locinput < reginfo->strend
4955 && (len = is_GCB_L_utf8(locinput)))
4960 /* Here, have exhausted L*. If the next character
4961 * is not an LV, LVT nor V, it means we had to have
4962 * at least one L, so matches L+ in the original
4963 * equation, we have a complete hangul syllable.
4966 if (locinput < reginfo->strend
4967 && is_GCB_LV_LVT_V_utf8(locinput))
4969 /* Otherwise keep going. Must be LV, LVT or V.
4970 * See if LVT, by first ruling out V, then LV */
4971 if (! is_GCB_V_utf8(locinput)
4972 /* All but every TCount one is LV */
4973 && (valid_utf8_to_uvchr((U8 *) locinput,
4978 locinput += UTF8SKIP(locinput);
4981 /* Must be V or LV. Take it, then match
4983 locinput += UTF8SKIP(locinput);
4984 while (locinput < reginfo->strend
4985 && (len = is_GCB_V_utf8(locinput)))
4991 /* And any of LV, LVT, or V can be followed
4993 while (locinput < reginfo->strend
4994 && (len = is_GCB_T_utf8(locinput)))
5002 /* Match any extender */
5003 while (locinput < reginfo->strend
5004 && swash_fetch(PL_utf8_X_extend,
5005 (U8*)locinput, utf8_target))
5007 locinput += UTF8SKIP(locinput);
5011 if (locinput > reginfo->strend) sayNO;
5015 case NREFFL: /* /\g{name}/il */
5016 { /* The capture buffer cases. The ones beginning with N for the
5017 named buffers just convert to the equivalent numbered and
5018 pretend they were called as the corresponding numbered buffer
5020 /* don't initialize these in the declaration, it makes C++
5025 const U8 *fold_array;
5028 folder = foldEQ_locale;
5029 fold_array = PL_fold_locale;
5031 utf8_fold_flags = FOLDEQ_LOCALE;
5034 case NREFFA: /* /\g{name}/iaa */
5035 folder = foldEQ_latin1;
5036 fold_array = PL_fold_latin1;
5038 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5041 case NREFFU: /* /\g{name}/iu */
5042 folder = foldEQ_latin1;
5043 fold_array = PL_fold_latin1;
5045 utf8_fold_flags = 0;
5048 case NREFF: /* /\g{name}/i */
5050 fold_array = PL_fold;
5052 utf8_fold_flags = 0;
5055 case NREF: /* /\g{name}/ */
5059 utf8_fold_flags = 0;
5062 /* For the named back references, find the corresponding buffer
5064 n = reg_check_named_buff_matched(rex,scan);
5069 goto do_nref_ref_common;
5071 case REFFL: /* /\1/il */
5072 folder = foldEQ_locale;
5073 fold_array = PL_fold_locale;
5074 utf8_fold_flags = FOLDEQ_LOCALE;
5077 case REFFA: /* /\1/iaa */
5078 folder = foldEQ_latin1;
5079 fold_array = PL_fold_latin1;
5080 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5083 case REFFU: /* /\1/iu */
5084 folder = foldEQ_latin1;
5085 fold_array = PL_fold_latin1;
5086 utf8_fold_flags = 0;
5089 case REFF: /* /\1/i */
5091 fold_array = PL_fold;
5092 utf8_fold_flags = 0;
5095 case REF: /* /\1/ */
5098 utf8_fold_flags = 0;
5102 n = ARG(scan); /* which paren pair */
5105 ln = rex->offs[n].start;
5106 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5107 if (rex->lastparen < n || ln == -1)
5108 sayNO; /* Do not match unless seen CLOSEn. */
5109 if (ln == rex->offs[n].end)
5112 s = reginfo->strbeg + ln;
5113 if (type != REF /* REF can do byte comparison */
5114 && (utf8_target || type == REFFU || type == REFFL))
5116 char * limit = reginfo->strend;
5118 /* This call case insensitively compares the entire buffer
5119 * at s, with the current input starting at locinput, but
5120 * not going off the end given by reginfo->strend, and
5121 * returns in <limit> upon success, how much of the
5122 * current input was matched */
5123 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
5124 locinput, &limit, 0, utf8_target, utf8_fold_flags))
5132 /* Not utf8: Inline the first character, for speed. */
5133 if (!NEXTCHR_IS_EOS &&
5134 UCHARAT(s) != nextchr &&
5136 UCHARAT(s) != fold_array[nextchr]))
5138 ln = rex->offs[n].end - ln;
5139 if (locinput + ln > reginfo->strend)
5141 if (ln > 1 && (type == REF
5142 ? memNE(s, locinput, ln)
5143 : ! folder(s, locinput, ln)))
5149 case NOTHING: /* null op; e.g. the 'nothing' following
5150 * the '*' in m{(a+|b)*}' */
5152 case TAIL: /* placeholder while compiling (A|B|C) */
5155 case BACK: /* ??? doesn't appear to be used ??? */
5159 #define ST st->u.eval
5164 regexp_internal *rei;
5165 regnode *startpoint;
5167 case GOSTART: /* (?R) */
5168 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
5169 if (cur_eval && cur_eval->locinput==locinput) {
5170 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
5171 Perl_croak(aTHX_ "Infinite recursion in regex");
5172 if ( ++nochange_depth > max_nochange_depth )
5174 "Pattern subroutine nesting without pos change"
5175 " exceeded limit in regex");
5182 if (OP(scan)==GOSUB) {
5183 startpoint = scan + ARG2L(scan);
5184 ST.close_paren = ARG(scan);
5186 startpoint = rei->program+1;
5190 /* Save all the positions seen so far. */
5191 ST.cp = regcppush(rex, 0, maxopenparen);
5192 REGCP_SET(ST.lastcp);
5194 /* and then jump to the code we share with EVAL */
5195 goto eval_recurse_doit;
5197 assert(0); /* NOTREACHED */
5199 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
5200 if (cur_eval && cur_eval->locinput==locinput) {
5201 if ( ++nochange_depth > max_nochange_depth )
5202 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
5207 /* execute the code in the {...} */
5211 OP * const oop = PL_op;
5212 COP * const ocurcop = PL_curcop;
5216 /* save *all* paren positions */
5217 regcppush(rex, 0, maxopenparen);
5218 REGCP_SET(runops_cp);
5221 caller_cv = find_runcv(NULL);
5225 if (rexi->data->what[n] == 'r') { /* code from an external qr */
5227 (REGEXP*)(rexi->data->data[n])
5230 nop = (OP*)rexi->data->data[n+1];
5232 else if (rexi->data->what[n] == 'l') { /* literal code */
5234 nop = (OP*)rexi->data->data[n];
5235 assert(CvDEPTH(newcv));
5238 /* literal with own CV */
5239 assert(rexi->data->what[n] == 'L');
5240 newcv = rex->qr_anoncv;
5241 nop = (OP*)rexi->data->data[n];
5244 /* normally if we're about to execute code from the same
5245 * CV that we used previously, we just use the existing
5246 * CX stack entry. However, its possible that in the
5247 * meantime we may have backtracked, popped from the save
5248 * stack, and undone the SAVECOMPPAD(s) associated with
5249 * PUSH_MULTICALL; in which case PL_comppad no longer
5250 * points to newcv's pad. */
5251 if (newcv != last_pushed_cv || PL_comppad != last_pad)
5253 U8 flags = (CXp_SUB_RE |
5254 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
5255 if (last_pushed_cv) {
5256 CHANGE_MULTICALL_FLAGS(newcv, flags);
5259 PUSH_MULTICALL_FLAGS(newcv, flags);
5261 last_pushed_cv = newcv;
5264 /* these assignments are just to silence compiler
5266 multicall_cop = NULL;
5269 last_pad = PL_comppad;
5271 /* the initial nextstate you would normally execute
5272 * at the start of an eval (which would cause error
5273 * messages to come from the eval), may be optimised
5274 * away from the execution path in the regex code blocks;
5275 * so manually set PL_curcop to it initially */
5277 OP *o = cUNOPx(nop)->op_first;
5278 assert(o->op_type == OP_NULL);
5279 if (o->op_targ == OP_SCOPE) {
5280 o = cUNOPo->op_first;
5283 assert(o->op_targ == OP_LEAVE);
5284 o = cUNOPo->op_first;
5285 assert(o->op_type == OP_ENTER);
5289 if (o->op_type != OP_STUB) {
5290 assert( o->op_type == OP_NEXTSTATE
5291 || o->op_type == OP_DBSTATE
5292 || (o->op_type == OP_NULL
5293 && ( o->op_targ == OP_NEXTSTATE
5294 || o->op_targ == OP_DBSTATE
5298 PL_curcop = (COP*)o;
5303 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
5304 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
5306 rex->offs[0].end = locinput - reginfo->strbeg;
5307 if (reginfo->info_aux_eval->pos_magic)
5308 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
5309 reginfo->sv, reginfo->strbeg,
5310 locinput - reginfo->strbeg);
5313 SV *sv_mrk = get_sv("REGMARK", 1);
5314 sv_setsv(sv_mrk, sv_yes_mark);
5317 /* we don't use MULTICALL here as we want to call the
5318 * first op of the block of interest, rather than the
5319 * first op of the sub */
5320 before = (IV)(SP-PL_stack_base);
5322 CALLRUNOPS(aTHX); /* Scalar context. */
5324 if ((IV)(SP-PL_stack_base) == before)
5325 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
5331 /* before restoring everything, evaluate the returned
5332 * value, so that 'uninit' warnings don't use the wrong
5333 * PL_op or pad. Also need to process any magic vars
5334 * (e.g. $1) *before* parentheses are restored */
5339 if (logical == 0) /* (?{})/ */
5340 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
5341 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
5342 sw = cBOOL(SvTRUE(ret));
5345 else { /* /(??{}) */
5346 /* if its overloaded, let the regex compiler handle
5347 * it; otherwise extract regex, or stringify */
5348 if (SvGMAGICAL(ret))
5349 ret = sv_mortalcopy(ret);
5350 if (!SvAMAGIC(ret)) {
5354 if (SvTYPE(sv) == SVt_REGEXP)
5355 re_sv = (REGEXP*) sv;
5356 else if (SvSMAGICAL(ret)) {
5357 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
5359 re_sv = (REGEXP *) mg->mg_obj;
5362 /* force any undef warnings here */
5363 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
5364 ret = sv_mortalcopy(ret);
5365 (void) SvPV_force_nolen(ret);
5371 /* *** Note that at this point we don't restore
5372 * PL_comppad, (or pop the CxSUB) on the assumption it may
5373 * be used again soon. This is safe as long as nothing
5374 * in the regexp code uses the pad ! */
5376 PL_curcop = ocurcop;
5377 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
5378 PL_curpm = PL_reg_curpm;
5384 /* only /(??{})/ from now on */
5387 /* extract RE object from returned value; compiling if
5391 re_sv = reg_temp_copy(NULL, re_sv);
5396 if (SvUTF8(ret) && IN_BYTES) {
5397 /* In use 'bytes': make a copy of the octet
5398 * sequence, but without the flag on */
5400 const char *const p = SvPV(ret, len);
5401 ret = newSVpvn_flags(p, len, SVs_TEMP);
5403 if (rex->intflags & PREGf_USE_RE_EVAL)
5404 pm_flags |= PMf_USE_RE_EVAL;
5406 /* if we got here, it should be an engine which
5407 * supports compiling code blocks and stuff */
5408 assert(rex->engine && rex->engine->op_comp);
5409 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
5410 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
5411 rex->engine, NULL, NULL,
5412 /* copy /msix etc to inner pattern */
5417 & (SVs_TEMP | SVs_GMG | SVf_ROK))
5418 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
5419 /* This isn't a first class regexp. Instead, it's
5420 caching a regexp onto an existing, Perl visible
5422 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
5428 RXp_MATCH_COPIED_off(re);
5429 re->subbeg = rex->subbeg;
5430 re->sublen = rex->sublen;
5431 re->suboffset = rex->suboffset;
5432 re->subcoffset = rex->subcoffset;
5434 re->lastcloseparen = 0;
5437 debug_start_match(re_sv, utf8_target, locinput,
5438 reginfo->strend, "Matching embedded");
5440 startpoint = rei->program + 1;
5441 ST.close_paren = 0; /* only used for GOSUB */
5442 /* Save all the seen positions so far. */
5443 ST.cp = regcppush(rex, 0, maxopenparen);
5444 REGCP_SET(ST.lastcp);
5445 /* and set maxopenparen to 0, since we are starting a "fresh" match */
5447 /* run the pattern returned from (??{...}) */
5449 eval_recurse_doit: /* Share code with GOSUB below this line
5450 * At this point we expect the stack context to be
5451 * set up correctly */
5453 /* invalidate the S-L poscache. We're now executing a
5454 * different set of WHILEM ops (and their associated
5455 * indexes) against the same string, so the bits in the
5456 * cache are meaningless. Setting maxiter to zero forces
5457 * the cache to be invalidated and zeroed before reuse.
5458 * XXX This is too dramatic a measure. Ideally we should
5459 * save the old cache and restore when running the outer
5461 reginfo->poscache_maxiter = 0;
5463 /* the new regexp might have a different is_utf8_pat than we do */
5464 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
5466 ST.prev_rex = rex_sv;
5467 ST.prev_curlyx = cur_curlyx;
5469 SET_reg_curpm(rex_sv);
5474 ST.prev_eval = cur_eval;
5476 /* now continue from first node in postoned RE */
5477 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
5478 assert(0); /* NOTREACHED */
5481 case EVAL_AB: /* cleanup after a successful (??{A})B */
5482 /* note: this is called twice; first after popping B, then A */
5483 rex_sv = ST.prev_rex;
5484 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5485 SET_reg_curpm(rex_sv);
5486 rex = ReANY(rex_sv);
5487 rexi = RXi_GET(rex);
5489 /* preserve $^R across LEAVE's. See Bug 121070. */
5490 SV *save_sv= GvSV(PL_replgv);
5491 SvREFCNT_inc(save_sv);
5492 regcpblow(ST.cp); /* LEAVE in disguise */
5493 sv_setsv(GvSV(PL_replgv), save_sv);
5494 SvREFCNT_dec(save_sv);
5496 cur_eval = ST.prev_eval;
5497 cur_curlyx = ST.prev_curlyx;
5499 /* Invalidate cache. See "invalidate" comment above. */
5500 reginfo->poscache_maxiter = 0;
5501 if ( nochange_depth )
5506 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
5507 /* note: this is called twice; first after popping B, then A */
5508 rex_sv = ST.prev_rex;
5509 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5510 SET_reg_curpm(rex_sv);
5511 rex = ReANY(rex_sv);
5512 rexi = RXi_GET(rex);
5514 REGCP_UNWIND(ST.lastcp);
5515 regcppop(rex, &maxopenparen);
5516 cur_eval = ST.prev_eval;
5517 cur_curlyx = ST.prev_curlyx;
5518 /* Invalidate cache. See "invalidate" comment above. */
5519 reginfo->poscache_maxiter = 0;
5520 if ( nochange_depth )
5526 n = ARG(scan); /* which paren pair */
5527 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
5528 if (n > maxopenparen)
5530 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
5531 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
5535 (IV)rex->offs[n].start_tmp,
5541 /* XXX really need to log other places start/end are set too */
5542 #define CLOSE_CAPTURE \
5543 rex->offs[n].start = rex->offs[n].start_tmp; \
5544 rex->offs[n].end = locinput - reginfo->strbeg; \
5545 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
5546 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
5548 PTR2UV(rex->offs), \
5550 (IV)rex->offs[n].start, \
5551 (IV)rex->offs[n].end \
5555 n = ARG(scan); /* which paren pair */
5557 if (n > rex->lastparen)
5559 rex->lastcloseparen = n;
5560 if (cur_eval && cur_eval->u.eval.close_paren == n) {
5565 case ACCEPT: /* (*ACCEPT) */
5569 cursor && OP(cursor)!=END;
5570 cursor=regnext(cursor))
5572 if ( OP(cursor)==CLOSE ){
5574 if ( n <= lastopen ) {
5576 if (n > rex->lastparen)
5578 rex->lastcloseparen = n;
5579 if ( n == ARG(scan) || (cur_eval &&
5580 cur_eval->u.eval.close_paren == n))
5589 case GROUPP: /* (?(1)) */
5590 n = ARG(scan); /* which paren pair */
5591 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
5594 case NGROUPP: /* (?(<name>)) */
5595 /* reg_check_named_buff_matched returns 0 for no match */
5596 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
5599 case INSUBP: /* (?(R)) */
5601 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
5604 case DEFINEP: /* (?(DEFINE)) */
5608 case IFTHEN: /* (?(cond)A|B) */
5609 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5611 next = NEXTOPER(NEXTOPER(scan));
5613 next = scan + ARG(scan);
5614 if (OP(next) == IFTHEN) /* Fake one. */
5615 next = NEXTOPER(NEXTOPER(next));
5619 case LOGICAL: /* modifier for EVAL and IFMATCH */
5620 logical = scan->flags;
5623 /*******************************************************************
5625 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
5626 pattern, where A and B are subpatterns. (For simple A, CURLYM or
5627 STAR/PLUS/CURLY/CURLYN are used instead.)
5629 A*B is compiled as <CURLYX><A><WHILEM><B>
5631 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
5632 state, which contains the current count, initialised to -1. It also sets
5633 cur_curlyx to point to this state, with any previous value saved in the
5636 CURLYX then jumps straight to the WHILEM op, rather than executing A,
5637 since the pattern may possibly match zero times (i.e. it's a while {} loop
5638 rather than a do {} while loop).
5640 Each entry to WHILEM represents a successful match of A. The count in the
5641 CURLYX block is incremented, another WHILEM state is pushed, and execution
5642 passes to A or B depending on greediness and the current count.
5644 For example, if matching against the string a1a2a3b (where the aN are
5645 substrings that match /A/), then the match progresses as follows: (the
5646 pushed states are interspersed with the bits of strings matched so far):
5649 <CURLYX cnt=0><WHILEM>
5650 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
5651 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
5652 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
5653 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
5655 (Contrast this with something like CURLYM, which maintains only a single
5659 a1 <CURLYM cnt=1> a2
5660 a1 a2 <CURLYM cnt=2> a3
5661 a1 a2 a3 <CURLYM cnt=3> b
5664 Each WHILEM state block marks a point to backtrack to upon partial failure
5665 of A or B, and also contains some minor state data related to that
5666 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
5667 overall state, such as the count, and pointers to the A and B ops.
5669 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
5670 must always point to the *current* CURLYX block, the rules are:
5672 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
5673 and set cur_curlyx to point the new block.
5675 When popping the CURLYX block after a successful or unsuccessful match,
5676 restore the previous cur_curlyx.
5678 When WHILEM is about to execute B, save the current cur_curlyx, and set it
5679 to the outer one saved in the CURLYX block.
5681 When popping the WHILEM block after a successful or unsuccessful B match,
5682 restore the previous cur_curlyx.
5684 Here's an example for the pattern (AI* BI)*BO
5685 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
5688 curlyx backtrack stack
5689 ------ ---------------
5691 CO <CO prev=NULL> <WO>
5692 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5693 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5694 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
5696 At this point the pattern succeeds, and we work back down the stack to
5697 clean up, restoring as we go:
5699 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5700 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5701 CO <CO prev=NULL> <WO>
5704 *******************************************************************/
5706 #define ST st->u.curlyx
5708 case CURLYX: /* start of /A*B/ (for complex A) */
5710 /* No need to save/restore up to this paren */
5711 I32 parenfloor = scan->flags;
5713 assert(next); /* keep Coverity happy */
5714 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
5717 /* XXXX Probably it is better to teach regpush to support
5718 parenfloor > maxopenparen ... */
5719 if (parenfloor > (I32)rex->lastparen)
5720 parenfloor = rex->lastparen; /* Pessimization... */
5722 ST.prev_curlyx= cur_curlyx;
5724 ST.cp = PL_savestack_ix;
5726 /* these fields contain the state of the current curly.
5727 * they are accessed by subsequent WHILEMs */
5728 ST.parenfloor = parenfloor;
5733 ST.count = -1; /* this will be updated by WHILEM */
5734 ST.lastloc = NULL; /* this will be updated by WHILEM */
5736 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
5737 assert(0); /* NOTREACHED */
5740 case CURLYX_end: /* just finished matching all of A*B */
5741 cur_curlyx = ST.prev_curlyx;
5743 assert(0); /* NOTREACHED */
5745 case CURLYX_end_fail: /* just failed to match all of A*B */
5747 cur_curlyx = ST.prev_curlyx;
5749 assert(0); /* NOTREACHED */
5753 #define ST st->u.whilem
5755 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
5757 /* see the discussion above about CURLYX/WHILEM */
5759 int min = ARG1(cur_curlyx->u.curlyx.me);
5760 int max = ARG2(cur_curlyx->u.curlyx.me);
5761 regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
5763 assert(cur_curlyx); /* keep Coverity happy */
5764 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
5765 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
5766 ST.cache_offset = 0;
5770 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5771 "%*s whilem: matched %ld out of %d..%d\n",
5772 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
5775 /* First just match a string of min A's. */
5778 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5780 cur_curlyx->u.curlyx.lastloc = locinput;
5781 REGCP_SET(ST.lastcp);
5783 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
5784 assert(0); /* NOTREACHED */
5787 /* If degenerate A matches "", assume A done. */
5789 if (locinput == cur_curlyx->u.curlyx.lastloc) {
5790 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5791 "%*s whilem: empty match detected, trying continuation...\n",
5792 REPORT_CODE_OFF+depth*2, "")
5794 goto do_whilem_B_max;
5797 /* super-linear cache processing.
5799 * The idea here is that for certain types of CURLYX/WHILEM -
5800 * principally those whose upper bound is infinity (and
5801 * excluding regexes that have things like \1 and other very
5802 * non-regular expresssiony things), then if a pattern like
5803 * /....A*.../ fails and we backtrack to the WHILEM, then we
5804 * make a note that this particular WHILEM op was at string
5805 * position 47 (say) when the rest of pattern failed. Then, if
5806 * we ever find ourselves back at that WHILEM, and at string
5807 * position 47 again, we can just fail immediately rather than
5808 * running the rest of the pattern again.
5810 * This is very handy when patterns start to go
5811 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
5812 * with a combinatorial explosion of backtracking.
5814 * The cache is implemented as a bit array, with one bit per
5815 * string byte position per WHILEM op (up to 16) - so its
5816 * between 0.25 and 2x the string size.
5818 * To avoid allocating a poscache buffer every time, we do an
5819 * initially countdown; only after we have executed a WHILEM
5820 * op (string-length x #WHILEMs) times do we allocate the
5823 * The top 4 bits of scan->flags byte say how many different
5824 * relevant CURLLYX/WHILEM op pairs there are, while the
5825 * bottom 4-bits is the identifying index number of this
5831 if (!reginfo->poscache_maxiter) {
5832 /* start the countdown: Postpone detection until we
5833 * know the match is not *that* much linear. */
5834 reginfo->poscache_maxiter
5835 = (reginfo->strend - reginfo->strbeg + 1)
5837 /* possible overflow for long strings and many CURLYX's */
5838 if (reginfo->poscache_maxiter < 0)
5839 reginfo->poscache_maxiter = I32_MAX;
5840 reginfo->poscache_iter = reginfo->poscache_maxiter;
5843 if (reginfo->poscache_iter-- == 0) {
5844 /* initialise cache */
5845 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
5846 regmatch_info_aux *const aux = reginfo->info_aux;
5847 if (aux->poscache) {
5848 if ((SSize_t)reginfo->poscache_size < size) {
5849 Renew(aux->poscache, size, char);
5850 reginfo->poscache_size = size;
5852 Zero(aux->poscache, size, char);
5855 reginfo->poscache_size = size;
5856 Newxz(aux->poscache, size, char);
5858 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5859 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
5860 PL_colors[4], PL_colors[5])
5864 if (reginfo->poscache_iter < 0) {
5865 /* have we already failed at this position? */
5866 SSize_t offset, mask;
5868 reginfo->poscache_iter = -1; /* stop eventual underflow */
5869 offset = (scan->flags & 0xf) - 1
5870 + (locinput - reginfo->strbeg)
5872 mask = 1 << (offset % 8);
5874 if (reginfo->info_aux->poscache[offset] & mask) {
5875 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5876 "%*s whilem: (cache) already tried at this position...\n",
5877 REPORT_CODE_OFF+depth*2, "")
5879 sayNO; /* cache records failure */
5881 ST.cache_offset = offset;
5882 ST.cache_mask = mask;
5886 /* Prefer B over A for minimal matching. */
5888 if (cur_curlyx->u.curlyx.minmod) {
5889 ST.save_curlyx = cur_curlyx;
5890 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5891 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
5893 REGCP_SET(ST.lastcp);
5894 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
5896 assert(0); /* NOTREACHED */
5899 /* Prefer A over B for maximal matching. */
5901 if (n < max) { /* More greed allowed? */
5902 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5904 cur_curlyx->u.curlyx.lastloc = locinput;
5905 REGCP_SET(ST.lastcp);
5906 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
5907 assert(0); /* NOTREACHED */
5909 goto do_whilem_B_max;
5911 assert(0); /* NOTREACHED */
5913 case WHILEM_B_min: /* just matched B in a minimal match */
5914 case WHILEM_B_max: /* just matched B in a maximal match */
5915 cur_curlyx = ST.save_curlyx;
5917 assert(0); /* NOTREACHED */
5919 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
5920 cur_curlyx = ST.save_curlyx;
5921 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5922 cur_curlyx->u.curlyx.count--;
5924 assert(0); /* NOTREACHED */
5926 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
5928 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
5929 REGCP_UNWIND(ST.lastcp);
5930 regcppop(rex, &maxopenparen);
5931 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5932 cur_curlyx->u.curlyx.count--;
5934 assert(0); /* NOTREACHED */
5936 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5937 REGCP_UNWIND(ST.lastcp);
5938 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
5939 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5940 "%*s whilem: failed, trying continuation...\n",
5941 REPORT_CODE_OFF+depth*2, "")
5944 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5945 && ckWARN(WARN_REGEXP)
5946 && !reginfo->warned)
5948 reginfo->warned = TRUE;
5949 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5950 "Complex regular subexpression recursion limit (%d) "
5956 ST.save_curlyx = cur_curlyx;
5957 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5958 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
5960 assert(0); /* NOTREACHED */
5962 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
5963 cur_curlyx = ST.save_curlyx;
5964 REGCP_UNWIND(ST.lastcp);
5965 regcppop(rex, &maxopenparen);
5967 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
5968 /* Maximum greed exceeded */
5969 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5970 && ckWARN(WARN_REGEXP)
5971 && !reginfo->warned)
5973 reginfo->warned = TRUE;
5974 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5975 "Complex regular subexpression recursion "
5976 "limit (%d) exceeded",
5979 cur_curlyx->u.curlyx.count--;
5983 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5984 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
5986 /* Try grabbing another A and see if it helps. */
5987 cur_curlyx->u.curlyx.lastloc = locinput;
5988 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5990 REGCP_SET(ST.lastcp);
5991 PUSH_STATE_GOTO(WHILEM_A_min,
5992 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
5994 assert(0); /* NOTREACHED */
5997 #define ST st->u.branch
5999 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6000 next = scan + ARG(scan);
6003 scan = NEXTOPER(scan);
6006 case BRANCH: /* /(...|A|...)/ */
6007 scan = NEXTOPER(scan); /* scan now points to inner node */
6008 ST.lastparen = rex->lastparen;
6009 ST.lastcloseparen = rex->lastcloseparen;
6010 ST.next_branch = next;
6013 /* Now go into the branch */
6015 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
6017 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
6019 assert(0); /* NOTREACHED */
6021 case CUTGROUP: /* /(*THEN)/ */
6022 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
6023 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6024 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
6025 assert(0); /* NOTREACHED */
6027 case CUTGROUP_next_fail:
6030 if (st->u.mark.mark_name)
6031 sv_commit = st->u.mark.mark_name;
6033 assert(0); /* NOTREACHED */
6037 assert(0); /* NOTREACHED */
6039 case BRANCH_next_fail: /* that branch failed; try the next, if any */
6044 REGCP_UNWIND(ST.cp);
6045 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6046 scan = ST.next_branch;
6047 /* no more branches? */
6048 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
6050 PerlIO_printf( Perl_debug_log,
6051 "%*s %sBRANCH failed...%s\n",
6052 REPORT_CODE_OFF+depth*2, "",
6058 continue; /* execute next BRANCH[J] op */
6059 assert(0); /* NOTREACHED */
6061 case MINMOD: /* next op will be non-greedy, e.g. A*? */
6066 #define ST st->u.curlym
6068 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
6070 /* This is an optimisation of CURLYX that enables us to push
6071 * only a single backtracking state, no matter how many matches
6072 * there are in {m,n}. It relies on the pattern being constant
6073 * length, with no parens to influence future backrefs
6077 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6079 ST.lastparen = rex->lastparen;
6080 ST.lastcloseparen = rex->lastcloseparen;
6082 /* if paren positive, emulate an OPEN/CLOSE around A */
6084 U32 paren = ST.me->flags;
6085 if (paren > maxopenparen)
6086 maxopenparen = paren;
6087 scan += NEXT_OFF(scan); /* Skip former OPEN. */
6095 ST.c1 = CHRTEST_UNINIT;
6098 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
6101 curlym_do_A: /* execute the A in /A{m,n}B/ */
6102 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
6103 assert(0); /* NOTREACHED */
6105 case CURLYM_A: /* we've just matched an A */
6107 /* after first match, determine A's length: u.curlym.alen */
6108 if (ST.count == 1) {
6109 if (reginfo->is_utf8_target) {
6110 char *s = st->locinput;
6111 while (s < locinput) {
6117 ST.alen = locinput - st->locinput;
6120 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
6123 PerlIO_printf(Perl_debug_log,
6124 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
6125 (int)(REPORT_CODE_OFF+(depth*2)), "",
6126 (IV) ST.count, (IV)ST.alen)
6129 if (cur_eval && cur_eval->u.eval.close_paren &&
6130 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6134 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
6135 if ( max == REG_INFTY || ST.count < max )
6136 goto curlym_do_A; /* try to match another A */
6138 goto curlym_do_B; /* try to match B */
6140 case CURLYM_A_fail: /* just failed to match an A */
6141 REGCP_UNWIND(ST.cp);
6143 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
6144 || (cur_eval && cur_eval->u.eval.close_paren &&
6145 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
6148 curlym_do_B: /* execute the B in /A{m,n}B/ */
6149 if (ST.c1 == CHRTEST_UNINIT) {
6150 /* calculate c1 and c2 for possible match of 1st char
6151 * following curly */
6152 ST.c1 = ST.c2 = CHRTEST_VOID;
6153 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
6154 regnode *text_node = ST.B;
6155 if (! HAS_TEXT(text_node))
6156 FIND_NEXT_IMPT(text_node);
6159 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
6161 But the former is redundant in light of the latter.
6163 if this changes back then the macro for
6164 IS_TEXT and friends need to change.
6166 if (PL_regkind[OP(text_node)] == EXACT) {
6167 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6168 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6178 PerlIO_printf(Perl_debug_log,
6179 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
6180 (int)(REPORT_CODE_OFF+(depth*2)),
6183 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
6184 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
6185 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6186 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6188 /* simulate B failing */
6190 PerlIO_printf(Perl_debug_log,
6191 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
6192 (int)(REPORT_CODE_OFF+(depth*2)),"",
6193 valid_utf8_to_uvchr((U8 *) locinput, NULL),
6194 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
6195 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
6197 state_num = CURLYM_B_fail;
6198 goto reenter_switch;
6201 else if (nextchr != ST.c1 && nextchr != ST.c2) {
6202 /* simulate B failing */
6204 PerlIO_printf(Perl_debug_log,
6205 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
6206 (int)(REPORT_CODE_OFF+(depth*2)),"",
6207 (int) nextchr, ST.c1, ST.c2)
6209 state_num = CURLYM_B_fail;
6210 goto reenter_switch;
6215 /* emulate CLOSE: mark current A as captured */
6216 I32 paren = ST.me->flags;
6218 rex->offs[paren].start
6219 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
6220 rex->offs[paren].end = locinput - reginfo->strbeg;
6221 if ((U32)paren > rex->lastparen)
6222 rex->lastparen = paren;
6223 rex->lastcloseparen = paren;
6226 rex->offs[paren].end = -1;
6227 if (cur_eval && cur_eval->u.eval.close_paren &&
6228 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6237 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
6238 assert(0); /* NOTREACHED */
6240 case CURLYM_B_fail: /* just failed to match a B */
6241 REGCP_UNWIND(ST.cp);
6242 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6244 I32 max = ARG2(ST.me);
6245 if (max != REG_INFTY && ST.count == max)
6247 goto curlym_do_A; /* try to match a further A */
6249 /* backtrack one A */
6250 if (ST.count == ARG1(ST.me) /* min */)
6253 SET_locinput(HOPc(locinput, -ST.alen));
6254 goto curlym_do_B; /* try to match B */
6257 #define ST st->u.curly
6259 #define CURLY_SETPAREN(paren, success) \
6262 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
6263 rex->offs[paren].end = locinput - reginfo->strbeg; \
6264 if (paren > rex->lastparen) \
6265 rex->lastparen = paren; \
6266 rex->lastcloseparen = paren; \
6269 rex->offs[paren].end = -1; \
6270 rex->lastparen = ST.lastparen; \
6271 rex->lastcloseparen = ST.lastcloseparen; \
6275 case STAR: /* /A*B/ where A is width 1 char */
6279 scan = NEXTOPER(scan);
6282 case PLUS: /* /A+B/ where A is width 1 char */
6286 scan = NEXTOPER(scan);
6289 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
6290 ST.paren = scan->flags; /* Which paren to set */
6291 ST.lastparen = rex->lastparen;
6292 ST.lastcloseparen = rex->lastcloseparen;
6293 if (ST.paren > maxopenparen)
6294 maxopenparen = ST.paren;
6295 ST.min = ARG1(scan); /* min to match */
6296 ST.max = ARG2(scan); /* max to match */
6297 if (cur_eval && cur_eval->u.eval.close_paren &&
6298 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6302 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
6305 case CURLY: /* /A{m,n}B/ where A is width 1 char */
6307 ST.min = ARG1(scan); /* min to match */
6308 ST.max = ARG2(scan); /* max to match */
6309 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6312 * Lookahead to avoid useless match attempts
6313 * when we know what character comes next.
6315 * Used to only do .*x and .*?x, but now it allows
6316 * for )'s, ('s and (?{ ... })'s to be in the way
6317 * of the quantifier and the EXACT-like node. -- japhy
6320 assert(ST.min <= ST.max);
6321 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
6322 ST.c1 = ST.c2 = CHRTEST_VOID;
6325 regnode *text_node = next;
6327 if (! HAS_TEXT(text_node))
6328 FIND_NEXT_IMPT(text_node);
6330 if (! HAS_TEXT(text_node))
6331 ST.c1 = ST.c2 = CHRTEST_VOID;
6333 if ( PL_regkind[OP(text_node)] != EXACT ) {
6334 ST.c1 = ST.c2 = CHRTEST_VOID;
6338 /* Currently we only get here when
6340 PL_rekind[OP(text_node)] == EXACT
6342 if this changes back then the macro for IS_TEXT and
6343 friends need to change. */
6344 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6345 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6357 char *li = locinput;
6360 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
6366 if (ST.c1 == CHRTEST_VOID)
6367 goto curly_try_B_min;
6369 ST.oldloc = locinput;
6371 /* set ST.maxpos to the furthest point along the
6372 * string that could possibly match */
6373 if (ST.max == REG_INFTY) {
6374 ST.maxpos = reginfo->strend - 1;
6376 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
6379 else if (utf8_target) {
6380 int m = ST.max - ST.min;
6381 for (ST.maxpos = locinput;
6382 m >0 && ST.maxpos < reginfo->strend; m--)
6383 ST.maxpos += UTF8SKIP(ST.maxpos);
6386 ST.maxpos = locinput + ST.max - ST.min;
6387 if (ST.maxpos >= reginfo->strend)
6388 ST.maxpos = reginfo->strend - 1;
6390 goto curly_try_B_min_known;
6394 /* avoid taking address of locinput, so it can remain
6396 char *li = locinput;
6397 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
6398 if (ST.count < ST.min)
6401 if ((ST.count > ST.min)
6402 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
6404 /* A{m,n} must come at the end of the string, there's
6405 * no point in backing off ... */
6407 /* ...except that $ and \Z can match before *and* after
6408 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
6409 We may back off by one in this case. */
6410 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
6414 goto curly_try_B_max;
6416 assert(0); /* NOTREACHED */
6419 case CURLY_B_min_known_fail:
6420 /* failed to find B in a non-greedy match where c1,c2 valid */
6422 REGCP_UNWIND(ST.cp);
6424 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6426 /* Couldn't or didn't -- move forward. */
6427 ST.oldloc = locinput;
6429 locinput += UTF8SKIP(locinput);
6433 curly_try_B_min_known:
6434 /* find the next place where 'B' could work, then call B */
6438 n = (ST.oldloc == locinput) ? 0 : 1;
6439 if (ST.c1 == ST.c2) {
6440 /* set n to utf8_distance(oldloc, locinput) */
6441 while (locinput <= ST.maxpos
6442 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
6444 locinput += UTF8SKIP(locinput);
6449 /* set n to utf8_distance(oldloc, locinput) */
6450 while (locinput <= ST.maxpos
6451 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6452 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6454 locinput += UTF8SKIP(locinput);
6459 else { /* Not utf8_target */
6460 if (ST.c1 == ST.c2) {
6461 while (locinput <= ST.maxpos &&
6462 UCHARAT(locinput) != ST.c1)
6466 while (locinput <= ST.maxpos
6467 && UCHARAT(locinput) != ST.c1
6468 && UCHARAT(locinput) != ST.c2)
6471 n = locinput - ST.oldloc;
6473 if (locinput > ST.maxpos)
6476 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
6477 * at b; check that everything between oldloc and
6478 * locinput matches */
6479 char *li = ST.oldloc;
6481 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
6483 assert(n == REG_INFTY || locinput == li);
6485 CURLY_SETPAREN(ST.paren, ST.count);
6486 if (cur_eval && cur_eval->u.eval.close_paren &&
6487 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6490 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
6492 assert(0); /* NOTREACHED */
6495 case CURLY_B_min_fail:
6496 /* failed to find B in a non-greedy match where c1,c2 invalid */
6498 REGCP_UNWIND(ST.cp);
6500 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6502 /* failed -- move forward one */
6504 char *li = locinput;
6505 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
6512 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
6513 ST.count > 0)) /* count overflow ? */
6516 CURLY_SETPAREN(ST.paren, ST.count);
6517 if (cur_eval && cur_eval->u.eval.close_paren &&
6518 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6521 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
6525 assert(0); /* NOTREACHED */
6529 /* a successful greedy match: now try to match B */
6530 if (cur_eval && cur_eval->u.eval.close_paren &&
6531 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6535 bool could_match = locinput < reginfo->strend;
6537 /* If it could work, try it. */
6538 if (ST.c1 != CHRTEST_VOID && could_match) {
6539 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
6541 could_match = memEQ(locinput,
6546 UTF8SKIP(locinput));
6549 could_match = UCHARAT(locinput) == ST.c1
6550 || UCHARAT(locinput) == ST.c2;
6553 if (ST.c1 == CHRTEST_VOID || could_match) {
6554 CURLY_SETPAREN(ST.paren, ST.count);
6555 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
6556 assert(0); /* NOTREACHED */
6561 case CURLY_B_max_fail:
6562 /* failed to find B in a greedy match */
6564 REGCP_UNWIND(ST.cp);
6566 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6569 if (--ST.count < ST.min)
6571 locinput = HOPc(locinput, -1);
6572 goto curly_try_B_max;
6576 case END: /* last op of main pattern */
6579 /* we've just finished A in /(??{A})B/; now continue with B */
6581 st->u.eval.prev_rex = rex_sv; /* inner */
6583 /* Save *all* the positions. */
6584 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
6585 rex_sv = cur_eval->u.eval.prev_rex;
6586 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6587 SET_reg_curpm(rex_sv);
6588 rex = ReANY(rex_sv);
6589 rexi = RXi_GET(rex);
6590 cur_curlyx = cur_eval->u.eval.prev_curlyx;
6592 REGCP_SET(st->u.eval.lastcp);
6594 /* Restore parens of the outer rex without popping the
6596 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
6599 st->u.eval.prev_eval = cur_eval;
6600 cur_eval = cur_eval->u.eval.prev_eval;
6602 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
6603 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
6604 if ( nochange_depth )
6607 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
6608 locinput); /* match B */
6611 if (locinput < reginfo->till) {
6612 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6613 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
6615 (long)(locinput - startpos),
6616 (long)(reginfo->till - startpos),
6619 sayNO_SILENT; /* Cannot match: too short. */
6621 sayYES; /* Success! */
6623 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
6625 PerlIO_printf(Perl_debug_log,
6626 "%*s %ssubpattern success...%s\n",
6627 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
6628 sayYES; /* Success! */
6631 #define ST st->u.ifmatch
6636 case SUSPEND: /* (?>A) */
6638 newstart = locinput;
6641 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
6643 goto ifmatch_trivial_fail_test;
6645 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
6647 ifmatch_trivial_fail_test:
6649 char * const s = HOPBACKc(locinput, scan->flags);
6654 sw = 1 - cBOOL(ST.wanted);
6658 next = scan + ARG(scan);
6666 newstart = locinput;
6670 ST.logical = logical;
6671 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
6673 /* execute body of (?...A) */
6674 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
6675 assert(0); /* NOTREACHED */
6678 case IFMATCH_A_fail: /* body of (?...A) failed */
6679 ST.wanted = !ST.wanted;
6682 case IFMATCH_A: /* body of (?...A) succeeded */
6684 sw = cBOOL(ST.wanted);
6686 else if (!ST.wanted)
6689 if (OP(ST.me) != SUSPEND) {
6690 /* restore old position except for (?>...) */
6691 locinput = st->locinput;
6693 scan = ST.me + ARG(ST.me);
6696 continue; /* execute B */
6700 case LONGJMP: /* alternative with many branches compiles to
6701 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
6702 next = scan + ARG(scan);
6707 case COMMIT: /* (*COMMIT) */
6708 reginfo->cutpoint = reginfo->strend;
6711 case PRUNE: /* (*PRUNE) */
6713 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6714 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
6715 assert(0); /* NOTREACHED */
6717 case COMMIT_next_fail:
6721 case OPFAIL: /* (*FAIL) */
6723 assert(0); /* NOTREACHED */
6725 #define ST st->u.mark
6726 case MARKPOINT: /* (*MARK:foo) */
6727 ST.prev_mark = mark_state;
6728 ST.mark_name = sv_commit = sv_yes_mark
6729 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6731 ST.mark_loc = locinput;
6732 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
6733 assert(0); /* NOTREACHED */
6735 case MARKPOINT_next:
6736 mark_state = ST.prev_mark;
6738 assert(0); /* NOTREACHED */
6740 case MARKPOINT_next_fail:
6741 if (popmark && sv_eq(ST.mark_name,popmark))
6743 if (ST.mark_loc > startpoint)
6744 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6745 popmark = NULL; /* we found our mark */
6746 sv_commit = ST.mark_name;
6749 PerlIO_printf(Perl_debug_log,
6750 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
6751 REPORT_CODE_OFF+depth*2, "",
6752 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
6755 mark_state = ST.prev_mark;
6756 sv_yes_mark = mark_state ?
6757 mark_state->u.mark.mark_name : NULL;
6759 assert(0); /* NOTREACHED */
6761 case SKIP: /* (*SKIP) */
6763 /* (*SKIP) : if we fail we cut here*/
6764 ST.mark_name = NULL;
6765 ST.mark_loc = locinput;
6766 PUSH_STATE_GOTO(SKIP_next,next, locinput);
6768 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
6769 otherwise do nothing. Meaning we need to scan
6771 regmatch_state *cur = mark_state;
6772 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6775 if ( sv_eq( cur->u.mark.mark_name,
6778 ST.mark_name = find;
6779 PUSH_STATE_GOTO( SKIP_next, next, locinput);
6781 cur = cur->u.mark.prev_mark;
6784 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
6787 case SKIP_next_fail:
6789 /* (*CUT:NAME) - Set up to search for the name as we
6790 collapse the stack*/
6791 popmark = ST.mark_name;
6793 /* (*CUT) - No name, we cut here.*/
6794 if (ST.mark_loc > startpoint)
6795 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6796 /* but we set sv_commit to latest mark_name if there
6797 is one so they can test to see how things lead to this
6800 sv_commit=mark_state->u.mark.mark_name;
6804 assert(0); /* NOTREACHED */
6807 case LNBREAK: /* \R */
6808 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
6815 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
6816 PTR2UV(scan), OP(scan));
6817 Perl_croak(aTHX_ "regexp memory corruption");
6819 /* this is a point to jump to in order to increment
6820 * locinput by one character */
6822 assert(!NEXTCHR_IS_EOS);
6824 locinput += PL_utf8skip[nextchr];
6825 /* locinput is allowed to go 1 char off the end, but not 2+ */
6826 if (locinput > reginfo->strend)
6835 /* switch break jumps here */
6836 scan = next; /* prepare to execute the next op and ... */
6837 continue; /* ... jump back to the top, reusing st */
6838 assert(0); /* NOTREACHED */
6841 /* push a state that backtracks on success */
6842 st->u.yes.prev_yes_state = yes_state;
6846 /* push a new regex state, then continue at scan */
6848 regmatch_state *newst;
6851 regmatch_state *cur = st;
6852 regmatch_state *curyes = yes_state;
6854 regmatch_slab *slab = PL_regmatch_slab;
6855 for (;curd > -1;cur--,curd--) {
6856 if (cur < SLAB_FIRST(slab)) {
6858 cur = SLAB_LAST(slab);
6860 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
6861 REPORT_CODE_OFF + 2 + depth * 2,"",
6862 curd, PL_reg_name[cur->resume_state],
6863 (curyes == cur) ? "yes" : ""
6866 curyes = cur->u.yes.prev_yes_state;
6869 DEBUG_STATE_pp("push")
6872 st->locinput = locinput;
6874 if (newst > SLAB_LAST(PL_regmatch_slab))
6875 newst = S_push_slab(aTHX);
6876 PL_regmatch_state = newst;
6878 locinput = pushinput;
6881 assert(0); /* NOTREACHED */
6886 * We get here only if there's trouble -- normally "case END" is
6887 * the terminating point.
6889 Perl_croak(aTHX_ "corrupted regexp pointers");
6895 /* we have successfully completed a subexpression, but we must now
6896 * pop to the state marked by yes_state and continue from there */
6897 assert(st != yes_state);
6899 while (st != yes_state) {
6901 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6902 PL_regmatch_slab = PL_regmatch_slab->prev;
6903 st = SLAB_LAST(PL_regmatch_slab);
6907 DEBUG_STATE_pp("pop (no final)");
6909 DEBUG_STATE_pp("pop (yes)");
6915 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
6916 || yes_state > SLAB_LAST(PL_regmatch_slab))
6918 /* not in this slab, pop slab */
6919 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
6920 PL_regmatch_slab = PL_regmatch_slab->prev;
6921 st = SLAB_LAST(PL_regmatch_slab);
6923 depth -= (st - yes_state);
6926 yes_state = st->u.yes.prev_yes_state;
6927 PL_regmatch_state = st;
6930 locinput= st->locinput;
6931 state_num = st->resume_state + no_final;
6932 goto reenter_switch;
6935 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6936 PL_colors[4], PL_colors[5]));
6938 if (reginfo->info_aux_eval) {
6939 /* each successfully executed (?{...}) block does the equivalent of
6940 * local $^R = do {...}
6941 * When popping the save stack, all these locals would be undone;
6942 * bypass this by setting the outermost saved $^R to the latest
6944 /* I dont know if this is needed or works properly now.
6945 * see code related to PL_replgv elsewhere in this file.
6948 if (oreplsv != GvSV(PL_replgv))
6949 sv_setsv(oreplsv, GvSV(PL_replgv));
6956 PerlIO_printf(Perl_debug_log,
6957 "%*s %sfailed...%s\n",
6958 REPORT_CODE_OFF+depth*2, "",
6959 PL_colors[4], PL_colors[5])
6971 /* there's a previous state to backtrack to */
6973 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6974 PL_regmatch_slab = PL_regmatch_slab->prev;
6975 st = SLAB_LAST(PL_regmatch_slab);
6977 PL_regmatch_state = st;
6978 locinput= st->locinput;
6980 DEBUG_STATE_pp("pop");
6982 if (yes_state == st)
6983 yes_state = st->u.yes.prev_yes_state;
6985 state_num = st->resume_state + 1; /* failure = success + 1 */
6986 goto reenter_switch;
6991 if (rex->intflags & PREGf_VERBARG_SEEN) {
6992 SV *sv_err = get_sv("REGERROR", 1);
6993 SV *sv_mrk = get_sv("REGMARK", 1);
6995 sv_commit = &PL_sv_no;
6997 sv_yes_mark = &PL_sv_yes;
7000 sv_commit = &PL_sv_yes;
7001 sv_yes_mark = &PL_sv_no;
7005 sv_setsv(sv_err, sv_commit);
7006 sv_setsv(sv_mrk, sv_yes_mark);
7010 if (last_pushed_cv) {
7013 PERL_UNUSED_VAR(SP);
7016 assert(!result || locinput - reginfo->strbeg >= 0);
7017 return result ? locinput - reginfo->strbeg : -1;
7021 - regrepeat - repeatedly match something simple, report how many
7023 * What 'simple' means is a node which can be the operand of a quantifier like
7026 * startposp - pointer a pointer to the start position. This is updated
7027 * to point to the byte following the highest successful
7029 * p - the regnode to be repeatedly matched against.
7030 * reginfo - struct holding match state, such as strend
7031 * max - maximum number of things to match.
7032 * depth - (for debugging) backtracking depth.
7035 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
7036 regmatch_info *const reginfo, I32 max, int depth)
7039 char *scan; /* Pointer to current position in target string */
7041 char *loceol = reginfo->strend; /* local version */
7042 I32 hardcount = 0; /* How many matches so far */
7043 bool utf8_target = reginfo->is_utf8_target;
7044 int to_complement = 0; /* Invert the result? */
7046 _char_class_number classnum;
7048 PERL_UNUSED_ARG(depth);
7051 PERL_ARGS_ASSERT_REGREPEAT;
7054 if (max == REG_INFTY)
7056 else if (! utf8_target && loceol - scan > max)
7057 loceol = scan + max;
7059 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
7060 * to the maximum of how far we should go in it (leaving it set to the real
7061 * end, if the maximum permissible would take us beyond that). This allows
7062 * us to make the loop exit condition that we haven't gone past <loceol> to
7063 * also mean that we haven't exceeded the max permissible count, saving a
7064 * test each time through the loop. But it assumes that the OP matches a
7065 * single byte, which is true for most of the OPs below when applied to a
7066 * non-UTF-8 target. Those relatively few OPs that don't have this
7067 * characteristic will have to compensate.
7069 * There is no adjustment for UTF-8 targets, as the number of bytes per
7070 * character varies. OPs will have to test both that the count is less
7071 * than the max permissible (using <hardcount> to keep track), and that we
7072 * are still within the bounds of the string (using <loceol>. A few OPs
7073 * match a single byte no matter what the encoding. They can omit the max
7074 * test if, for the UTF-8 case, they do the adjustment that was skipped
7077 * Thus, the code above sets things up for the common case; and exceptional
7078 * cases need extra work; the common case is to make sure <scan> doesn't
7079 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
7080 * count doesn't exceed the maximum permissible */
7085 while (scan < loceol && hardcount < max && *scan != '\n') {
7086 scan += UTF8SKIP(scan);
7090 while (scan < loceol && *scan != '\n')
7096 while (scan < loceol && hardcount < max) {
7097 scan += UTF8SKIP(scan);
7104 case CANY: /* Move <scan> forward <max> bytes, unless goes off end */
7105 if (utf8_target && loceol - scan > max) {
7107 /* <loceol> hadn't been adjusted in the UTF-8 case */
7115 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7119 /* Can use a simple loop if the pattern char to match on is invariant
7120 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
7121 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
7122 * true iff it doesn't matter if the argument is in UTF-8 or not */
7123 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
7124 if (utf8_target && loceol - scan > max) {
7125 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
7126 * since here, to match at all, 1 char == 1 byte */
7127 loceol = scan + max;
7129 while (scan < loceol && UCHARAT(scan) == c) {
7133 else if (reginfo->is_utf8_pat) {
7135 STRLEN scan_char_len;
7137 /* When both target and pattern are UTF-8, we have to do
7139 while (hardcount < max
7141 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
7142 && memEQ(scan, STRING(p), scan_char_len))
7144 scan += scan_char_len;
7148 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
7150 /* Target isn't utf8; convert the character in the UTF-8
7151 * pattern to non-UTF8, and do a simple loop */
7152 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
7153 while (scan < loceol && UCHARAT(scan) == c) {
7156 } /* else pattern char is above Latin1, can't possibly match the
7161 /* Here, the string must be utf8; pattern isn't, and <c> is
7162 * different in utf8 than not, so can't compare them directly.
7163 * Outside the loop, find the two utf8 bytes that represent c, and
7164 * then look for those in sequence in the utf8 string */
7165 U8 high = UTF8_TWO_BYTE_HI(c);
7166 U8 low = UTF8_TWO_BYTE_LO(c);
7168 while (hardcount < max
7169 && scan + 1 < loceol
7170 && UCHARAT(scan) == high
7171 && UCHARAT(scan + 1) == low)
7179 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
7180 assert(! reginfo->is_utf8_pat);
7183 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7187 utf8_flags = FOLDEQ_LOCALE;
7190 case EXACTF: /* This node only generated for non-utf8 patterns */
7191 assert(! reginfo->is_utf8_pat);
7197 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
7201 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
7203 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7205 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
7208 if (c1 == CHRTEST_VOID) {
7209 /* Use full Unicode fold matching */
7210 char *tmpeol = reginfo->strend;
7211 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
7212 while (hardcount < max
7213 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
7214 STRING(p), NULL, pat_len,
7215 reginfo->is_utf8_pat, utf8_flags))
7218 tmpeol = reginfo->strend;
7222 else if (utf8_target) {
7224 while (scan < loceol
7226 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
7228 scan += UTF8SKIP(scan);
7233 while (scan < loceol
7235 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
7236 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
7238 scan += UTF8SKIP(scan);
7243 else if (c1 == c2) {
7244 while (scan < loceol && UCHARAT(scan) == c1) {
7249 while (scan < loceol &&
7250 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
7260 while (hardcount < max
7262 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
7264 scan += UTF8SKIP(scan);
7268 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
7273 /* The argument (FLAGS) to all the POSIX node types is the class number */
7280 if (! utf8_target) {
7281 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
7287 while (hardcount < max && scan < loceol
7288 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
7291 scan += UTF8SKIP(scan);
7304 if (utf8_target && loceol - scan > max) {
7306 /* We didn't adjust <loceol> at the beginning of this routine
7307 * because is UTF-8, but it is actually ok to do so, since here, to
7308 * match, 1 char == 1 byte. */
7309 loceol = scan + max;
7311 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
7324 if (! utf8_target) {
7325 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
7331 /* The complement of something that matches only ASCII matches all
7332 * non-ASCII, plus everything in ASCII that isn't in the class. */
7333 while (hardcount < max && scan < loceol
7334 && (! isASCII_utf8(scan)
7335 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
7337 scan += UTF8SKIP(scan);
7348 if (! utf8_target) {
7349 while (scan < loceol && to_complement
7350 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
7357 classnum = (_char_class_number) FLAGS(p);
7358 if (classnum < _FIRST_NON_SWASH_CC) {
7360 /* Here, a swash is needed for above-Latin1 code points.
7361 * Process as many Latin1 code points using the built-in rules.
7362 * Go to another loop to finish processing upon encountering
7363 * the first Latin1 code point. We could do that in this loop
7364 * as well, but the other way saves having to test if the swash
7365 * has been loaded every time through the loop: extra space to
7367 while (hardcount < max && scan < loceol) {
7368 if (UTF8_IS_INVARIANT(*scan)) {
7369 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
7376 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
7377 if (! (to_complement
7378 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
7387 goto found_above_latin1;
7394 /* For these character classes, the knowledge of how to handle
7395 * every code point is compiled in to Perl via a macro. This
7396 * code is written for making the loops as tight as possible.
7397 * It could be refactored to save space instead */
7399 case _CC_ENUM_SPACE: /* XXX would require separate code
7400 if we revert the change of \v
7403 case _CC_ENUM_PSXSPC:
7404 while (hardcount < max
7406 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
7408 scan += UTF8SKIP(scan);
7412 case _CC_ENUM_BLANK:
7413 while (hardcount < max
7415 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
7417 scan += UTF8SKIP(scan);
7421 case _CC_ENUM_XDIGIT:
7422 while (hardcount < max
7424 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
7426 scan += UTF8SKIP(scan);
7430 case _CC_ENUM_VERTSPACE:
7431 while (hardcount < max
7433 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
7435 scan += UTF8SKIP(scan);
7439 case _CC_ENUM_CNTRL:
7440 while (hardcount < max
7442 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
7444 scan += UTF8SKIP(scan);
7449 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
7455 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
7457 /* Load the swash if not already present */
7458 if (! PL_utf8_swash_ptrs[classnum]) {
7459 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7460 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
7464 PL_XPosix_ptrs[classnum], &flags);
7467 while (hardcount < max && scan < loceol
7468 && to_complement ^ cBOOL(_generic_utf8(
7471 swash_fetch(PL_utf8_swash_ptrs[classnum],
7475 scan += UTF8SKIP(scan);
7482 while (hardcount < max && scan < loceol &&
7483 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
7488 /* LNBREAK can match one or two latin chars, which is ok, but we
7489 * have to use hardcount in this situation, and throw away the
7490 * adjustment to <loceol> done before the switch statement */
7491 loceol = reginfo->strend;
7492 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
7513 /* These are all 0 width, so match right here or not at all. */
7517 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
7518 assert(0); /* NOTREACHED */
7525 c = scan - *startposp;
7529 GET_RE_DEBUG_FLAGS_DECL;
7531 SV * const prop = sv_newmortal();
7532 regprop(prog, prop, p, reginfo);
7533 PerlIO_printf(Perl_debug_log,
7534 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
7535 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
7543 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
7545 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
7546 create a copy so that changes the caller makes won't change the shared one.
7547 If <altsvp> is non-null, will return NULL in it, for back-compat.
7550 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
7552 PERL_ARGS_ASSERT_REGCLASS_SWASH;
7558 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL));
7562 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
7563 const regnode* node,
7566 SV** only_utf8_locale_ptr)
7568 /* For internal core use only.
7569 * Returns the swash for the input 'node' in the regex 'prog'.
7570 * If <doinit> is 'true', will attempt to create the swash if not already
7572 * If <listsvp> is non-null, will return the printable contents of the
7573 * swash. This can be used to get debugging information even before the
7574 * swash exists, by calling this function with 'doinit' set to false, in
7575 * which case the components that will be used to eventually create the
7576 * swash are returned (in a printable form).
7577 * Tied intimately to how regcomp.c sets up the data structure */
7581 SV *si = NULL; /* Input swash initialization string */
7584 RXi_GET_DECL(prog,progi);
7585 const struct reg_data * const data = prog ? progi->data : NULL;
7587 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
7589 assert(ANYOF_FLAGS(node)
7590 & (ANYOF_UTF8|ANYOF_NONBITMAP_NON_UTF8|ANYOF_LOC_FOLD));
7592 if (data && data->count) {
7593 const U32 n = ARG(node);
7595 if (data->what[n] == 's') {
7596 SV * const rv = MUTABLE_SV(data->data[n]);
7597 AV * const av = MUTABLE_AV(SvRV(rv));
7598 SV **const ary = AvARRAY(av);
7599 U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7601 si = *ary; /* ary[0] = the string to initialize the swash with */
7603 /* Elements 3 and 4 are either both present or both absent. [3] is
7604 * any inversion list generated at compile time; [4] indicates if
7605 * that inversion list has any user-defined properties in it. */
7606 if (av_tindex(av) >= 2) {
7607 if (only_utf8_locale_ptr
7609 && ary[2] != &PL_sv_undef)
7611 *only_utf8_locale_ptr = ary[2];
7614 assert(only_utf8_locale_ptr);
7615 *only_utf8_locale_ptr = NULL;
7618 if (av_tindex(av) >= 3) {
7621 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
7629 /* Element [1] is reserved for the set-up swash. If already there,
7630 * return it; if not, create it and store it there */
7631 if (ary[1] && SvROK(ary[1])) {
7634 else if (doinit && ((si && si != &PL_sv_undef)
7635 || (invlist && invlist != &PL_sv_undef))) {
7637 sw = _core_swash_init("utf8", /* the utf8 package */
7641 0, /* not from tr/// */
7644 (void)av_store(av, 1, sw);
7649 /* If requested, return a printable version of what this swash matches */
7651 SV* matches_string = newSVpvs("");
7653 /* The swash should be used, if possible, to get the data, as it
7654 * contains the resolved data. But this function can be called at
7655 * compile-time, before everything gets resolved, in which case we
7656 * return the currently best available information, which is the string
7657 * that will eventually be used to do that resolving, 'si' */
7658 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
7659 && (si && si != &PL_sv_undef))
7661 sv_catsv(matches_string, si);
7664 /* Add the inversion list to whatever we have. This may have come from
7665 * the swash, or from an input parameter */
7667 sv_catsv(matches_string, _invlist_contents(invlist));
7669 *listsvp = matches_string;
7674 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
7677 - reginclass - determine if a character falls into a character class
7679 n is the ANYOF regnode
7680 p is the target string
7681 p_end points to one byte beyond the end of the target string
7682 utf8_target tells whether p is in UTF-8.
7684 Returns true if matched; false otherwise.
7686 Note that this can be a synthetic start class, a combination of various
7687 nodes, so things you think might be mutually exclusive, such as locale,
7688 aren't. It can match both locale and non-locale
7693 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
7696 const char flags = ANYOF_FLAGS(n);
7700 PERL_ARGS_ASSERT_REGINCLASS;
7702 /* If c is not already the code point, get it. Note that
7703 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
7704 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
7706 c = utf8n_to_uvchr(p, p_end - p, &c_len,
7707 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
7708 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
7709 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
7710 * UTF8_ALLOW_FFFF */
7711 if (c_len == (STRLEN)-1)
7712 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
7715 /* If this character is potentially in the bitmap, check it */
7717 if (ANYOF_BITMAP_TEST(n, c))
7719 else if (flags & ANYOF_NON_UTF8_NON_ASCII_ALL
7725 else if (flags & ANYOF_LOCALE_FLAGS) {
7726 if (flags & ANYOF_LOC_FOLD) {
7727 if (ANYOF_BITMAP_TEST(n, PL_fold_locale[c])) {
7731 if (! match && ANYOF_POSIXL_TEST_ANY_SET(n)) {
7733 /* The data structure is arranged so bits 0, 2, 4, ... are set
7734 * if the class includes the Posix character class given by
7735 * bit/2; and 1, 3, 5, ... are set if the class includes the
7736 * complemented Posix class given by int(bit/2). So we loop
7737 * through the bits, each time changing whether we complement
7738 * the result or not. Suppose for the sake of illustration
7739 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
7740 * is set, it means there is a match for this ANYOF node if the
7741 * character is in the class given by the expression (0 / 2 = 0
7742 * = \w). If it is in that class, isFOO_lc() will return 1,
7743 * and since 'to_complement' is 0, the result will stay TRUE,
7744 * and we exit the loop. Suppose instead that bit 0 is 0, but
7745 * bit 1 is 1. That means there is a match if the character
7746 * matches \W. We won't bother to call isFOO_lc() on bit 0,
7747 * but will on bit 1. On the second iteration 'to_complement'
7748 * will be 1, so the exclusive or will reverse things, so we
7749 * are testing for \W. On the third iteration, 'to_complement'
7750 * will be 0, and we would be testing for \s; the fourth
7751 * iteration would test for \S, etc.
7753 * Note that this code assumes that all the classes are closed
7754 * under folding. For example, if a character matches \w, then
7755 * its fold does too; and vice versa. This should be true for
7756 * any well-behaved locale for all the currently defined Posix
7757 * classes, except for :lower: and :upper:, which are handled
7758 * by the pseudo-class :cased: which matches if either of the
7759 * other two does. To get rid of this assumption, an outer
7760 * loop could be used below to iterate over both the source
7761 * character, and its fold (if different) */
7764 int to_complement = 0;
7766 while (count < ANYOF_MAX) {
7767 if (ANYOF_POSIXL_TEST(n, count)
7768 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
7781 /* If the bitmap didn't (or couldn't) match, and something outside the
7782 * bitmap could match, try that. */
7784 if (c >= 256 && (flags & ANYOF_ABOVE_LATIN1_ALL)) {
7785 match = TRUE; /* Everything above 255 matches */
7787 else if ((flags & ANYOF_NONBITMAP_NON_UTF8)
7788 || (utf8_target && (flags & ANYOF_UTF8))
7789 || ((flags & ANYOF_LOC_FOLD)
7790 && IN_UTF8_CTYPE_LOCALE
7791 && ARG(n) != ANYOF_NONBITMAP_EMPTY))
7793 SV* only_utf8_locale = NULL;
7794 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
7801 } else { /* Convert to utf8 */
7802 utf8_p = utf8_buffer;
7803 append_utf8_from_native_byte(*p, &utf8_p);
7804 utf8_p = utf8_buffer;
7807 if (swash_fetch(sw, utf8_p, TRUE)) {
7811 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
7812 match = _invlist_contains_cp(only_utf8_locale, c);
7816 if (UNICODE_IS_SUPER(c)
7817 && (flags & ANYOF_WARN_SUPER)
7818 && ckWARN_d(WARN_NON_UNICODE))
7820 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7821 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
7825 #if ANYOF_INVERT != 1
7826 /* Depending on compiler optimization cBOOL takes time, so if don't have to
7828 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
7831 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
7832 return (flags & ANYOF_INVERT) ^ match;
7836 S_reghop3(U8 *s, SSize_t off, const U8* lim)
7838 /* return the position 'off' UTF-8 characters away from 's', forward if
7839 * 'off' >= 0, backwards if negative. But don't go outside of position
7840 * 'lim', which better be < s if off < 0 */
7844 PERL_ARGS_ASSERT_REGHOP3;
7847 while (off-- && s < lim) {
7848 /* XXX could check well-formedness here */
7853 while (off++ && s > lim) {
7855 if (UTF8_IS_CONTINUED(*s)) {
7856 while (s > lim && UTF8_IS_CONTINUATION(*s))
7859 /* XXX could check well-formedness here */
7866 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
7870 PERL_ARGS_ASSERT_REGHOP4;
7873 while (off-- && s < rlim) {
7874 /* XXX could check well-formedness here */
7879 while (off++ && s > llim) {
7881 if (UTF8_IS_CONTINUED(*s)) {
7882 while (s > llim && UTF8_IS_CONTINUATION(*s))
7885 /* XXX could check well-formedness here */
7891 /* like reghop3, but returns NULL on overrun, rather than returning last
7895 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
7899 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7902 while (off-- && s < lim) {
7903 /* XXX could check well-formedness here */
7910 while (off++ && s > lim) {
7912 if (UTF8_IS_CONTINUED(*s)) {
7913 while (s > lim && UTF8_IS_CONTINUATION(*s))
7916 /* XXX could check well-formedness here */
7925 /* when executing a regex that may have (?{}), extra stuff needs setting
7926 up that will be visible to the called code, even before the current
7927 match has finished. In particular:
7929 * $_ is localised to the SV currently being matched;
7930 * pos($_) is created if necessary, ready to be updated on each call-out
7932 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
7933 isn't set until the current pattern is successfully finished), so that
7934 $1 etc of the match-so-far can be seen;
7935 * save the old values of subbeg etc of the current regex, and set then
7936 to the current string (again, this is normally only done at the end
7941 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
7944 regexp *const rex = ReANY(reginfo->prog);
7945 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
7947 eval_state->rex = rex;
7950 /* Make $_ available to executed code. */
7951 if (reginfo->sv != DEFSV) {
7953 DEFSV_set(reginfo->sv);
7956 if (!(mg = mg_find_mglob(reginfo->sv))) {
7957 /* prepare for quick setting of pos */
7958 mg = sv_magicext_mglob(reginfo->sv);
7961 eval_state->pos_magic = mg;
7962 eval_state->pos = mg->mg_len;
7963 eval_state->pos_flags = mg->mg_flags;
7966 eval_state->pos_magic = NULL;
7968 if (!PL_reg_curpm) {
7969 /* PL_reg_curpm is a fake PMOP that we can attach the current
7970 * regex to and point PL_curpm at, so that $1 et al are visible
7971 * within a /(?{})/. It's just allocated once per interpreter the
7972 * first time its needed */
7973 Newxz(PL_reg_curpm, 1, PMOP);
7976 SV* const repointer = &PL_sv_undef;
7977 /* this regexp is also owned by the new PL_reg_curpm, which
7978 will try to free it. */
7979 av_push(PL_regex_padav, repointer);
7980 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
7981 PL_regex_pad = AvARRAY(PL_regex_padav);
7985 SET_reg_curpm(reginfo->prog);
7986 eval_state->curpm = PL_curpm;
7987 PL_curpm = PL_reg_curpm;
7988 if (RXp_MATCH_COPIED(rex)) {
7989 /* Here is a serious problem: we cannot rewrite subbeg,
7990 since it may be needed if this match fails. Thus
7991 $` inside (?{}) could fail... */
7992 eval_state->subbeg = rex->subbeg;
7993 eval_state->sublen = rex->sublen;
7994 eval_state->suboffset = rex->suboffset;
7995 eval_state->subcoffset = rex->subcoffset;
7997 eval_state->saved_copy = rex->saved_copy;
7999 RXp_MATCH_COPIED_off(rex);
8002 eval_state->subbeg = NULL;
8003 rex->subbeg = (char *)reginfo->strbeg;
8005 rex->subcoffset = 0;
8006 rex->sublen = reginfo->strend - reginfo->strbeg;
8010 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8013 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8016 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8017 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8020 Safefree(aux->poscache);
8024 /* undo the effects of S_setup_eval_state() */
8026 if (eval_state->subbeg) {
8027 regexp * const rex = eval_state->rex;
8028 rex->subbeg = eval_state->subbeg;
8029 rex->sublen = eval_state->sublen;
8030 rex->suboffset = eval_state->suboffset;
8031 rex->subcoffset = eval_state->subcoffset;
8033 rex->saved_copy = eval_state->saved_copy;
8035 RXp_MATCH_COPIED_on(rex);
8037 if (eval_state->pos_magic)
8039 eval_state->pos_magic->mg_len = eval_state->pos;
8040 eval_state->pos_magic->mg_flags =
8041 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8042 | (eval_state->pos_flags & MGf_BYTES);
8045 PL_curpm = eval_state->curpm;
8048 PL_regmatch_state = aux->old_regmatch_state;
8049 PL_regmatch_slab = aux->old_regmatch_slab;
8051 /* free all slabs above current one - this must be the last action
8052 * of this function, as aux and eval_state are allocated within
8053 * slabs and may be freed here */
8055 s = PL_regmatch_slab->next;
8057 PL_regmatch_slab->next = NULL;
8059 regmatch_slab * const osl = s;
8068 S_to_utf8_substr(pTHX_ regexp *prog)
8070 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8071 * on the converted value */
8075 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8078 if (prog->substrs->data[i].substr
8079 && !prog->substrs->data[i].utf8_substr) {
8080 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8081 prog->substrs->data[i].utf8_substr = sv;
8082 sv_utf8_upgrade(sv);
8083 if (SvVALID(prog->substrs->data[i].substr)) {
8084 if (SvTAIL(prog->substrs->data[i].substr)) {
8085 /* Trim the trailing \n that fbm_compile added last
8087 SvCUR_set(sv, SvCUR(sv) - 1);
8088 /* Whilst this makes the SV technically "invalid" (as its
8089 buffer is no longer followed by "\0") when fbm_compile()
8090 adds the "\n" back, a "\0" is restored. */
8091 fbm_compile(sv, FBMcf_TAIL);
8095 if (prog->substrs->data[i].substr == prog->check_substr)
8096 prog->check_utf8 = sv;
8102 S_to_byte_substr(pTHX_ regexp *prog)
8104 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8105 * on the converted value; returns FALSE if can't be converted. */
8110 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8113 if (prog->substrs->data[i].utf8_substr
8114 && !prog->substrs->data[i].substr) {
8115 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
8116 if (! sv_utf8_downgrade(sv, TRUE)) {
8119 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
8120 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
8121 /* Trim the trailing \n that fbm_compile added last
8123 SvCUR_set(sv, SvCUR(sv) - 1);
8124 fbm_compile(sv, FBMcf_TAIL);
8128 prog->substrs->data[i].substr = sv;
8129 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
8130 prog->check_substr = sv;
8139 * c-indentation-style: bsd
8141 * indent-tabs-mode: nil
8144 * ex: set ts=8 sts=4 sw=4 et: