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: %i",
304 paren_elems_to_push, maxopenparen, parenfloor, REGCP_PAREN_ELEMS);
306 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
307 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
308 " out of range (%lu-%ld)",
310 (unsigned long)maxopenparen,
313 SSGROW(total_elems + REGCP_FRAME_ELEMS);
316 if ((int)maxopenparen > (int)parenfloor)
317 PerlIO_printf(Perl_debug_log,
318 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
323 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
324 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
325 SSPUSHIV(rex->offs[p].end);
326 SSPUSHIV(rex->offs[p].start);
327 SSPUSHINT(rex->offs[p].start_tmp);
328 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
329 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
331 (IV)rex->offs[p].start,
332 (IV)rex->offs[p].start_tmp,
336 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
337 SSPUSHINT(maxopenparen);
338 SSPUSHINT(rex->lastparen);
339 SSPUSHINT(rex->lastcloseparen);
340 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
345 /* These are needed since we do not localize EVAL nodes: */
346 #define REGCP_SET(cp) \
348 PerlIO_printf(Perl_debug_log, \
349 " Setting an EVAL scope, savestack=%"IVdf"\n", \
350 (IV)PL_savestack_ix)); \
353 #define REGCP_UNWIND(cp) \
355 if (cp != PL_savestack_ix) \
356 PerlIO_printf(Perl_debug_log, \
357 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
358 (IV)(cp), (IV)PL_savestack_ix)); \
361 #define UNWIND_PAREN(lp, lcp) \
362 for (n = rex->lastparen; n > lp; n--) \
363 rex->offs[n].end = -1; \
364 rex->lastparen = n; \
365 rex->lastcloseparen = lcp;
369 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
374 GET_RE_DEBUG_FLAGS_DECL;
376 PERL_ARGS_ASSERT_REGCPPOP;
378 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
380 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
381 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
382 rex->lastcloseparen = SSPOPINT;
383 rex->lastparen = SSPOPINT;
384 *maxopenparen_p = SSPOPINT;
386 i -= REGCP_OTHER_ELEMS;
387 /* Now restore the parentheses context. */
389 if (i || rex->lastparen + 1 <= rex->nparens)
390 PerlIO_printf(Perl_debug_log,
391 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
396 paren = *maxopenparen_p;
397 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
399 rex->offs[paren].start_tmp = SSPOPINT;
400 rex->offs[paren].start = SSPOPIV;
402 if (paren <= rex->lastparen)
403 rex->offs[paren].end = tmps;
404 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
405 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
407 (IV)rex->offs[paren].start,
408 (IV)rex->offs[paren].start_tmp,
409 (IV)rex->offs[paren].end,
410 (paren > rex->lastparen ? "(skipped)" : ""));
415 /* It would seem that the similar code in regtry()
416 * already takes care of this, and in fact it is in
417 * a better location to since this code can #if 0-ed out
418 * but the code in regtry() is needed or otherwise tests
419 * requiring null fields (pat.t#187 and split.t#{13,14}
420 * (as of patchlevel 7877) will fail. Then again,
421 * this code seems to be necessary or otherwise
422 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
423 * --jhi updated by dapm */
424 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
425 if (i > *maxopenparen_p)
426 rex->offs[i].start = -1;
427 rex->offs[i].end = -1;
428 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
429 " \\%"UVuf": %s ..-1 undeffing\n",
431 (i > *maxopenparen_p) ? "-1" : " "
437 /* restore the parens and associated vars at savestack position ix,
438 * but without popping the stack */
441 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
443 I32 tmpix = PL_savestack_ix;
444 PL_savestack_ix = ix;
445 regcppop(rex, maxopenparen_p);
446 PL_savestack_ix = tmpix;
449 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
452 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
454 /* Returns a boolean as to whether or not 'character' is a member of the
455 * Posix character class given by 'classnum' that should be equivalent to a
456 * value in the typedef '_char_class_number'.
458 * Ideally this could be replaced by a just an array of function pointers
459 * to the C library functions that implement the macros this calls.
460 * However, to compile, the precise function signatures are required, and
461 * these may vary from platform to to platform. To avoid having to figure
462 * out what those all are on each platform, I (khw) am using this method,
463 * which adds an extra layer of function call overhead (unless the C
464 * optimizer strips it away). But we don't particularly care about
465 * performance with locales anyway. */
467 switch ((_char_class_number) classnum) {
468 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
469 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
470 case _CC_ENUM_ASCII: return isASCII_LC(character);
471 case _CC_ENUM_BLANK: return isBLANK_LC(character);
472 case _CC_ENUM_CASED: return isLOWER_LC(character)
473 || isUPPER_LC(character);
474 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
475 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
476 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
477 case _CC_ENUM_LOWER: return isLOWER_LC(character);
478 case _CC_ENUM_PRINT: return isPRINT_LC(character);
479 case _CC_ENUM_PSXSPC: return isPSXSPC_LC(character);
480 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
481 case _CC_ENUM_SPACE: return isSPACE_LC(character);
482 case _CC_ENUM_UPPER: return isUPPER_LC(character);
483 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
484 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
485 default: /* VERTSPACE should never occur in locales */
486 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
489 assert(0); /* NOTREACHED */
494 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
496 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
497 * 'character' is a member of the Posix character class given by 'classnum'
498 * that should be equivalent to a value in the typedef
499 * '_char_class_number'.
501 * This just calls isFOO_lc on the code point for the character if it is in
502 * the range 0-255. Outside that range, all characters avoid Unicode
503 * rules, ignoring any locale. So use the Unicode function if this class
504 * requires a swash, and use the Unicode macro otherwise. */
506 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
508 if (UTF8_IS_INVARIANT(*character)) {
509 return isFOO_lc(classnum, *character);
511 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
512 return isFOO_lc(classnum,
513 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
516 if (classnum < _FIRST_NON_SWASH_CC) {
518 /* Initialize the swash unless done already */
519 if (! PL_utf8_swash_ptrs[classnum]) {
520 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
521 PL_utf8_swash_ptrs[classnum] =
522 _core_swash_init("utf8",
525 PL_XPosix_ptrs[classnum], &flags);
528 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
530 TRUE /* is UTF */ ));
533 switch ((_char_class_number) classnum) {
535 case _CC_ENUM_PSXSPC: return is_XPERLSPACE_high(character);
537 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
538 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
539 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
540 default: return 0; /* Things like CNTRL are always
544 assert(0); /* NOTREACHED */
549 * pregexec and friends
552 #ifndef PERL_IN_XSUB_RE
554 - pregexec - match a regexp against a string
557 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
558 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
559 /* stringarg: the point in the string at which to begin matching */
560 /* strend: pointer to null at end of string */
561 /* strbeg: real beginning of string */
562 /* minend: end of match must be >= minend bytes after stringarg. */
563 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
564 * itself is accessed via the pointers above */
565 /* nosave: For optimizations. */
567 PERL_ARGS_ASSERT_PREGEXEC;
570 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
571 nosave ? 0 : REXEC_COPY_STR);
577 /* re_intuit_start():
579 * Based on some optimiser hints, try to find the earliest position in the
580 * string where the regex could match.
582 * rx: the regex to match against
583 * sv: the SV being matched: only used for utf8 flag; the string
584 * itself is accessed via the pointers below. Note that on
585 * something like an overloaded SV, SvPOK(sv) may be false
586 * and the string pointers may point to something unrelated to
588 * strbeg: real beginning of string
589 * strpos: the point in the string at which to begin matching
590 * strend: pointer to the byte following the last char of the string
591 * flags currently unused; set to 0
592 * data: currently unused; set to NULL
594 * The basic idea of re_intuit_start() is to use some known information
595 * about the pattern, namely:
597 * a) the longest known anchored substring (i.e. one that's at a
598 * constant offset from the beginning of the pattern; but not
599 * necessarily at a fixed offset from the beginning of the
601 * b) the longest floating substring (i.e. one that's not at a constant
602 * offset from the beginning of the pattern);
603 * c) Whether the pattern is anchored to the string; either
604 * an absolute anchor: /^../, or anchored to \n: /^.../m,
605 * or anchored to pos(): /\G/;
606 * d) A start class: a real or synthetic character class which
607 * represents which characters are legal at the start of the pattern;
609 * to either quickly reject the match, or to find the earliest position
610 * within the string at which the pattern might match, thus avoiding
611 * running the full NFA engine at those earlier locations, only to
612 * eventually fail and retry further along.
614 * Returns NULL if the pattern can't match, or returns the address within
615 * the string which is the earliest place the match could occur.
617 * The longest of the anchored and floating substrings is called 'check'
618 * and is checked first. The other is called 'other' and is checked
619 * second. The 'other' substring may not be present. For example,
621 * /(abc|xyz)ABC\d{0,3}DEFG/
625 * check substr (float) = "DEFG", offset 6..9 chars
626 * other substr (anchored) = "ABC", offset 3..3 chars
629 * Be aware that during the course of this function, sometimes 'anchored'
630 * refers to a substring being anchored relative to the start of the
631 * pattern, and sometimes to the pattern itself being anchored relative to
632 * the string. For example:
634 * /\dabc/: "abc" is anchored to the pattern;
635 * /^\dabc/: "abc" is anchored to the pattern and the string;
636 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
637 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
638 * but the pattern is anchored to the string.
642 Perl_re_intuit_start(pTHX_
645 const char * const strbeg,
649 re_scream_pos_data *data)
652 struct regexp *const prog = ReANY(rx);
653 SSize_t start_shift = prog->check_offset_min;
654 /* Should be nonnegative! */
655 SSize_t end_shift = 0;
656 /* current lowest pos in string where the regex can start matching */
657 char *rx_origin = strpos;
659 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
660 U8 other_ix = 1 - prog->substrs->check_ix;
662 char *other_last = strpos;/* latest pos 'other' substr already checked to */
663 char *check_at = NULL; /* check substr found at this pos */
664 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
665 RXi_GET_DECL(prog,progi);
666 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
667 regmatch_info *const reginfo = ®info_buf;
668 GET_RE_DEBUG_FLAGS_DECL;
670 PERL_ARGS_ASSERT_RE_INTUIT_START;
671 PERL_UNUSED_ARG(flags);
672 PERL_UNUSED_ARG(data);
674 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
675 "Intuit: trying to determine minimum start position...\n"));
677 /* for now, assume that all substr offsets are positive. If at some point
678 * in the future someone wants to do clever things with look-behind and
679 * -ve offsets, they'll need to fix up any code in this function
680 * which uses these offsets. See the thread beginning
681 * <20140113145929.GF27210@iabyn.com>
683 assert(prog->substrs->data[0].min_offset >= 0);
684 assert(prog->substrs->data[0].max_offset >= 0);
685 assert(prog->substrs->data[1].min_offset >= 0);
686 assert(prog->substrs->data[1].max_offset >= 0);
687 assert(prog->substrs->data[2].min_offset >= 0);
688 assert(prog->substrs->data[2].max_offset >= 0);
690 /* for now, assume that if both present, that the floating substring
691 * doesn't start before the anchored substring.
692 * If you break this assumption (e.g. doing better optimisations
693 * with lookahead/behind), then you'll need to audit the code in this
694 * function carefully first
697 ! ( (prog->anchored_utf8 || prog->anchored_substr)
698 && (prog->float_utf8 || prog->float_substr))
699 || (prog->float_min_offset >= prog->anchored_offset));
701 /* byte rather than char calculation for efficiency. It fails
702 * to quickly reject some cases that can't match, but will reject
703 * them later after doing full char arithmetic */
704 if (prog->minlen > strend - strpos) {
705 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
706 " String too short...\n"));
710 RX_MATCH_UTF8_set(rx,utf8_target);
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; \
1455 /* FALL THROUGH */ \
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; \
1472 /* FALL THROUGH */ \
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 * UTF-8 variant code points, plus everything in ASCII that isn't
1922 REXEC_FBC_UTF8_CLASS_SCAN(! UTF8_IS_INVARIANT(*s)
1923 || ! _generic_isCC_A(*s, FLAGS(c)));
1932 /* Don't need to worry about utf8, as it can match only a single
1933 * byte invariant character. */
1934 REXEC_FBC_CLASS_SCAN(
1935 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
1943 if (! utf8_target) {
1944 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
1950 classnum = (_char_class_number) FLAGS(c);
1951 if (classnum < _FIRST_NON_SWASH_CC) {
1952 while (s < strend) {
1954 /* We avoid loading in the swash as long as possible, but
1955 * should we have to, we jump to a separate loop. This
1956 * extra 'if' statement is what keeps this code from being
1957 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
1958 if (UTF8_IS_ABOVE_LATIN1(*s)) {
1959 goto found_above_latin1;
1961 if ((UTF8_IS_INVARIANT(*s)
1962 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
1964 || (UTF8_IS_DOWNGRADEABLE_START(*s)
1965 && to_complement ^ cBOOL(
1966 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
1970 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
1982 else switch (classnum) { /* These classes are implemented as
1984 case _CC_ENUM_SPACE: /* XXX would require separate code if we
1985 revert the change of \v matching this */
1988 case _CC_ENUM_PSXSPC:
1989 REXEC_FBC_UTF8_CLASS_SCAN(
1990 to_complement ^ cBOOL(isSPACE_utf8(s)));
1993 case _CC_ENUM_BLANK:
1994 REXEC_FBC_UTF8_CLASS_SCAN(
1995 to_complement ^ cBOOL(isBLANK_utf8(s)));
1998 case _CC_ENUM_XDIGIT:
1999 REXEC_FBC_UTF8_CLASS_SCAN(
2000 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2003 case _CC_ENUM_VERTSPACE:
2004 REXEC_FBC_UTF8_CLASS_SCAN(
2005 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2008 case _CC_ENUM_CNTRL:
2009 REXEC_FBC_UTF8_CLASS_SCAN(
2010 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2014 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2015 assert(0); /* NOTREACHED */
2020 found_above_latin1: /* Here we have to load a swash to get the result
2021 for the current code point */
2022 if (! PL_utf8_swash_ptrs[classnum]) {
2023 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2024 PL_utf8_swash_ptrs[classnum] =
2025 _core_swash_init("utf8",
2028 PL_XPosix_ptrs[classnum], &flags);
2031 /* This is a copy of the loop above for swash classes, though using the
2032 * FBC macro instead of being expanded out. Since we've loaded the
2033 * swash, we don't have to check for that each time through the loop */
2034 REXEC_FBC_UTF8_CLASS_SCAN(
2035 to_complement ^ cBOOL(_generic_utf8(
2038 swash_fetch(PL_utf8_swash_ptrs[classnum],
2046 /* what trie are we using right now */
2047 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2048 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2049 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2051 const char *last_start = strend - trie->minlen;
2053 const char *real_start = s;
2055 STRLEN maxlen = trie->maxlen;
2057 U8 **points; /* map of where we were in the input string
2058 when reading a given char. For ASCII this
2059 is unnecessary overhead as the relationship
2060 is always 1:1, but for Unicode, especially
2061 case folded Unicode this is not true. */
2062 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2066 GET_RE_DEBUG_FLAGS_DECL;
2068 /* We can't just allocate points here. We need to wrap it in
2069 * an SV so it gets freed properly if there is a croak while
2070 * running the match */
2073 sv_points=newSV(maxlen * sizeof(U8 *));
2074 SvCUR_set(sv_points,
2075 maxlen * sizeof(U8 *));
2076 SvPOK_on(sv_points);
2077 sv_2mortal(sv_points);
2078 points=(U8**)SvPV_nolen(sv_points );
2079 if ( trie_type != trie_utf8_fold
2080 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2083 bitmap=(U8*)trie->bitmap;
2085 bitmap=(U8*)ANYOF_BITMAP(c);
2087 /* this is the Aho-Corasick algorithm modified a touch
2088 to include special handling for long "unknown char" sequences.
2089 The basic idea being that we use AC as long as we are dealing
2090 with a possible matching char, when we encounter an unknown char
2091 (and we have not encountered an accepting state) we scan forward
2092 until we find a legal starting char.
2093 AC matching is basically that of trie matching, except that when
2094 we encounter a failing transition, we fall back to the current
2095 states "fail state", and try the current char again, a process
2096 we repeat until we reach the root state, state 1, or a legal
2097 transition. If we fail on the root state then we can either
2098 terminate if we have reached an accepting state previously, or
2099 restart the entire process from the beginning if we have not.
2102 while (s <= last_start) {
2103 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2111 U8 *uscan = (U8*)NULL;
2112 U8 *leftmost = NULL;
2114 U32 accepted_word= 0;
2118 while ( state && uc <= (U8*)strend ) {
2120 U32 word = aho->states[ state ].wordnum;
2124 DEBUG_TRIE_EXECUTE_r(
2125 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2126 dump_exec_pos( (char *)uc, c, strend, real_start,
2127 (char *)uc, utf8_target );
2128 PerlIO_printf( Perl_debug_log,
2129 " Scanning for legal start char...\n");
2133 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2137 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2143 if (uc >(U8*)last_start) break;
2147 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2148 if (!leftmost || lpos < leftmost) {
2149 DEBUG_r(accepted_word=word);
2155 points[pointpos++ % maxlen]= uc;
2156 if (foldlen || uc < (U8*)strend) {
2157 REXEC_TRIE_READ_CHAR(trie_type, trie,
2159 uscan, len, uvc, charid, foldlen,
2161 DEBUG_TRIE_EXECUTE_r({
2162 dump_exec_pos( (char *)uc, c, strend,
2163 real_start, s, utf8_target);
2164 PerlIO_printf(Perl_debug_log,
2165 " Charid:%3u CP:%4"UVxf" ",
2177 word = aho->states[ state ].wordnum;
2179 base = aho->states[ state ].trans.base;
2181 DEBUG_TRIE_EXECUTE_r({
2183 dump_exec_pos( (char *)uc, c, strend, real_start,
2185 PerlIO_printf( Perl_debug_log,
2186 "%sState: %4"UVxf", word=%"UVxf,
2187 failed ? " Fail transition to " : "",
2188 (UV)state, (UV)word);
2194 ( ((offset = base + charid
2195 - 1 - trie->uniquecharcount)) >= 0)
2196 && ((U32)offset < trie->lasttrans)
2197 && trie->trans[offset].check == state
2198 && (tmp=trie->trans[offset].next))
2200 DEBUG_TRIE_EXECUTE_r(
2201 PerlIO_printf( Perl_debug_log," - legal\n"));
2206 DEBUG_TRIE_EXECUTE_r(
2207 PerlIO_printf( Perl_debug_log," - fail\n"));
2209 state = aho->fail[state];
2213 /* we must be accepting here */
2214 DEBUG_TRIE_EXECUTE_r(
2215 PerlIO_printf( Perl_debug_log," - accepting\n"));
2224 if (!state) state = 1;
2227 if ( aho->states[ state ].wordnum ) {
2228 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2229 if (!leftmost || lpos < leftmost) {
2230 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2235 s = (char*)leftmost;
2236 DEBUG_TRIE_EXECUTE_r({
2238 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2239 (UV)accepted_word, (IV)(s - real_start)
2242 if (reginfo->intuit || regtry(reginfo, &s)) {
2248 DEBUG_TRIE_EXECUTE_r({
2249 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2252 DEBUG_TRIE_EXECUTE_r(
2253 PerlIO_printf( Perl_debug_log,"No match.\n"));
2262 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2270 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2271 * flags have same meanings as with regexec_flags() */
2274 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2281 struct regexp *const prog = ReANY(rx);
2283 if (flags & REXEC_COPY_STR) {
2287 PerlIO_printf(Perl_debug_log,
2288 "Copy on write: regexp capture, type %d\n",
2291 /* Create a new COW SV to share the match string and store
2292 * in saved_copy, unless the current COW SV in saved_copy
2293 * is valid and suitable for our purpose */
2294 if (( prog->saved_copy
2295 && SvIsCOW(prog->saved_copy)
2296 && SvPOKp(prog->saved_copy)
2299 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2301 /* just reuse saved_copy SV */
2302 if (RXp_MATCH_COPIED(prog)) {
2303 Safefree(prog->subbeg);
2304 RXp_MATCH_COPIED_off(prog);
2308 /* create new COW SV to share string */
2309 RX_MATCH_COPY_FREE(rx);
2310 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2312 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2313 assert (SvPOKp(prog->saved_copy));
2314 prog->sublen = strend - strbeg;
2315 prog->suboffset = 0;
2316 prog->subcoffset = 0;
2321 SSize_t max = strend - strbeg;
2324 if ( (flags & REXEC_COPY_SKIP_POST)
2325 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2326 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2327 ) { /* don't copy $' part of string */
2330 /* calculate the right-most part of the string covered
2331 * by a capture. Due to look-ahead, this may be to
2332 * the right of $&, so we have to scan all captures */
2333 while (n <= prog->lastparen) {
2334 if (prog->offs[n].end > max)
2335 max = prog->offs[n].end;
2339 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2340 ? prog->offs[0].start
2342 assert(max >= 0 && max <= strend - strbeg);
2345 if ( (flags & REXEC_COPY_SKIP_PRE)
2346 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2347 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2348 ) { /* don't copy $` part of string */
2351 /* calculate the left-most part of the string covered
2352 * by a capture. Due to look-behind, this may be to
2353 * the left of $&, so we have to scan all captures */
2354 while (min && n <= prog->lastparen) {
2355 if ( prog->offs[n].start != -1
2356 && prog->offs[n].start < min)
2358 min = prog->offs[n].start;
2362 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2363 && min > prog->offs[0].end
2365 min = prog->offs[0].end;
2369 assert(min >= 0 && min <= max && min <= strend - strbeg);
2372 if (RX_MATCH_COPIED(rx)) {
2373 if (sublen > prog->sublen)
2375 (char*)saferealloc(prog->subbeg, sublen+1);
2378 prog->subbeg = (char*)safemalloc(sublen+1);
2379 Copy(strbeg + min, prog->subbeg, sublen, char);
2380 prog->subbeg[sublen] = '\0';
2381 prog->suboffset = min;
2382 prog->sublen = sublen;
2383 RX_MATCH_COPIED_on(rx);
2385 prog->subcoffset = prog->suboffset;
2386 if (prog->suboffset && utf8_target) {
2387 /* Convert byte offset to chars.
2388 * XXX ideally should only compute this if @-/@+
2389 * has been seen, a la PL_sawampersand ??? */
2391 /* If there's a direct correspondence between the
2392 * string which we're matching and the original SV,
2393 * then we can use the utf8 len cache associated with
2394 * the SV. In particular, it means that under //g,
2395 * sv_pos_b2u() will use the previously cached
2396 * position to speed up working out the new length of
2397 * subcoffset, rather than counting from the start of
2398 * the string each time. This stops
2399 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2400 * from going quadratic */
2401 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2402 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2403 SV_GMAGIC|SV_CONST_RETURN);
2405 prog->subcoffset = utf8_length((U8*)strbeg,
2406 (U8*)(strbeg+prog->suboffset));
2410 RX_MATCH_COPY_FREE(rx);
2411 prog->subbeg = strbeg;
2412 prog->suboffset = 0;
2413 prog->subcoffset = 0;
2414 prog->sublen = strend - strbeg;
2422 - regexec_flags - match a regexp against a string
2425 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2426 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2427 /* stringarg: the point in the string at which to begin matching */
2428 /* strend: pointer to null at end of string */
2429 /* strbeg: real beginning of string */
2430 /* minend: end of match must be >= minend bytes after stringarg. */
2431 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2432 * itself is accessed via the pointers above */
2433 /* data: May be used for some additional optimizations.
2434 Currently unused. */
2435 /* flags: For optimizations. See REXEC_* in regexp.h */
2439 struct regexp *const prog = ReANY(rx);
2443 SSize_t minlen; /* must match at least this many chars */
2444 SSize_t dontbother = 0; /* how many characters not to try at end */
2445 const bool utf8_target = cBOOL(DO_UTF8(sv));
2447 RXi_GET_DECL(prog,progi);
2448 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2449 regmatch_info *const reginfo = ®info_buf;
2450 regexp_paren_pair *swap = NULL;
2452 GET_RE_DEBUG_FLAGS_DECL;
2454 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2455 PERL_UNUSED_ARG(data);
2457 /* Be paranoid... */
2458 if (prog == NULL || stringarg == NULL) {
2459 Perl_croak(aTHX_ "NULL regexp parameter");
2464 debug_start_match(rx, utf8_target, stringarg, strend,
2468 startpos = stringarg;
2470 if (prog->intflags & PREGf_GPOS_SEEN) {
2473 /* set reginfo->ganch, the position where \G can match */
2476 (flags & REXEC_IGNOREPOS)
2477 ? stringarg /* use start pos rather than pos() */
2478 : (sv && (mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2479 /* Defined pos(): */
2480 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2481 : strbeg; /* pos() not defined; use start of string */
2483 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2484 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2486 /* in the presence of \G, we may need to start looking earlier in
2487 * the string than the suggested start point of stringarg:
2488 * if prog->gofs is set, then that's a known, fixed minimum
2491 * /ab|c\G/: gofs = 1
2492 * or if the minimum offset isn't known, then we have to go back
2493 * to the start of the string, e.g. /w+\G/
2496 if (prog->intflags & PREGf_ANCH_GPOS) {
2497 startpos = reginfo->ganch - prog->gofs;
2499 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2501 DEBUG_r(PerlIO_printf(Perl_debug_log,
2502 "fail: ganch-gofs before earliest possible start\n"));
2506 else if (prog->gofs) {
2507 if (startpos - prog->gofs < strbeg)
2510 startpos -= prog->gofs;
2512 else if (prog->intflags & PREGf_GPOS_FLOAT)
2516 minlen = prog->minlen;
2517 if ((startpos + minlen) > strend || startpos < strbeg) {
2518 DEBUG_r(PerlIO_printf(Perl_debug_log,
2519 "Regex match can't succeed, so not even tried\n"));
2523 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2524 * which will call destuctors to reset PL_regmatch_state, free higher
2525 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2526 * regmatch_info_aux_eval */
2528 oldsave = PL_savestack_ix;
2532 if ((prog->extflags & RXf_USE_INTUIT)
2533 && !(flags & REXEC_CHECKED))
2535 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2540 if (prog->extflags & RXf_CHECK_ALL) {
2541 /* we can match based purely on the result of INTUIT.
2542 * Set up captures etc just for $& and $-[0]
2543 * (an intuit-only match wont have $1,$2,..) */
2544 assert(!prog->nparens);
2546 /* s/// doesn't like it if $& is earlier than where we asked it to
2547 * start searching (which can happen on something like /.\G/) */
2548 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2551 /* this should only be possible under \G */
2552 assert(prog->intflags & PREGf_GPOS_SEEN);
2553 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2554 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2558 /* match via INTUIT shouldn't have any captures.
2559 * Let @-, @+, $^N know */
2560 prog->lastparen = prog->lastcloseparen = 0;
2561 RX_MATCH_UTF8_set(rx, utf8_target);
2562 prog->offs[0].start = s - strbeg;
2563 prog->offs[0].end = utf8_target
2564 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2565 : s - strbeg + prog->minlenret;
2566 if ( !(flags & REXEC_NOT_FIRST) )
2567 S_reg_set_capture_string(aTHX_ rx,
2569 sv, flags, utf8_target);
2575 multiline = prog->extflags & RXf_PMf_MULTILINE;
2577 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2578 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2579 "String too short [regexec_flags]...\n"));
2583 /* Check validity of program. */
2584 if (UCHARAT(progi->program) != REG_MAGIC) {
2585 Perl_croak(aTHX_ "corrupted regexp program");
2588 RX_MATCH_TAINTED_off(rx);
2589 RX_MATCH_UTF8_set(rx, utf8_target);
2591 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2592 reginfo->intuit = 0;
2593 reginfo->is_utf8_target = cBOOL(utf8_target);
2594 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2595 reginfo->warned = FALSE;
2596 reginfo->strbeg = strbeg;
2598 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2599 reginfo->strend = strend;
2600 /* see how far we have to get to not match where we matched before */
2601 reginfo->till = stringarg + minend;
2603 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2604 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2605 S_cleanup_regmatch_info_aux has executed (registered by
2606 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2607 magic belonging to this SV.
2608 Not newSVsv, either, as it does not COW.
2610 assert(!IS_PADGV(sv));
2611 reginfo->sv = newSV(0);
2612 SvSetSV_nosteal(reginfo->sv, sv);
2613 SAVEFREESV(reginfo->sv);
2616 /* reserve next 2 or 3 slots in PL_regmatch_state:
2617 * slot N+0: may currently be in use: skip it
2618 * slot N+1: use for regmatch_info_aux struct
2619 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2620 * slot N+3: ready for use by regmatch()
2624 regmatch_state *old_regmatch_state;
2625 regmatch_slab *old_regmatch_slab;
2626 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2628 /* on first ever match, allocate first slab */
2629 if (!PL_regmatch_slab) {
2630 Newx(PL_regmatch_slab, 1, regmatch_slab);
2631 PL_regmatch_slab->prev = NULL;
2632 PL_regmatch_slab->next = NULL;
2633 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2636 old_regmatch_state = PL_regmatch_state;
2637 old_regmatch_slab = PL_regmatch_slab;
2639 for (i=0; i <= max; i++) {
2641 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2643 reginfo->info_aux_eval =
2644 reginfo->info_aux->info_aux_eval =
2645 &(PL_regmatch_state->u.info_aux_eval);
2647 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2648 PL_regmatch_state = S_push_slab(aTHX);
2651 /* note initial PL_regmatch_state position; at end of match we'll
2652 * pop back to there and free any higher slabs */
2654 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
2655 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
2656 reginfo->info_aux->poscache = NULL;
2658 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
2660 if ((prog->extflags & RXf_EVAL_SEEN))
2661 S_setup_eval_state(aTHX_ reginfo);
2663 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
2666 /* If there is a "must appear" string, look for it. */
2668 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2669 /* We have to be careful. If the previous successful match
2670 was from this regex we don't want a subsequent partially
2671 successful match to clobber the old results.
2672 So when we detect this possibility we add a swap buffer
2673 to the re, and switch the buffer each match. If we fail,
2674 we switch it back; otherwise we leave it swapped.
2677 /* do we need a save destructor here for eval dies? */
2678 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2679 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2680 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2687 /* Simplest case: anchored match need be tried only once. */
2688 /* [unless only anchor is BOL and multiline is set] */
2689 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
2690 if (s == startpos && regtry(reginfo, &s))
2692 else if (multiline || (prog->intflags & (PREGf_IMPLICIT | PREGf_ANCH_MBOL))) /* XXXX SBOL? */
2697 dontbother = minlen - 1;
2698 end = HOP3c(strend, -dontbother, strbeg) - 1;
2699 /* for multiline we only have to try after newlines */
2700 if (prog->check_substr || prog->check_utf8) {
2701 /* because of the goto we can not easily reuse the macros for bifurcating the
2702 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2705 goto after_try_utf8;
2707 if (regtry(reginfo, &s)) {
2714 if (prog->extflags & RXf_USE_INTUIT) {
2715 s = re_intuit_start(rx, sv, strbeg,
2716 s + UTF8SKIP(s), strend, flags, NULL);
2725 } /* end search for check string in unicode */
2727 if (s == startpos) {
2728 goto after_try_latin;
2731 if (regtry(reginfo, &s)) {
2738 if (prog->extflags & RXf_USE_INTUIT) {
2739 s = re_intuit_start(rx, sv, strbeg,
2740 s + 1, strend, flags, NULL);
2749 } /* end search for check string in latin*/
2750 } /* end search for check string */
2751 else { /* search for newline */
2753 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2756 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2757 while (s <= end) { /* note it could be possible to match at the end of the string */
2758 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2759 if (regtry(reginfo, &s))
2763 } /* end search for newline */
2764 } /* end anchored/multiline check string search */
2766 } else if (prog->intflags & PREGf_ANCH_GPOS)
2768 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
2769 assert(prog->intflags & PREGf_GPOS_SEEN);
2770 /* For anchored \G, the only position it can match from is
2771 * (ganch-gofs); we already set startpos to this above; if intuit
2772 * moved us on from there, we can't possibly succeed */
2773 assert(startpos == reginfo->ganch - prog->gofs);
2774 if (s == startpos && regtry(reginfo, &s))
2779 /* Messy cases: unanchored match. */
2780 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2781 /* we have /x+whatever/ */
2782 /* it must be a one character string (XXXX Except is_utf8_pat?) */
2788 if (! prog->anchored_utf8) {
2789 to_utf8_substr(prog);
2791 ch = SvPVX_const(prog->anchored_utf8)[0];
2794 DEBUG_EXECUTE_r( did_match = 1 );
2795 if (regtry(reginfo, &s)) goto got_it;
2797 while (s < strend && *s == ch)
2804 if (! prog->anchored_substr) {
2805 if (! to_byte_substr(prog)) {
2806 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2809 ch = SvPVX_const(prog->anchored_substr)[0];
2812 DEBUG_EXECUTE_r( did_match = 1 );
2813 if (regtry(reginfo, &s)) goto got_it;
2815 while (s < strend && *s == ch)
2820 DEBUG_EXECUTE_r(if (!did_match)
2821 PerlIO_printf(Perl_debug_log,
2822 "Did not find anchored character...\n")
2825 else if (prog->anchored_substr != NULL
2826 || prog->anchored_utf8 != NULL
2827 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2828 && prog->float_max_offset < strend - s)) {
2833 char *last1; /* Last position checked before */
2837 if (prog->anchored_substr || prog->anchored_utf8) {
2839 if (! prog->anchored_utf8) {
2840 to_utf8_substr(prog);
2842 must = prog->anchored_utf8;
2845 if (! prog->anchored_substr) {
2846 if (! to_byte_substr(prog)) {
2847 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2850 must = prog->anchored_substr;
2852 back_max = back_min = prog->anchored_offset;
2855 if (! prog->float_utf8) {
2856 to_utf8_substr(prog);
2858 must = prog->float_utf8;
2861 if (! prog->float_substr) {
2862 if (! to_byte_substr(prog)) {
2863 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2866 must = prog->float_substr;
2868 back_max = prog->float_max_offset;
2869 back_min = prog->float_min_offset;
2875 last = HOP3c(strend, /* Cannot start after this */
2876 -(SSize_t)(CHR_SVLEN(must)
2877 - (SvTAIL(must) != 0) + back_min), strbeg);
2879 if (s > reginfo->strbeg)
2880 last1 = HOPc(s, -1);
2882 last1 = s - 1; /* bogus */
2884 /* XXXX check_substr already used to find "s", can optimize if
2885 check_substr==must. */
2887 strend = HOPc(strend, -dontbother);
2888 while ( (s <= last) &&
2889 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
2890 (unsigned char*)strend, must,
2891 multiline ? FBMrf_MULTILINE : 0)) ) {
2892 DEBUG_EXECUTE_r( did_match = 1 );
2893 if (HOPc(s, -back_max) > last1) {
2894 last1 = HOPc(s, -back_min);
2895 s = HOPc(s, -back_max);
2898 char * const t = (last1 >= reginfo->strbeg)
2899 ? HOPc(last1, 1) : last1 + 1;
2901 last1 = HOPc(s, -back_min);
2905 while (s <= last1) {
2906 if (regtry(reginfo, &s))
2909 s++; /* to break out of outer loop */
2916 while (s <= last1) {
2917 if (regtry(reginfo, &s))
2923 DEBUG_EXECUTE_r(if (!did_match) {
2924 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2925 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2926 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2927 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2928 ? "anchored" : "floating"),
2929 quoted, RE_SV_TAIL(must));
2933 else if ( (c = progi->regstclass) ) {
2935 const OPCODE op = OP(progi->regstclass);
2936 /* don't bother with what can't match */
2937 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2938 strend = HOPc(strend, -(minlen - 1));
2941 SV * const prop = sv_newmortal();
2942 regprop(prog, prop, c, reginfo);
2944 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2946 PerlIO_printf(Perl_debug_log,
2947 "Matching stclass %.*s against %s (%d bytes)\n",
2948 (int)SvCUR(prop), SvPVX_const(prop),
2949 quoted, (int)(strend - s));
2952 if (find_byclass(prog, c, s, strend, reginfo))
2954 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2958 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2966 if (! prog->float_utf8) {
2967 to_utf8_substr(prog);
2969 float_real = prog->float_utf8;
2972 if (! prog->float_substr) {
2973 if (! to_byte_substr(prog)) {
2974 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2977 float_real = prog->float_substr;
2980 little = SvPV_const(float_real, len);
2981 if (SvTAIL(float_real)) {
2982 /* This means that float_real contains an artificial \n on
2983 * the end due to the presence of something like this:
2984 * /foo$/ where we can match both "foo" and "foo\n" at the
2985 * end of the string. So we have to compare the end of the
2986 * string first against the float_real without the \n and
2987 * then against the full float_real with the string. We
2988 * have to watch out for cases where the string might be
2989 * smaller than the float_real or the float_real without
2991 char *checkpos= strend - len;
2993 PerlIO_printf(Perl_debug_log,
2994 "%sChecking for float_real.%s\n",
2995 PL_colors[4], PL_colors[5]));
2996 if (checkpos + 1 < strbeg) {
2997 /* can't match, even if we remove the trailing \n
2998 * string is too short to match */
3000 PerlIO_printf(Perl_debug_log,
3001 "%sString shorter than required trailing substring, cannot match.%s\n",
3002 PL_colors[4], PL_colors[5]));
3004 } else if (memEQ(checkpos + 1, little, len - 1)) {
3005 /* can match, the end of the string matches without the
3007 last = checkpos + 1;
3008 } else if (checkpos < strbeg) {
3009 /* cant match, string is too short when the "\n" is
3012 PerlIO_printf(Perl_debug_log,
3013 "%sString does not contain required trailing substring, cannot match.%s\n",
3014 PL_colors[4], PL_colors[5]));
3016 } else if (!multiline) {
3017 /* non multiline match, so compare with the "\n" at the
3018 * end of the string */
3019 if (memEQ(checkpos, little, len)) {
3023 PerlIO_printf(Perl_debug_log,
3024 "%sString does not contain required trailing substring, cannot match.%s\n",
3025 PL_colors[4], PL_colors[5]));
3029 /* multiline match, so we have to search for a place
3030 * where the full string is located */
3036 last = rninstr(s, strend, little, little + len);
3038 last = strend; /* matching "$" */
3041 /* at one point this block contained a comment which was
3042 * probably incorrect, which said that this was a "should not
3043 * happen" case. Even if it was true when it was written I am
3044 * pretty sure it is not anymore, so I have removed the comment
3045 * and replaced it with this one. Yves */
3047 PerlIO_printf(Perl_debug_log,
3048 "String does not contain required substring, cannot match.\n"
3052 dontbother = strend - last + prog->float_min_offset;
3054 if (minlen && (dontbother < minlen))
3055 dontbother = minlen - 1;
3056 strend -= dontbother; /* this one's always in bytes! */
3057 /* We don't know much -- general case. */
3060 if (regtry(reginfo, &s))
3069 if (regtry(reginfo, &s))
3071 } while (s++ < strend);
3079 /* s/// doesn't like it if $& is earlier than where we asked it to
3080 * start searching (which can happen on something like /.\G/) */
3081 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3082 && (prog->offs[0].start < stringarg - strbeg))
3084 /* this should only be possible under \G */
3085 assert(prog->intflags & PREGf_GPOS_SEEN);
3086 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3087 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3093 PerlIO_printf(Perl_debug_log,
3094 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3101 /* clean up; this will trigger destructors that will free all slabs
3102 * above the current one, and cleanup the regmatch_info_aux
3103 * and regmatch_info_aux_eval sructs */
3105 LEAVE_SCOPE(oldsave);
3107 if (RXp_PAREN_NAMES(prog))
3108 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3110 /* make sure $`, $&, $', and $digit will work later */
3111 if ( !(flags & REXEC_NOT_FIRST) )
3112 S_reg_set_capture_string(aTHX_ rx,
3113 strbeg, reginfo->strend,
3114 sv, flags, utf8_target);
3119 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3120 PL_colors[4], PL_colors[5]));
3122 /* clean up; this will trigger destructors that will free all slabs
3123 * above the current one, and cleanup the regmatch_info_aux
3124 * and regmatch_info_aux_eval sructs */
3126 LEAVE_SCOPE(oldsave);
3129 /* we failed :-( roll it back */
3130 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3131 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3136 Safefree(prog->offs);
3143 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3144 * Do inc before dec, in case old and new rex are the same */
3145 #define SET_reg_curpm(Re2) \
3146 if (reginfo->info_aux_eval) { \
3147 (void)ReREFCNT_inc(Re2); \
3148 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3149 PM_SETRE((PL_reg_curpm), (Re2)); \
3154 - regtry - try match at specific point
3156 STATIC I32 /* 0 failure, 1 success */
3157 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3161 REGEXP *const rx = reginfo->prog;
3162 regexp *const prog = ReANY(rx);
3164 RXi_GET_DECL(prog,progi);
3165 GET_RE_DEBUG_FLAGS_DECL;
3167 PERL_ARGS_ASSERT_REGTRY;
3169 reginfo->cutpoint=NULL;
3171 prog->offs[0].start = *startposp - reginfo->strbeg;
3172 prog->lastparen = 0;
3173 prog->lastcloseparen = 0;
3175 /* XXXX What this code is doing here?!!! There should be no need
3176 to do this again and again, prog->lastparen should take care of
3179 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3180 * Actually, the code in regcppop() (which Ilya may be meaning by
3181 * prog->lastparen), is not needed at all by the test suite
3182 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3183 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3184 * Meanwhile, this code *is* needed for the
3185 * above-mentioned test suite tests to succeed. The common theme
3186 * on those tests seems to be returning null fields from matches.
3187 * --jhi updated by dapm */
3189 if (prog->nparens) {
3190 regexp_paren_pair *pp = prog->offs;
3192 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3200 result = regmatch(reginfo, *startposp, progi->program + 1);
3202 prog->offs[0].end = result;
3205 if (reginfo->cutpoint)
3206 *startposp= reginfo->cutpoint;
3207 REGCP_UNWIND(lastcp);
3212 #define sayYES goto yes
3213 #define sayNO goto no
3214 #define sayNO_SILENT goto no_silent
3216 /* we dont use STMT_START/END here because it leads to
3217 "unreachable code" warnings, which are bogus, but distracting. */
3218 #define CACHEsayNO \
3219 if (ST.cache_mask) \
3220 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3223 /* this is used to determine how far from the left messages like
3224 'failed...' are printed. It should be set such that messages
3225 are inline with the regop output that created them.
3227 #define REPORT_CODE_OFF 32
3230 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3231 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3232 #define CHRTEST_NOT_A_CP_1 -999
3233 #define CHRTEST_NOT_A_CP_2 -998
3235 /* grab a new slab and return the first slot in it */
3237 STATIC regmatch_state *
3240 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3243 regmatch_slab *s = PL_regmatch_slab->next;
3245 Newx(s, 1, regmatch_slab);
3246 s->prev = PL_regmatch_slab;
3248 PL_regmatch_slab->next = s;
3250 PL_regmatch_slab = s;
3251 return SLAB_FIRST(s);
3255 /* push a new state then goto it */
3257 #define PUSH_STATE_GOTO(state, node, input) \
3258 pushinput = input; \
3260 st->resume_state = state; \
3263 /* push a new state with success backtracking, then goto it */
3265 #define PUSH_YES_STATE_GOTO(state, node, input) \
3266 pushinput = input; \
3268 st->resume_state = state; \
3269 goto push_yes_state;
3276 regmatch() - main matching routine
3278 This is basically one big switch statement in a loop. We execute an op,
3279 set 'next' to point the next op, and continue. If we come to a point which
3280 we may need to backtrack to on failure such as (A|B|C), we push a
3281 backtrack state onto the backtrack stack. On failure, we pop the top
3282 state, and re-enter the loop at the state indicated. If there are no more
3283 states to pop, we return failure.
3285 Sometimes we also need to backtrack on success; for example /A+/, where
3286 after successfully matching one A, we need to go back and try to
3287 match another one; similarly for lookahead assertions: if the assertion
3288 completes successfully, we backtrack to the state just before the assertion
3289 and then carry on. In these cases, the pushed state is marked as
3290 'backtrack on success too'. This marking is in fact done by a chain of
3291 pointers, each pointing to the previous 'yes' state. On success, we pop to
3292 the nearest yes state, discarding any intermediate failure-only states.
3293 Sometimes a yes state is pushed just to force some cleanup code to be
3294 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3295 it to free the inner regex.
3297 Note that failure backtracking rewinds the cursor position, while
3298 success backtracking leaves it alone.
3300 A pattern is complete when the END op is executed, while a subpattern
3301 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3302 ops trigger the "pop to last yes state if any, otherwise return true"
3305 A common convention in this function is to use A and B to refer to the two
3306 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3307 the subpattern to be matched possibly multiple times, while B is the entire
3308 rest of the pattern. Variable and state names reflect this convention.
3310 The states in the main switch are the union of ops and failure/success of
3311 substates associated with with that op. For example, IFMATCH is the op
3312 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3313 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3314 successfully matched A and IFMATCH_A_fail is a state saying that we have
3315 just failed to match A. Resume states always come in pairs. The backtrack
3316 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3317 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3318 on success or failure.
3320 The struct that holds a backtracking state is actually a big union, with
3321 one variant for each major type of op. The variable st points to the
3322 top-most backtrack struct. To make the code clearer, within each
3323 block of code we #define ST to alias the relevant union.
3325 Here's a concrete example of a (vastly oversimplified) IFMATCH
3331 #define ST st->u.ifmatch
3333 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3334 ST.foo = ...; // some state we wish to save
3336 // push a yes backtrack state with a resume value of
3337 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3339 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3342 case IFMATCH_A: // we have successfully executed A; now continue with B
3344 bar = ST.foo; // do something with the preserved value
3347 case IFMATCH_A_fail: // A failed, so the assertion failed
3348 ...; // do some housekeeping, then ...
3349 sayNO; // propagate the failure
3356 For any old-timers reading this who are familiar with the old recursive
3357 approach, the code above is equivalent to:
3359 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3368 ...; // do some housekeeping, then ...
3369 sayNO; // propagate the failure
3372 The topmost backtrack state, pointed to by st, is usually free. If you
3373 want to claim it, populate any ST.foo fields in it with values you wish to
3374 save, then do one of
3376 PUSH_STATE_GOTO(resume_state, node, newinput);
3377 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3379 which sets that backtrack state's resume value to 'resume_state', pushes a
3380 new free entry to the top of the backtrack stack, then goes to 'node'.
3381 On backtracking, the free slot is popped, and the saved state becomes the
3382 new free state. An ST.foo field in this new top state can be temporarily
3383 accessed to retrieve values, but once the main loop is re-entered, it
3384 becomes available for reuse.
3386 Note that the depth of the backtrack stack constantly increases during the
3387 left-to-right execution of the pattern, rather than going up and down with
3388 the pattern nesting. For example the stack is at its maximum at Z at the
3389 end of the pattern, rather than at X in the following:
3391 /(((X)+)+)+....(Y)+....Z/
3393 The only exceptions to this are lookahead/behind assertions and the cut,
3394 (?>A), which pop all the backtrack states associated with A before
3397 Backtrack state structs are allocated in slabs of about 4K in size.
3398 PL_regmatch_state and st always point to the currently active state,
3399 and PL_regmatch_slab points to the slab currently containing
3400 PL_regmatch_state. The first time regmatch() is called, the first slab is
3401 allocated, and is never freed until interpreter destruction. When the slab
3402 is full, a new one is allocated and chained to the end. At exit from
3403 regmatch(), slabs allocated since entry are freed.
3408 #define DEBUG_STATE_pp(pp) \
3410 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3411 PerlIO_printf(Perl_debug_log, \
3412 " %*s"pp" %s%s%s%s%s\n", \
3414 PL_reg_name[st->resume_state], \
3415 ((st==yes_state||st==mark_state) ? "[" : ""), \
3416 ((st==yes_state) ? "Y" : ""), \
3417 ((st==mark_state) ? "M" : ""), \
3418 ((st==yes_state||st==mark_state) ? "]" : "") \
3423 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3428 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3429 const char *start, const char *end, const char *blurb)
3431 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3433 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3438 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3439 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3441 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3442 start, end - start, 60);
3444 PerlIO_printf(Perl_debug_log,
3445 "%s%s REx%s %s against %s\n",
3446 PL_colors[4], blurb, PL_colors[5], s0, s1);
3448 if (utf8_target||utf8_pat)
3449 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3450 utf8_pat ? "pattern" : "",
3451 utf8_pat && utf8_target ? " and " : "",
3452 utf8_target ? "string" : ""
3458 S_dump_exec_pos(pTHX_ const char *locinput,
3459 const regnode *scan,
3460 const char *loc_regeol,
3461 const char *loc_bostr,
3462 const char *loc_reg_starttry,
3463 const bool utf8_target)
3465 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3466 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3467 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3468 /* The part of the string before starttry has one color
3469 (pref0_len chars), between starttry and current
3470 position another one (pref_len - pref0_len chars),
3471 after the current position the third one.
3472 We assume that pref0_len <= pref_len, otherwise we
3473 decrease pref0_len. */
3474 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3475 ? (5 + taill) - l : locinput - loc_bostr;
3478 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3480 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3482 pref0_len = pref_len - (locinput - loc_reg_starttry);
3483 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3484 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3485 ? (5 + taill) - pref_len : loc_regeol - locinput);
3486 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3490 if (pref0_len > pref_len)
3491 pref0_len = pref_len;
3493 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3495 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3496 (locinput - pref_len),pref0_len, 60, 4, 5);
3498 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3499 (locinput - pref_len + pref0_len),
3500 pref_len - pref0_len, 60, 2, 3);
3502 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3503 locinput, loc_regeol - locinput, 10, 0, 1);
3505 const STRLEN tlen=len0+len1+len2;
3506 PerlIO_printf(Perl_debug_log,
3507 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3508 (IV)(locinput - loc_bostr),
3511 (docolor ? "" : "> <"),
3513 (int)(tlen > 19 ? 0 : 19 - tlen),
3520 /* reg_check_named_buff_matched()
3521 * Checks to see if a named buffer has matched. The data array of
3522 * buffer numbers corresponding to the buffer is expected to reside
3523 * in the regexp->data->data array in the slot stored in the ARG() of
3524 * node involved. Note that this routine doesn't actually care about the
3525 * name, that information is not preserved from compilation to execution.
3526 * Returns the index of the leftmost defined buffer with the given name
3527 * or 0 if non of the buffers matched.
3530 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
3533 RXi_GET_DECL(rex,rexi);
3534 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3535 I32 *nums=(I32*)SvPVX(sv_dat);
3537 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3539 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3540 if ((I32)rex->lastparen >= nums[n] &&
3541 rex->offs[nums[n]].end != -1)
3551 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3552 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3554 /* This function determines if there are one or two characters that match
3555 * the first character of the passed-in EXACTish node <text_node>, and if
3556 * so, returns them in the passed-in pointers.
3558 * If it determines that no possible character in the target string can
3559 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3560 * the first character in <text_node> requires UTF-8 to represent, and the
3561 * target string isn't in UTF-8.)
3563 * If there are more than two characters that could match the beginning of
3564 * <text_node>, or if more context is required to determine a match or not,
3565 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3567 * The motiviation behind this function is to allow the caller to set up
3568 * tight loops for matching. If <text_node> is of type EXACT, there is
3569 * only one possible character that can match its first character, and so
3570 * the situation is quite simple. But things get much more complicated if
3571 * folding is involved. It may be that the first character of an EXACTFish
3572 * node doesn't participate in any possible fold, e.g., punctuation, so it
3573 * can be matched only by itself. The vast majority of characters that are
3574 * in folds match just two things, their lower and upper-case equivalents.
3575 * But not all are like that; some have multiple possible matches, or match
3576 * sequences of more than one character. This function sorts all that out.
3578 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3579 * loop of trying to match A*, we know we can't exit where the thing
3580 * following it isn't a B. And something can't be a B unless it is the
3581 * beginning of B. By putting a quick test for that beginning in a tight
3582 * loop, we can rule out things that can't possibly be B without having to
3583 * break out of the loop, thus avoiding work. Similarly, if A is a single
3584 * character, we can make a tight loop matching A*, using the outputs of
3587 * If the target string to match isn't in UTF-8, and there aren't
3588 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3589 * the one or two possible octets (which are characters in this situation)
3590 * that can match. In all cases, if there is only one character that can
3591 * match, *<c1p> and *<c2p> will be identical.
3593 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3594 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3595 * can match the beginning of <text_node>. They should be declared with at
3596 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3597 * undefined what these contain.) If one or both of the buffers are
3598 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3599 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3600 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3601 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3602 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3604 const bool utf8_target = reginfo->is_utf8_target;
3606 UV c1 = CHRTEST_NOT_A_CP_1;
3607 UV c2 = CHRTEST_NOT_A_CP_2;
3608 bool use_chrtest_void = FALSE;
3609 const bool is_utf8_pat = reginfo->is_utf8_pat;
3611 /* Used when we have both utf8 input and utf8 output, to avoid converting
3612 * to/from code points */
3613 bool utf8_has_been_setup = FALSE;
3617 U8 *pat = (U8*)STRING(text_node);
3618 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3620 if (OP(text_node) == EXACT) {
3622 /* In an exact node, only one thing can be matched, that first
3623 * character. If both the pat and the target are UTF-8, we can just
3624 * copy the input to the output, avoiding finding the code point of
3629 else if (utf8_target) {
3630 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3631 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3632 utf8_has_been_setup = TRUE;
3635 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3638 else { /* an EXACTFish node */
3639 U8 *pat_end = pat + STR_LEN(text_node);
3641 /* An EXACTFL node has at least some characters unfolded, because what
3642 * they match is not known until now. So, now is the time to fold
3643 * the first few of them, as many as are needed to determine 'c1' and
3644 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3645 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3646 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3647 * need to fold as many characters as a single character can fold to,
3648 * so that later we can check if the first ones are such a multi-char
3649 * fold. But, in such a pattern only locale-problematic characters
3650 * aren't folded, so we can skip this completely if the first character
3651 * in the node isn't one of the tricky ones */
3652 if (OP(text_node) == EXACTFL) {
3654 if (! is_utf8_pat) {
3655 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3657 folded[0] = folded[1] = 's';
3659 pat_end = folded + 2;
3662 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3667 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3669 *(d++) = (U8) toFOLD_LC(*s);
3674 _to_utf8_fold_flags(s,
3677 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
3688 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
3689 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
3691 /* Multi-character folds require more context to sort out. Also
3692 * PL_utf8_foldclosures used below doesn't handle them, so have to
3693 * be handled outside this routine */
3694 use_chrtest_void = TRUE;
3696 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
3697 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
3699 /* Load the folds hash, if not already done */
3701 if (! PL_utf8_foldclosures) {
3702 if (! PL_utf8_tofold) {
3703 U8 dummy[UTF8_MAXBYTES_CASE+1];
3705 /* Force loading this by folding an above-Latin1 char */
3706 to_utf8_fold((U8*) HYPHEN_UTF8, dummy, NULL);
3707 assert(PL_utf8_tofold); /* Verify that worked */
3709 PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
3712 /* The fold closures data structure is a hash with the keys
3713 * being the UTF-8 of every character that is folded to, like
3714 * 'k', and the values each an array of all code points that
3715 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
3716 * Multi-character folds are not included */
3717 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
3722 /* Not found in the hash, therefore there are no folds
3723 * containing it, so there is only a single character that
3727 else { /* Does participate in folds */
3728 AV* list = (AV*) *listp;
3729 if (av_tindex(list) != 1) {
3731 /* If there aren't exactly two folds to this, it is
3732 * outside the scope of this function */
3733 use_chrtest_void = TRUE;
3735 else { /* There are two. Get them */
3736 SV** c_p = av_fetch(list, 0, FALSE);
3738 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3742 c_p = av_fetch(list, 1, FALSE);
3744 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3748 /* Folds that cross the 255/256 boundary are forbidden
3749 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
3750 * one is ASCIII. Since the pattern character is above
3751 * 256, and its only other match is below 256, the only
3752 * legal match will be to itself. We have thrown away
3753 * the original, so have to compute which is the one
3755 if ((c1 < 256) != (c2 < 256)) {
3756 if ((OP(text_node) == EXACTFL
3757 && ! IN_UTF8_CTYPE_LOCALE)
3758 || ((OP(text_node) == EXACTFA
3759 || OP(text_node) == EXACTFA_NO_TRIE)
3760 && (isASCII(c1) || isASCII(c2))))
3773 else /* Here, c1 is < 255 */
3775 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
3776 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
3777 && ((OP(text_node) != EXACTFA
3778 && OP(text_node) != EXACTFA_NO_TRIE)
3781 /* Here, there could be something above Latin1 in the target
3782 * which folds to this character in the pattern. All such
3783 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
3784 * than two characters involved in their folds, so are outside
3785 * the scope of this function */
3786 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
3787 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
3790 use_chrtest_void = TRUE;
3793 else { /* Here nothing above Latin1 can fold to the pattern
3795 switch (OP(text_node)) {
3797 case EXACTFL: /* /l rules */
3798 c2 = PL_fold_locale[c1];
3801 case EXACTF: /* This node only generated for non-utf8
3803 assert(! is_utf8_pat);
3804 if (! utf8_target) { /* /d rules */
3809 /* /u rules for all these. This happens to work for
3810 * EXACTFA as nothing in Latin1 folds to ASCII */
3811 case EXACTFA_NO_TRIE: /* This node only generated for
3812 non-utf8 patterns */
3813 assert(! is_utf8_pat);
3818 c2 = PL_fold_latin1[c1];
3822 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
3823 assert(0); /* NOTREACHED */
3829 /* Here have figured things out. Set up the returns */
3830 if (use_chrtest_void) {
3831 *c2p = *c1p = CHRTEST_VOID;
3833 else if (utf8_target) {
3834 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
3835 uvchr_to_utf8(c1_utf8, c1);
3836 uvchr_to_utf8(c2_utf8, c2);
3839 /* Invariants are stored in both the utf8 and byte outputs; Use
3840 * negative numbers otherwise for the byte ones. Make sure that the
3841 * byte ones are the same iff the utf8 ones are the same */
3842 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
3843 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
3846 ? CHRTEST_NOT_A_CP_1
3847 : CHRTEST_NOT_A_CP_2;
3849 else if (c1 > 255) {
3850 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
3855 *c1p = *c2p = c2; /* c2 is the only representable value */
3857 else { /* c1 is representable; see about c2 */
3859 *c2p = (c2 < 256) ? c2 : c1;
3865 /* returns -1 on failure, $+[0] on success */
3867 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
3869 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3873 const bool utf8_target = reginfo->is_utf8_target;
3874 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3875 REGEXP *rex_sv = reginfo->prog;
3876 regexp *rex = ReANY(rex_sv);
3877 RXi_GET_DECL(rex,rexi);
3878 /* the current state. This is a cached copy of PL_regmatch_state */
3880 /* cache heavy used fields of st in registers */
3883 U32 n = 0; /* general value; init to avoid compiler warning */
3884 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
3885 char *locinput = startpos;
3886 char *pushinput; /* where to continue after a PUSH */
3887 I32 nextchr; /* is always set to UCHARAT(locinput) */
3889 bool result = 0; /* return value of S_regmatch */
3890 int depth = 0; /* depth of backtrack stack */
3891 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3892 const U32 max_nochange_depth =
3893 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3894 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3895 regmatch_state *yes_state = NULL; /* state to pop to on success of
3897 /* mark_state piggy backs on the yes_state logic so that when we unwind
3898 the stack on success we can update the mark_state as we go */
3899 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3900 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3901 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3903 bool no_final = 0; /* prevent failure from backtracking? */
3904 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3905 char *startpoint = locinput;
3906 SV *popmark = NULL; /* are we looking for a mark? */
3907 SV *sv_commit = NULL; /* last mark name seen in failure */
3908 SV *sv_yes_mark = NULL; /* last mark name we have seen
3909 during a successful match */
3910 U32 lastopen = 0; /* last open we saw */
3911 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3912 SV* const oreplsv = GvSVn(PL_replgv);
3913 /* these three flags are set by various ops to signal information to
3914 * the very next op. They have a useful lifetime of exactly one loop
3915 * iteration, and are not preserved or restored by state pushes/pops
3917 bool sw = 0; /* the condition value in (?(cond)a|b) */
3918 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3919 int logical = 0; /* the following EVAL is:
3923 or the following IFMATCH/UNLESSM is:
3924 false: plain (?=foo)
3925 true: used as a condition: (?(?=foo))
3927 PAD* last_pad = NULL;
3929 I32 gimme = G_SCALAR;
3930 CV *caller_cv = NULL; /* who called us */
3931 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
3932 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
3933 U32 maxopenparen = 0; /* max '(' index seen so far */
3934 int to_complement; /* Invert the result? */
3935 _char_class_number classnum;
3936 bool is_utf8_pat = reginfo->is_utf8_pat;
3939 GET_RE_DEBUG_FLAGS_DECL;
3942 /* protect against undef(*^R) */
3943 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
3945 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3946 multicall_oldcatch = 0;
3947 multicall_cv = NULL;
3949 PERL_UNUSED_VAR(multicall_cop);
3950 PERL_UNUSED_VAR(newsp);
3953 PERL_ARGS_ASSERT_REGMATCH;
3955 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3956 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3959 st = PL_regmatch_state;
3961 /* Note that nextchr is a byte even in UTF */
3964 while (scan != NULL) {
3967 SV * const prop = sv_newmortal();
3968 regnode *rnext=regnext(scan);
3969 DUMP_EXEC_POS( locinput, scan, utf8_target );
3970 regprop(rex, prop, scan, reginfo);
3972 PerlIO_printf(Perl_debug_log,
3973 "%3"IVdf":%*s%s(%"IVdf")\n",
3974 (IV)(scan - rexi->program), depth*2, "",
3976 (PL_regkind[OP(scan)] == END || !rnext) ?
3977 0 : (IV)(rnext - rexi->program));
3980 next = scan + NEXT_OFF(scan);
3983 state_num = OP(scan);
3989 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
3991 switch (state_num) {
3992 case BOL: /* /^../ */
3993 case SBOL: /* /^../s */
3994 if (locinput == reginfo->strbeg)
3998 case MBOL: /* /^../m */
3999 if (locinput == reginfo->strbeg ||
4000 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4007 if (locinput == reginfo->ganch)
4011 case KEEPS: /* \K */
4012 /* update the startpoint */
4013 st->u.keeper.val = rex->offs[0].start;
4014 rex->offs[0].start = locinput - reginfo->strbeg;
4015 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4016 assert(0); /*NOTREACHED*/
4017 case KEEPS_next_fail:
4018 /* rollback the start point change */
4019 rex->offs[0].start = st->u.keeper.val;
4021 assert(0); /*NOTREACHED*/
4023 case MEOL: /* /..$/m */
4024 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4028 case EOL: /* /..$/ */
4030 case SEOL: /* /..$/s */
4031 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4033 if (reginfo->strend - locinput > 1)
4038 if (!NEXTCHR_IS_EOS)
4042 case SANY: /* /./s */
4045 goto increment_locinput;
4053 case REG_ANY: /* /./ */
4054 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4056 goto increment_locinput;
4060 #define ST st->u.trie
4061 case TRIEC: /* (ab|cd) with known charclass */
4062 /* In this case the charclass data is available inline so
4063 we can fail fast without a lot of extra overhead.
4065 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
4067 PerlIO_printf(Perl_debug_log,
4068 "%*s %sfailed to match trie start class...%s\n",
4069 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4072 assert(0); /* NOTREACHED */
4075 case TRIE: /* (ab|cd) */
4076 /* the basic plan of execution of the trie is:
4077 * At the beginning, run though all the states, and
4078 * find the longest-matching word. Also remember the position
4079 * of the shortest matching word. For example, this pattern:
4082 * when matched against the string "abcde", will generate
4083 * accept states for all words except 3, with the longest
4084 * matching word being 4, and the shortest being 2 (with
4085 * the position being after char 1 of the string).
4087 * Then for each matching word, in word order (i.e. 1,2,4,5),
4088 * we run the remainder of the pattern; on each try setting
4089 * the current position to the character following the word,
4090 * returning to try the next word on failure.
4092 * We avoid having to build a list of words at runtime by
4093 * using a compile-time structure, wordinfo[].prev, which
4094 * gives, for each word, the previous accepting word (if any).
4095 * In the case above it would contain the mappings 1->2, 2->0,
4096 * 3->0, 4->5, 5->1. We can use this table to generate, from
4097 * the longest word (4 above), a list of all words, by
4098 * following the list of prev pointers; this gives us the
4099 * unordered list 4,5,1,2. Then given the current word we have
4100 * just tried, we can go through the list and find the
4101 * next-biggest word to try (so if we just failed on word 2,
4102 * the next in the list is 4).
4104 * Since at runtime we don't record the matching position in
4105 * the string for each word, we have to work that out for
4106 * each word we're about to process. The wordinfo table holds
4107 * the character length of each word; given that we recorded
4108 * at the start: the position of the shortest word and its
4109 * length in chars, we just need to move the pointer the
4110 * difference between the two char lengths. Depending on
4111 * Unicode status and folding, that's cheap or expensive.
4113 * This algorithm is optimised for the case where are only a
4114 * small number of accept states, i.e. 0,1, or maybe 2.
4115 * With lots of accepts states, and having to try all of them,
4116 * it becomes quadratic on number of accept states to find all
4121 /* what type of TRIE am I? (utf8 makes this contextual) */
4122 DECL_TRIE_TYPE(scan);
4124 /* what trie are we using right now */
4125 reg_trie_data * const trie
4126 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
4127 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
4128 U32 state = trie->startstate;
4131 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
4133 if (trie->states[ state ].wordnum) {
4135 PerlIO_printf(Perl_debug_log,
4136 "%*s %smatched empty string...%s\n",
4137 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4143 PerlIO_printf(Perl_debug_log,
4144 "%*s %sfailed to match trie start class...%s\n",
4145 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4152 U8 *uc = ( U8* )locinput;
4156 U8 *uscan = (U8*)NULL;
4157 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
4158 U32 charcount = 0; /* how many input chars we have matched */
4159 U32 accepted = 0; /* have we seen any accepting states? */
4161 ST.jump = trie->jump;
4164 ST.longfold = FALSE; /* char longer if folded => it's harder */
4167 /* fully traverse the TRIE; note the position of the
4168 shortest accept state and the wordnum of the longest
4171 while ( state && uc <= (U8*)(reginfo->strend) ) {
4172 U32 base = trie->states[ state ].trans.base;
4176 wordnum = trie->states[ state ].wordnum;
4178 if (wordnum) { /* it's an accept state */
4181 /* record first match position */
4183 ST.firstpos = (U8*)locinput;
4188 ST.firstchars = charcount;
4191 if (!ST.nextword || wordnum < ST.nextword)
4192 ST.nextword = wordnum;
4193 ST.topword = wordnum;
4196 DEBUG_TRIE_EXECUTE_r({
4197 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
4198 PerlIO_printf( Perl_debug_log,
4199 "%*s %sState: %4"UVxf" Accepted: %c ",
4200 2+depth * 2, "", PL_colors[4],
4201 (UV)state, (accepted ? 'Y' : 'N'));
4204 /* read a char and goto next state */
4205 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
4207 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
4208 uscan, len, uvc, charid, foldlen,
4215 base + charid - 1 - trie->uniquecharcount)) >= 0)
4217 && ((U32)offset < trie->lasttrans)
4218 && trie->trans[offset].check == state)
4220 state = trie->trans[offset].next;
4231 DEBUG_TRIE_EXECUTE_r(
4232 PerlIO_printf( Perl_debug_log,
4233 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
4234 charid, uvc, (UV)state, PL_colors[5] );
4240 /* calculate total number of accept states */
4245 w = trie->wordinfo[w].prev;
4248 ST.accepted = accepted;
4252 PerlIO_printf( Perl_debug_log,
4253 "%*s %sgot %"IVdf" possible matches%s\n",
4254 REPORT_CODE_OFF + depth * 2, "",
4255 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
4257 goto trie_first_try; /* jump into the fail handler */
4259 assert(0); /* NOTREACHED */
4261 case TRIE_next_fail: /* we failed - try next alternative */
4265 REGCP_UNWIND(ST.cp);
4266 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
4268 if (!--ST.accepted) {
4270 PerlIO_printf( Perl_debug_log,
4271 "%*s %sTRIE failed...%s\n",
4272 REPORT_CODE_OFF+depth*2, "",
4279 /* Find next-highest word to process. Note that this code
4280 * is O(N^2) per trie run (O(N) per branch), so keep tight */
4283 U16 const nextword = ST.nextword;
4284 reg_trie_wordinfo * const wordinfo
4285 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
4286 for (word=ST.topword; word; word=wordinfo[word].prev) {
4287 if (word > nextword && (!min || word < min))
4300 ST.lastparen = rex->lastparen;
4301 ST.lastcloseparen = rex->lastcloseparen;
4305 /* find start char of end of current word */
4307 U32 chars; /* how many chars to skip */
4308 reg_trie_data * const trie
4309 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
4311 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
4313 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
4318 /* the hard option - fold each char in turn and find
4319 * its folded length (which may be different */
4320 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
4328 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
4336 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
4341 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
4357 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
4358 ? ST.jump[ST.nextword]
4362 PerlIO_printf( Perl_debug_log,
4363 "%*s %sTRIE matched word #%d, continuing%s\n",
4364 REPORT_CODE_OFF+depth*2, "",
4371 if (ST.accepted > 1 || has_cutgroup) {
4372 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
4373 assert(0); /* NOTREACHED */
4375 /* only one choice left - just continue */
4377 AV *const trie_words
4378 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
4379 SV ** const tmp = av_fetch( trie_words,
4381 SV *sv= tmp ? sv_newmortal() : NULL;
4383 PerlIO_printf( Perl_debug_log,
4384 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
4385 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
4387 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
4388 PL_colors[0], PL_colors[1],
4389 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
4391 : "not compiled under -Dr",
4395 locinput = (char*)uc;
4396 continue; /* execute rest of RE */
4397 assert(0); /* NOTREACHED */
4401 case EXACT: { /* /abc/ */
4402 char *s = STRING(scan);
4404 if (utf8_target != is_utf8_pat) {
4405 /* The target and the pattern have differing utf8ness. */
4407 const char * const e = s + ln;
4410 /* The target is utf8, the pattern is not utf8.
4411 * Above-Latin1 code points can't match the pattern;
4412 * invariants match exactly, and the other Latin1 ones need
4413 * to be downgraded to a single byte in order to do the
4414 * comparison. (If we could be confident that the target
4415 * is not malformed, this could be refactored to have fewer
4416 * tests by just assuming that if the first bytes match, it
4417 * is an invariant, but there are tests in the test suite
4418 * dealing with (??{...}) which violate this) */
4420 if (l >= reginfo->strend
4421 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
4425 if (UTF8_IS_INVARIANT(*(U8*)l)) {
4432 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
4442 /* The target is not utf8, the pattern is utf8. */
4444 if (l >= reginfo->strend
4445 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
4449 if (UTF8_IS_INVARIANT(*(U8*)s)) {
4456 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
4468 /* The target and the pattern have the same utf8ness. */
4469 /* Inline the first character, for speed. */
4470 if (reginfo->strend - locinput < ln
4471 || UCHARAT(s) != nextchr
4472 || (ln > 1 && memNE(s, locinput, ln)))
4481 case EXACTFL: { /* /abc/il */
4483 const U8 * fold_array;
4485 U32 fold_utf8_flags;
4487 folder = foldEQ_locale;
4488 fold_array = PL_fold_locale;
4489 fold_utf8_flags = FOLDEQ_LOCALE;
4492 case EXACTFU_SS: /* /\x{df}/iu */
4493 case EXACTFU: /* /abc/iu */
4494 folder = foldEQ_latin1;
4495 fold_array = PL_fold_latin1;
4496 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
4499 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
4501 assert(! is_utf8_pat);
4503 case EXACTFA: /* /abc/iaa */
4504 folder = foldEQ_latin1;
4505 fold_array = PL_fold_latin1;
4506 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4509 case EXACTF: /* /abc/i This node only generated for
4510 non-utf8 patterns */
4511 assert(! is_utf8_pat);
4513 fold_array = PL_fold;
4514 fold_utf8_flags = 0;
4522 || state_num == EXACTFU_SS
4523 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
4525 /* Either target or the pattern are utf8, or has the issue where
4526 * the fold lengths may differ. */
4527 const char * const l = locinput;
4528 char *e = reginfo->strend;
4530 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
4531 l, &e, 0, utf8_target, fold_utf8_flags))
4539 /* Neither the target nor the pattern are utf8 */
4540 if (UCHARAT(s) != nextchr
4542 && UCHARAT(s) != fold_array[nextchr])
4546 if (reginfo->strend - locinput < ln)
4548 if (ln > 1 && ! folder(s, locinput, ln))
4554 /* XXX Could improve efficiency by separating these all out using a
4555 * macro or in-line function. At that point regcomp.c would no longer
4556 * have to set the FLAGS fields of these */
4557 case BOUNDL: /* /\b/l */
4558 case NBOUNDL: /* /\B/l */
4559 case BOUND: /* /\b/ */
4560 case BOUNDU: /* /\b/u */
4561 case BOUNDA: /* /\b/a */
4562 case NBOUND: /* /\B/ */
4563 case NBOUNDU: /* /\B/u */
4564 case NBOUNDA: /* /\B/a */
4565 /* was last char in word? */
4567 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
4568 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
4570 if (locinput == reginfo->strbeg)
4573 const U8 * const r =
4574 reghop3((U8*)locinput, -1, (U8*)(reginfo->strbeg));
4576 ln = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,
4579 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
4580 ln = isWORDCHAR_uni(ln);
4584 LOAD_UTF8_CHARCLASS_ALNUM();
4585 n = swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)locinput,
4590 ln = isWORDCHAR_LC_uvchr(ln);
4591 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC_utf8((U8*)locinput);
4596 /* Here the string isn't utf8, or is utf8 and only ascii
4597 * characters are to match \w. In the latter case looking at
4598 * the byte just prior to the current one may be just the final
4599 * byte of a multi-byte character. This is ok. There are two
4601 * 1) it is a single byte character, and then the test is doing
4602 * just what it's supposed to.
4603 * 2) it is a multi-byte character, in which case the final
4604 * byte is never mistakable for ASCII, and so the test
4605 * will say it is not a word character, which is the
4606 * correct answer. */
4607 ln = (locinput != reginfo->strbeg) ?
4608 UCHARAT(locinput - 1) : '\n';
4609 switch (FLAGS(scan)) {
4610 case REGEX_UNICODE_CHARSET:
4611 ln = isWORDCHAR_L1(ln);
4612 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_L1(nextchr);
4614 case REGEX_LOCALE_CHARSET:
4615 ln = isWORDCHAR_LC(ln);
4616 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC(nextchr);
4618 case REGEX_DEPENDS_CHARSET:
4619 ln = isWORDCHAR(ln);
4620 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR(nextchr);
4622 case REGEX_ASCII_RESTRICTED_CHARSET:
4623 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
4624 ln = isWORDCHAR_A(ln);
4625 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_A(nextchr);
4628 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
4632 /* Note requires that all BOUNDs be lower than all NBOUNDs in
4634 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
4638 case ANYOF: /* /[abc]/ */
4642 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
4645 locinput += UTF8SKIP(locinput);
4648 if (!REGINCLASS(rex, scan, (U8*)locinput))
4654 /* The argument (FLAGS) to all the POSIX node types is the class number
4657 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
4661 case POSIXL: /* \w or [:punct:] etc. under /l */
4665 /* Use isFOO_lc() for characters within Latin1. (Note that
4666 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4667 * wouldn't be invariant) */
4668 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4669 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
4673 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4674 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
4675 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4676 *(locinput + 1))))))
4681 else { /* Here, must be an above Latin-1 code point */
4682 goto utf8_posix_not_eos;
4685 /* Here, must be utf8 */
4686 locinput += UTF8SKIP(locinput);
4689 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
4693 case POSIXD: /* \w or [:punct:] etc. under /d */
4699 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
4701 if (NEXTCHR_IS_EOS) {
4705 /* All UTF-8 variants match */
4706 if (! UTF8_IS_INVARIANT(nextchr)) {
4707 goto increment_locinput;
4713 case POSIXA: /* \w or [:punct:] etc. under /a */
4716 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
4717 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
4718 * character is a single byte */
4721 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
4727 /* Here we are either not in utf8, or we matched a utf8-invariant,
4728 * so the next char is the next byte */
4732 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
4736 case POSIXU: /* \w or [:punct:] etc. under /u */
4738 if (NEXTCHR_IS_EOS) {
4743 /* Use _generic_isCC() for characters within Latin1. (Note that
4744 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4745 * wouldn't be invariant) */
4746 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4747 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
4754 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4755 if (! (to_complement
4756 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4764 else { /* Handle above Latin-1 code points */
4765 classnum = (_char_class_number) FLAGS(scan);
4766 if (classnum < _FIRST_NON_SWASH_CC) {
4768 /* Here, uses a swash to find such code points. Load if if
4769 * not done already */
4770 if (! PL_utf8_swash_ptrs[classnum]) {
4771 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
4772 PL_utf8_swash_ptrs[classnum]
4773 = _core_swash_init("utf8",
4776 PL_XPosix_ptrs[classnum], &flags);
4778 if (! (to_complement
4779 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
4780 (U8 *) locinput, TRUE))))
4785 else { /* Here, uses macros to find above Latin-1 code points */
4787 case _CC_ENUM_SPACE: /* XXX would require separate
4788 code if we revert the change
4789 of \v matching this */
4790 case _CC_ENUM_PSXSPC:
4791 if (! (to_complement
4792 ^ cBOOL(is_XPERLSPACE_high(locinput))))
4797 case _CC_ENUM_BLANK:
4798 if (! (to_complement
4799 ^ cBOOL(is_HORIZWS_high(locinput))))
4804 case _CC_ENUM_XDIGIT:
4805 if (! (to_complement
4806 ^ cBOOL(is_XDIGIT_high(locinput))))
4811 case _CC_ENUM_VERTSPACE:
4812 if (! (to_complement
4813 ^ cBOOL(is_VERTWS_high(locinput))))
4818 default: /* The rest, e.g. [:cntrl:], can't match
4820 if (! to_complement) {
4826 locinput += UTF8SKIP(locinput);
4830 case CLUMP: /* Match \X: logical Unicode character. This is defined as
4831 a Unicode extended Grapheme Cluster */
4832 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
4833 extended Grapheme Cluster is:
4836 | Prepend* Begin Extend*
4839 Begin is: ( Special_Begin | ! Control )
4840 Special_Begin is: ( Regional-Indicator+ | Hangul-syllable )
4841 Extend is: ( Grapheme_Extend | Spacing_Mark )
4842 Control is: [ GCB_Control | CR | LF ]
4843 Hangul-syllable is: ( T+ | ( L* ( L | ( LVT | ( V | LV ) V* ) T* ) ))
4845 If we create a 'Regular_Begin' = Begin - Special_Begin, then
4848 Begin is ( Regular_Begin + Special Begin )
4850 It turns out that 98.4% of all Unicode code points match
4851 Regular_Begin. Doing it this way eliminates a table match in
4852 the previous implementation for almost all Unicode code points.
4854 There is a subtlety with Prepend* which showed up in testing.
4855 Note that the Begin, and only the Begin is required in:
4856 | Prepend* Begin Extend*
4857 Also, Begin contains '! Control'. A Prepend must be a
4858 '! Control', which means it must also be a Begin. What it
4859 comes down to is that if we match Prepend* and then find no
4860 suitable Begin afterwards, that if we backtrack the last
4861 Prepend, that one will be a suitable Begin.
4866 if (! utf8_target) {
4868 /* Match either CR LF or '.', as all the other possibilities
4870 locinput++; /* Match the . or CR */
4871 if (nextchr == '\r' /* And if it was CR, and the next is LF,
4873 && locinput < reginfo->strend
4874 && UCHARAT(locinput) == '\n')
4881 /* Utf8: See if is ( CR LF ); already know that locinput <
4882 * reginfo->strend, so locinput+1 is in bounds */
4883 if ( nextchr == '\r' && locinput+1 < reginfo->strend
4884 && UCHARAT(locinput + 1) == '\n')
4891 /* In case have to backtrack to beginning, then match '.' */
4892 char *starting = locinput;
4894 /* In case have to backtrack the last prepend */
4895 char *previous_prepend = NULL;
4897 LOAD_UTF8_CHARCLASS_GCB();
4899 /* Match (prepend)* */
4900 while (locinput < reginfo->strend
4901 && (len = is_GCB_Prepend_utf8(locinput)))
4903 previous_prepend = locinput;
4907 /* As noted above, if we matched a prepend character, but
4908 * the next thing won't match, back off the last prepend we
4909 * matched, as it is guaranteed to match the begin */
4910 if (previous_prepend
4911 && (locinput >= reginfo->strend
4912 || (! swash_fetch(PL_utf8_X_regular_begin,
4913 (U8*)locinput, utf8_target)
4914 && ! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)))
4917 locinput = previous_prepend;
4920 /* Note that here we know reginfo->strend > locinput, as we
4921 * tested that upon input to this switch case, and if we
4922 * moved locinput forward, we tested the result just above
4923 * and it either passed, or we backed off so that it will
4925 if (swash_fetch(PL_utf8_X_regular_begin,
4926 (U8*)locinput, utf8_target)) {
4927 locinput += UTF8SKIP(locinput);
4929 else if (! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)) {
4931 /* Here did not match the required 'Begin' in the
4932 * second term. So just match the very first
4933 * character, the '.' of the final term of the regex */
4934 locinput = starting + UTF8SKIP(starting);
4938 /* Here is a special begin. It can be composed of
4939 * several individual characters. One possibility is
4941 if ((len = is_GCB_RI_utf8(locinput))) {
4943 while (locinput < reginfo->strend
4944 && (len = is_GCB_RI_utf8(locinput)))
4948 } else if ((len = is_GCB_T_utf8(locinput))) {
4949 /* Another possibility is T+ */
4951 while (locinput < reginfo->strend
4952 && (len = is_GCB_T_utf8(locinput)))
4958 /* Here, neither RI+ nor T+; must be some other
4959 * Hangul. That means it is one of the others: L,
4960 * LV, LVT or V, and matches:
4961 * L* (L | LVT T* | V * V* T* | LV V* T*) */
4964 while (locinput < reginfo->strend
4965 && (len = is_GCB_L_utf8(locinput)))
4970 /* Here, have exhausted L*. If the next character
4971 * is not an LV, LVT nor V, it means we had to have
4972 * at least one L, so matches L+ in the original
4973 * equation, we have a complete hangul syllable.
4976 if (locinput < reginfo->strend
4977 && is_GCB_LV_LVT_V_utf8(locinput))
4979 /* Otherwise keep going. Must be LV, LVT or V.
4980 * See if LVT, by first ruling out V, then LV */
4981 if (! is_GCB_V_utf8(locinput)
4982 /* All but every TCount one is LV */
4983 && (valid_utf8_to_uvchr((U8 *) locinput,
4988 locinput += UTF8SKIP(locinput);
4991 /* Must be V or LV. Take it, then match
4993 locinput += UTF8SKIP(locinput);
4994 while (locinput < reginfo->strend
4995 && (len = is_GCB_V_utf8(locinput)))
5001 /* And any of LV, LVT, or V can be followed
5003 while (locinput < reginfo->strend
5004 && (len = is_GCB_T_utf8(locinput)))
5012 /* Match any extender */
5013 while (locinput < reginfo->strend
5014 && swash_fetch(PL_utf8_X_extend,
5015 (U8*)locinput, utf8_target))
5017 locinput += UTF8SKIP(locinput);
5021 if (locinput > reginfo->strend) sayNO;
5025 case NREFFL: /* /\g{name}/il */
5026 { /* The capture buffer cases. The ones beginning with N for the
5027 named buffers just convert to the equivalent numbered and
5028 pretend they were called as the corresponding numbered buffer
5030 /* don't initialize these in the declaration, it makes C++
5035 const U8 *fold_array;
5038 folder = foldEQ_locale;
5039 fold_array = PL_fold_locale;
5041 utf8_fold_flags = FOLDEQ_LOCALE;
5044 case NREFFA: /* /\g{name}/iaa */
5045 folder = foldEQ_latin1;
5046 fold_array = PL_fold_latin1;
5048 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5051 case NREFFU: /* /\g{name}/iu */
5052 folder = foldEQ_latin1;
5053 fold_array = PL_fold_latin1;
5055 utf8_fold_flags = 0;
5058 case NREFF: /* /\g{name}/i */
5060 fold_array = PL_fold;
5062 utf8_fold_flags = 0;
5065 case NREF: /* /\g{name}/ */
5069 utf8_fold_flags = 0;
5072 /* For the named back references, find the corresponding buffer
5074 n = reg_check_named_buff_matched(rex,scan);
5079 goto do_nref_ref_common;
5081 case REFFL: /* /\1/il */
5082 folder = foldEQ_locale;
5083 fold_array = PL_fold_locale;
5084 utf8_fold_flags = FOLDEQ_LOCALE;
5087 case REFFA: /* /\1/iaa */
5088 folder = foldEQ_latin1;
5089 fold_array = PL_fold_latin1;
5090 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5093 case REFFU: /* /\1/iu */
5094 folder = foldEQ_latin1;
5095 fold_array = PL_fold_latin1;
5096 utf8_fold_flags = 0;
5099 case REFF: /* /\1/i */
5101 fold_array = PL_fold;
5102 utf8_fold_flags = 0;
5105 case REF: /* /\1/ */
5108 utf8_fold_flags = 0;
5112 n = ARG(scan); /* which paren pair */
5115 ln = rex->offs[n].start;
5116 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5117 if (rex->lastparen < n || ln == -1)
5118 sayNO; /* Do not match unless seen CLOSEn. */
5119 if (ln == rex->offs[n].end)
5122 s = reginfo->strbeg + ln;
5123 if (type != REF /* REF can do byte comparison */
5124 && (utf8_target || type == REFFU || type == REFFL))
5126 char * limit = reginfo->strend;
5128 /* This call case insensitively compares the entire buffer
5129 * at s, with the current input starting at locinput, but
5130 * not going off the end given by reginfo->strend, and
5131 * returns in <limit> upon success, how much of the
5132 * current input was matched */
5133 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
5134 locinput, &limit, 0, utf8_target, utf8_fold_flags))
5142 /* Not utf8: Inline the first character, for speed. */
5143 if (!NEXTCHR_IS_EOS &&
5144 UCHARAT(s) != nextchr &&
5146 UCHARAT(s) != fold_array[nextchr]))
5148 ln = rex->offs[n].end - ln;
5149 if (locinput + ln > reginfo->strend)
5151 if (ln > 1 && (type == REF
5152 ? memNE(s, locinput, ln)
5153 : ! folder(s, locinput, ln)))
5159 case NOTHING: /* null op; e.g. the 'nothing' following
5160 * the '*' in m{(a+|b)*}' */
5162 case TAIL: /* placeholder while compiling (A|B|C) */
5165 case BACK: /* ??? doesn't appear to be used ??? */
5169 #define ST st->u.eval
5174 regexp_internal *rei;
5175 regnode *startpoint;
5177 case GOSTART: /* (?R) */
5178 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
5179 if (cur_eval && cur_eval->locinput==locinput) {
5180 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
5181 Perl_croak(aTHX_ "Infinite recursion in regex");
5182 if ( ++nochange_depth > max_nochange_depth )
5184 "Pattern subroutine nesting without pos change"
5185 " exceeded limit in regex");
5192 if (OP(scan)==GOSUB) {
5193 startpoint = scan + ARG2L(scan);
5194 ST.close_paren = ARG(scan);
5196 startpoint = rei->program+1;
5200 /* Save all the positions seen so far. */
5201 ST.cp = regcppush(rex, 0, maxopenparen);
5202 REGCP_SET(ST.lastcp);
5204 /* and then jump to the code we share with EVAL */
5205 goto eval_recurse_doit;
5207 assert(0); /* NOTREACHED */
5209 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
5210 if (cur_eval && cur_eval->locinput==locinput) {
5211 if ( ++nochange_depth > max_nochange_depth )
5212 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
5217 /* execute the code in the {...} */
5221 OP * const oop = PL_op;
5222 COP * const ocurcop = PL_curcop;
5226 /* save *all* paren positions */
5227 regcppush(rex, 0, maxopenparen);
5228 REGCP_SET(runops_cp);
5231 caller_cv = find_runcv(NULL);
5235 if (rexi->data->what[n] == 'r') { /* code from an external qr */
5237 (REGEXP*)(rexi->data->data[n])
5240 nop = (OP*)rexi->data->data[n+1];
5242 else if (rexi->data->what[n] == 'l') { /* literal code */
5244 nop = (OP*)rexi->data->data[n];
5245 assert(CvDEPTH(newcv));
5248 /* literal with own CV */
5249 assert(rexi->data->what[n] == 'L');
5250 newcv = rex->qr_anoncv;
5251 nop = (OP*)rexi->data->data[n];
5254 /* normally if we're about to execute code from the same
5255 * CV that we used previously, we just use the existing
5256 * CX stack entry. However, its possible that in the
5257 * meantime we may have backtracked, popped from the save
5258 * stack, and undone the SAVECOMPPAD(s) associated with
5259 * PUSH_MULTICALL; in which case PL_comppad no longer
5260 * points to newcv's pad. */
5261 if (newcv != last_pushed_cv || PL_comppad != last_pad)
5263 U8 flags = (CXp_SUB_RE |
5264 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
5265 if (last_pushed_cv) {
5266 CHANGE_MULTICALL_FLAGS(newcv, flags);
5269 PUSH_MULTICALL_FLAGS(newcv, flags);
5271 last_pushed_cv = newcv;
5274 /* these assignments are just to silence compiler
5276 multicall_cop = NULL;
5279 last_pad = PL_comppad;
5281 /* the initial nextstate you would normally execute
5282 * at the start of an eval (which would cause error
5283 * messages to come from the eval), may be optimised
5284 * away from the execution path in the regex code blocks;
5285 * so manually set PL_curcop to it initially */
5287 OP *o = cUNOPx(nop)->op_first;
5288 assert(o->op_type == OP_NULL);
5289 if (o->op_targ == OP_SCOPE) {
5290 o = cUNOPo->op_first;
5293 assert(o->op_targ == OP_LEAVE);
5294 o = cUNOPo->op_first;
5295 assert(o->op_type == OP_ENTER);
5299 if (o->op_type != OP_STUB) {
5300 assert( o->op_type == OP_NEXTSTATE
5301 || o->op_type == OP_DBSTATE
5302 || (o->op_type == OP_NULL
5303 && ( o->op_targ == OP_NEXTSTATE
5304 || o->op_targ == OP_DBSTATE
5308 PL_curcop = (COP*)o;
5313 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
5314 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
5316 rex->offs[0].end = locinput - reginfo->strbeg;
5317 if (reginfo->info_aux_eval->pos_magic)
5318 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
5319 reginfo->sv, reginfo->strbeg,
5320 locinput - reginfo->strbeg);
5323 SV *sv_mrk = get_sv("REGMARK", 1);
5324 sv_setsv(sv_mrk, sv_yes_mark);
5327 /* we don't use MULTICALL here as we want to call the
5328 * first op of the block of interest, rather than the
5329 * first op of the sub */
5330 before = (IV)(SP-PL_stack_base);
5332 CALLRUNOPS(aTHX); /* Scalar context. */
5334 if ((IV)(SP-PL_stack_base) == before)
5335 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
5341 /* before restoring everything, evaluate the returned
5342 * value, so that 'uninit' warnings don't use the wrong
5343 * PL_op or pad. Also need to process any magic vars
5344 * (e.g. $1) *before* parentheses are restored */
5349 if (logical == 0) /* (?{})/ */
5350 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
5351 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
5352 sw = cBOOL(SvTRUE(ret));
5355 else { /* /(??{}) */
5356 /* if its overloaded, let the regex compiler handle
5357 * it; otherwise extract regex, or stringify */
5358 if (SvGMAGICAL(ret))
5359 ret = sv_mortalcopy(ret);
5360 if (!SvAMAGIC(ret)) {
5364 if (SvTYPE(sv) == SVt_REGEXP)
5365 re_sv = (REGEXP*) sv;
5366 else if (SvSMAGICAL(ret)) {
5367 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
5369 re_sv = (REGEXP *) mg->mg_obj;
5372 /* force any undef warnings here */
5373 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
5374 ret = sv_mortalcopy(ret);
5375 (void) SvPV_force_nolen(ret);
5381 /* *** Note that at this point we don't restore
5382 * PL_comppad, (or pop the CxSUB) on the assumption it may
5383 * be used again soon. This is safe as long as nothing
5384 * in the regexp code uses the pad ! */
5386 PL_curcop = ocurcop;
5387 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
5388 PL_curpm = PL_reg_curpm;
5394 /* only /(??{})/ from now on */
5397 /* extract RE object from returned value; compiling if
5401 re_sv = reg_temp_copy(NULL, re_sv);
5406 if (SvUTF8(ret) && IN_BYTES) {
5407 /* In use 'bytes': make a copy of the octet
5408 * sequence, but without the flag on */
5410 const char *const p = SvPV(ret, len);
5411 ret = newSVpvn_flags(p, len, SVs_TEMP);
5413 if (rex->intflags & PREGf_USE_RE_EVAL)
5414 pm_flags |= PMf_USE_RE_EVAL;
5416 /* if we got here, it should be an engine which
5417 * supports compiling code blocks and stuff */
5418 assert(rex->engine && rex->engine->op_comp);
5419 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
5420 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
5421 rex->engine, NULL, NULL,
5422 /* copy /msix etc to inner pattern */
5427 & (SVs_TEMP | SVs_GMG | SVf_ROK))
5428 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
5429 /* This isn't a first class regexp. Instead, it's
5430 caching a regexp onto an existing, Perl visible
5432 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
5438 RXp_MATCH_COPIED_off(re);
5439 re->subbeg = rex->subbeg;
5440 re->sublen = rex->sublen;
5441 re->suboffset = rex->suboffset;
5442 re->subcoffset = rex->subcoffset;
5444 re->lastcloseparen = 0;
5447 debug_start_match(re_sv, utf8_target, locinput,
5448 reginfo->strend, "Matching embedded");
5450 startpoint = rei->program + 1;
5451 ST.close_paren = 0; /* only used for GOSUB */
5452 /* Save all the seen positions so far. */
5453 ST.cp = regcppush(rex, 0, maxopenparen);
5454 REGCP_SET(ST.lastcp);
5455 /* and set maxopenparen to 0, since we are starting a "fresh" match */
5457 /* run the pattern returned from (??{...}) */
5459 eval_recurse_doit: /* Share code with GOSUB below this line
5460 * At this point we expect the stack context to be
5461 * set up correctly */
5463 /* invalidate the S-L poscache. We're now executing a
5464 * different set of WHILEM ops (and their associated
5465 * indexes) against the same string, so the bits in the
5466 * cache are meaningless. Setting maxiter to zero forces
5467 * the cache to be invalidated and zeroed before reuse.
5468 * XXX This is too dramatic a measure. Ideally we should
5469 * save the old cache and restore when running the outer
5471 reginfo->poscache_maxiter = 0;
5473 /* the new regexp might have a different is_utf8_pat than we do */
5474 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
5476 ST.prev_rex = rex_sv;
5477 ST.prev_curlyx = cur_curlyx;
5479 SET_reg_curpm(rex_sv);
5484 ST.prev_eval = cur_eval;
5486 /* now continue from first node in postoned RE */
5487 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
5488 assert(0); /* NOTREACHED */
5491 case EVAL_AB: /* cleanup after a successful (??{A})B */
5492 /* note: this is called twice; first after popping B, then A */
5493 rex_sv = ST.prev_rex;
5494 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5495 SET_reg_curpm(rex_sv);
5496 rex = ReANY(rex_sv);
5497 rexi = RXi_GET(rex);
5499 /* preserve $^R across LEAVE's. See Bug 121070. */
5500 SV *save_sv= GvSV(PL_replgv);
5501 SvREFCNT_inc(save_sv);
5502 regcpblow(ST.cp); /* LEAVE in disguise */
5503 sv_setsv(GvSV(PL_replgv), save_sv);
5504 SvREFCNT_dec(save_sv);
5506 cur_eval = ST.prev_eval;
5507 cur_curlyx = ST.prev_curlyx;
5509 /* Invalidate cache. See "invalidate" comment above. */
5510 reginfo->poscache_maxiter = 0;
5511 if ( nochange_depth )
5516 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
5517 /* note: this is called twice; first after popping B, then A */
5518 rex_sv = ST.prev_rex;
5519 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5520 SET_reg_curpm(rex_sv);
5521 rex = ReANY(rex_sv);
5522 rexi = RXi_GET(rex);
5524 REGCP_UNWIND(ST.lastcp);
5525 regcppop(rex, &maxopenparen);
5526 cur_eval = ST.prev_eval;
5527 cur_curlyx = ST.prev_curlyx;
5528 /* Invalidate cache. See "invalidate" comment above. */
5529 reginfo->poscache_maxiter = 0;
5530 if ( nochange_depth )
5536 n = ARG(scan); /* which paren pair */
5537 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
5538 if (n > maxopenparen)
5540 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
5541 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
5545 (IV)rex->offs[n].start_tmp,
5551 /* XXX really need to log other places start/end are set too */
5552 #define CLOSE_CAPTURE \
5553 rex->offs[n].start = rex->offs[n].start_tmp; \
5554 rex->offs[n].end = locinput - reginfo->strbeg; \
5555 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
5556 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
5558 PTR2UV(rex->offs), \
5560 (IV)rex->offs[n].start, \
5561 (IV)rex->offs[n].end \
5565 n = ARG(scan); /* which paren pair */
5567 if (n > rex->lastparen)
5569 rex->lastcloseparen = n;
5570 if (cur_eval && cur_eval->u.eval.close_paren == n) {
5575 case ACCEPT: /* (*ACCEPT) */
5579 cursor && OP(cursor)!=END;
5580 cursor=regnext(cursor))
5582 if ( OP(cursor)==CLOSE ){
5584 if ( n <= lastopen ) {
5586 if (n > rex->lastparen)
5588 rex->lastcloseparen = n;
5589 if ( n == ARG(scan) || (cur_eval &&
5590 cur_eval->u.eval.close_paren == n))
5599 case GROUPP: /* (?(1)) */
5600 n = ARG(scan); /* which paren pair */
5601 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
5604 case NGROUPP: /* (?(<name>)) */
5605 /* reg_check_named_buff_matched returns 0 for no match */
5606 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
5609 case INSUBP: /* (?(R)) */
5611 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
5614 case DEFINEP: /* (?(DEFINE)) */
5618 case IFTHEN: /* (?(cond)A|B) */
5619 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5621 next = NEXTOPER(NEXTOPER(scan));
5623 next = scan + ARG(scan);
5624 if (OP(next) == IFTHEN) /* Fake one. */
5625 next = NEXTOPER(NEXTOPER(next));
5629 case LOGICAL: /* modifier for EVAL and IFMATCH */
5630 logical = scan->flags;
5633 /*******************************************************************
5635 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
5636 pattern, where A and B are subpatterns. (For simple A, CURLYM or
5637 STAR/PLUS/CURLY/CURLYN are used instead.)
5639 A*B is compiled as <CURLYX><A><WHILEM><B>
5641 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
5642 state, which contains the current count, initialised to -1. It also sets
5643 cur_curlyx to point to this state, with any previous value saved in the
5646 CURLYX then jumps straight to the WHILEM op, rather than executing A,
5647 since the pattern may possibly match zero times (i.e. it's a while {} loop
5648 rather than a do {} while loop).
5650 Each entry to WHILEM represents a successful match of A. The count in the
5651 CURLYX block is incremented, another WHILEM state is pushed, and execution
5652 passes to A or B depending on greediness and the current count.
5654 For example, if matching against the string a1a2a3b (where the aN are
5655 substrings that match /A/), then the match progresses as follows: (the
5656 pushed states are interspersed with the bits of strings matched so far):
5659 <CURLYX cnt=0><WHILEM>
5660 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
5661 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
5662 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
5663 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
5665 (Contrast this with something like CURLYM, which maintains only a single
5669 a1 <CURLYM cnt=1> a2
5670 a1 a2 <CURLYM cnt=2> a3
5671 a1 a2 a3 <CURLYM cnt=3> b
5674 Each WHILEM state block marks a point to backtrack to upon partial failure
5675 of A or B, and also contains some minor state data related to that
5676 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
5677 overall state, such as the count, and pointers to the A and B ops.
5679 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
5680 must always point to the *current* CURLYX block, the rules are:
5682 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
5683 and set cur_curlyx to point the new block.
5685 When popping the CURLYX block after a successful or unsuccessful match,
5686 restore the previous cur_curlyx.
5688 When WHILEM is about to execute B, save the current cur_curlyx, and set it
5689 to the outer one saved in the CURLYX block.
5691 When popping the WHILEM block after a successful or unsuccessful B match,
5692 restore the previous cur_curlyx.
5694 Here's an example for the pattern (AI* BI)*BO
5695 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
5698 curlyx backtrack stack
5699 ------ ---------------
5701 CO <CO prev=NULL> <WO>
5702 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5703 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5704 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
5706 At this point the pattern succeeds, and we work back down the stack to
5707 clean up, restoring as we go:
5709 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5710 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5711 CO <CO prev=NULL> <WO>
5714 *******************************************************************/
5716 #define ST st->u.curlyx
5718 case CURLYX: /* start of /A*B/ (for complex A) */
5720 /* No need to save/restore up to this paren */
5721 I32 parenfloor = scan->flags;
5723 assert(next); /* keep Coverity happy */
5724 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
5727 /* XXXX Probably it is better to teach regpush to support
5728 parenfloor > maxopenparen ... */
5729 if (parenfloor > (I32)rex->lastparen)
5730 parenfloor = rex->lastparen; /* Pessimization... */
5732 ST.prev_curlyx= cur_curlyx;
5734 ST.cp = PL_savestack_ix;
5736 /* these fields contain the state of the current curly.
5737 * they are accessed by subsequent WHILEMs */
5738 ST.parenfloor = parenfloor;
5743 ST.count = -1; /* this will be updated by WHILEM */
5744 ST.lastloc = NULL; /* this will be updated by WHILEM */
5746 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
5747 assert(0); /* NOTREACHED */
5750 case CURLYX_end: /* just finished matching all of A*B */
5751 cur_curlyx = ST.prev_curlyx;
5753 assert(0); /* NOTREACHED */
5755 case CURLYX_end_fail: /* just failed to match all of A*B */
5757 cur_curlyx = ST.prev_curlyx;
5759 assert(0); /* NOTREACHED */
5763 #define ST st->u.whilem
5765 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
5767 /* see the discussion above about CURLYX/WHILEM */
5769 int min = ARG1(cur_curlyx->u.curlyx.me);
5770 int max = ARG2(cur_curlyx->u.curlyx.me);
5771 regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
5773 assert(cur_curlyx); /* keep Coverity happy */
5774 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
5775 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
5776 ST.cache_offset = 0;
5780 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5781 "%*s whilem: matched %ld out of %d..%d\n",
5782 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
5785 /* First just match a string of min A's. */
5788 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5790 cur_curlyx->u.curlyx.lastloc = locinput;
5791 REGCP_SET(ST.lastcp);
5793 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
5794 assert(0); /* NOTREACHED */
5797 /* If degenerate A matches "", assume A done. */
5799 if (locinput == cur_curlyx->u.curlyx.lastloc) {
5800 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5801 "%*s whilem: empty match detected, trying continuation...\n",
5802 REPORT_CODE_OFF+depth*2, "")
5804 goto do_whilem_B_max;
5807 /* super-linear cache processing.
5809 * The idea here is that for certain types of CURLYX/WHILEM -
5810 * principally those whose upper bound is infinity (and
5811 * excluding regexes that have things like \1 and other very
5812 * non-regular expresssiony things), then if a pattern like
5813 * /....A*.../ fails and we backtrack to the WHILEM, then we
5814 * make a note that this particular WHILEM op was at string
5815 * position 47 (say) when the rest of pattern failed. Then, if
5816 * we ever find ourselves back at that WHILEM, and at string
5817 * position 47 again, we can just fail immediately rather than
5818 * running the rest of the pattern again.
5820 * This is very handy when patterns start to go
5821 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
5822 * with a combinatorial explosion of backtracking.
5824 * The cache is implemented as a bit array, with one bit per
5825 * string byte position per WHILEM op (up to 16) - so its
5826 * between 0.25 and 2x the string size.
5828 * To avoid allocating a poscache buffer every time, we do an
5829 * initially countdown; only after we have executed a WHILEM
5830 * op (string-length x #WHILEMs) times do we allocate the
5833 * The top 4 bits of scan->flags byte say how many different
5834 * relevant CURLLYX/WHILEM op pairs there are, while the
5835 * bottom 4-bits is the identifying index number of this
5841 if (!reginfo->poscache_maxiter) {
5842 /* start the countdown: Postpone detection until we
5843 * know the match is not *that* much linear. */
5844 reginfo->poscache_maxiter
5845 = (reginfo->strend - reginfo->strbeg + 1)
5847 /* possible overflow for long strings and many CURLYX's */
5848 if (reginfo->poscache_maxiter < 0)
5849 reginfo->poscache_maxiter = I32_MAX;
5850 reginfo->poscache_iter = reginfo->poscache_maxiter;
5853 if (reginfo->poscache_iter-- == 0) {
5854 /* initialise cache */
5855 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
5856 regmatch_info_aux *const aux = reginfo->info_aux;
5857 if (aux->poscache) {
5858 if ((SSize_t)reginfo->poscache_size < size) {
5859 Renew(aux->poscache, size, char);
5860 reginfo->poscache_size = size;
5862 Zero(aux->poscache, size, char);
5865 reginfo->poscache_size = size;
5866 Newxz(aux->poscache, size, char);
5868 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5869 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
5870 PL_colors[4], PL_colors[5])
5874 if (reginfo->poscache_iter < 0) {
5875 /* have we already failed at this position? */
5876 SSize_t offset, mask;
5878 reginfo->poscache_iter = -1; /* stop eventual underflow */
5879 offset = (scan->flags & 0xf) - 1
5880 + (locinput - reginfo->strbeg)
5882 mask = 1 << (offset % 8);
5884 if (reginfo->info_aux->poscache[offset] & mask) {
5885 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5886 "%*s whilem: (cache) already tried at this position...\n",
5887 REPORT_CODE_OFF+depth*2, "")
5889 sayNO; /* cache records failure */
5891 ST.cache_offset = offset;
5892 ST.cache_mask = mask;
5896 /* Prefer B over A for minimal matching. */
5898 if (cur_curlyx->u.curlyx.minmod) {
5899 ST.save_curlyx = cur_curlyx;
5900 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5901 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
5903 REGCP_SET(ST.lastcp);
5904 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
5906 assert(0); /* NOTREACHED */
5909 /* Prefer A over B for maximal matching. */
5911 if (n < max) { /* More greed allowed? */
5912 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5914 cur_curlyx->u.curlyx.lastloc = locinput;
5915 REGCP_SET(ST.lastcp);
5916 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
5917 assert(0); /* NOTREACHED */
5919 goto do_whilem_B_max;
5921 assert(0); /* NOTREACHED */
5923 case WHILEM_B_min: /* just matched B in a minimal match */
5924 case WHILEM_B_max: /* just matched B in a maximal match */
5925 cur_curlyx = ST.save_curlyx;
5927 assert(0); /* NOTREACHED */
5929 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
5930 cur_curlyx = ST.save_curlyx;
5931 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5932 cur_curlyx->u.curlyx.count--;
5934 assert(0); /* NOTREACHED */
5936 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
5938 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
5939 REGCP_UNWIND(ST.lastcp);
5940 regcppop(rex, &maxopenparen);
5941 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5942 cur_curlyx->u.curlyx.count--;
5944 assert(0); /* NOTREACHED */
5946 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5947 REGCP_UNWIND(ST.lastcp);
5948 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
5949 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5950 "%*s whilem: failed, trying continuation...\n",
5951 REPORT_CODE_OFF+depth*2, "")
5954 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5955 && ckWARN(WARN_REGEXP)
5956 && !reginfo->warned)
5958 reginfo->warned = TRUE;
5959 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5960 "Complex regular subexpression recursion limit (%d) "
5966 ST.save_curlyx = cur_curlyx;
5967 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5968 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
5970 assert(0); /* NOTREACHED */
5972 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
5973 cur_curlyx = ST.save_curlyx;
5974 REGCP_UNWIND(ST.lastcp);
5975 regcppop(rex, &maxopenparen);
5977 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
5978 /* Maximum greed exceeded */
5979 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5980 && ckWARN(WARN_REGEXP)
5981 && !reginfo->warned)
5983 reginfo->warned = TRUE;
5984 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5985 "Complex regular subexpression recursion "
5986 "limit (%d) exceeded",
5989 cur_curlyx->u.curlyx.count--;
5993 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5994 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
5996 /* Try grabbing another A and see if it helps. */
5997 cur_curlyx->u.curlyx.lastloc = locinput;
5998 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6000 REGCP_SET(ST.lastcp);
6001 PUSH_STATE_GOTO(WHILEM_A_min,
6002 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6004 assert(0); /* NOTREACHED */
6007 #define ST st->u.branch
6009 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6010 next = scan + ARG(scan);
6013 scan = NEXTOPER(scan);
6016 case BRANCH: /* /(...|A|...)/ */
6017 scan = NEXTOPER(scan); /* scan now points to inner node */
6018 ST.lastparen = rex->lastparen;
6019 ST.lastcloseparen = rex->lastcloseparen;
6020 ST.next_branch = next;
6023 /* Now go into the branch */
6025 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
6027 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
6029 assert(0); /* NOTREACHED */
6031 case CUTGROUP: /* /(*THEN)/ */
6032 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
6033 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6034 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
6035 assert(0); /* NOTREACHED */
6037 case CUTGROUP_next_fail:
6040 if (st->u.mark.mark_name)
6041 sv_commit = st->u.mark.mark_name;
6043 assert(0); /* NOTREACHED */
6047 assert(0); /* NOTREACHED */
6049 case BRANCH_next_fail: /* that branch failed; try the next, if any */
6054 REGCP_UNWIND(ST.cp);
6055 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6056 scan = ST.next_branch;
6057 /* no more branches? */
6058 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
6060 PerlIO_printf( Perl_debug_log,
6061 "%*s %sBRANCH failed...%s\n",
6062 REPORT_CODE_OFF+depth*2, "",
6068 continue; /* execute next BRANCH[J] op */
6069 assert(0); /* NOTREACHED */
6071 case MINMOD: /* next op will be non-greedy, e.g. A*? */
6076 #define ST st->u.curlym
6078 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
6080 /* This is an optimisation of CURLYX that enables us to push
6081 * only a single backtracking state, no matter how many matches
6082 * there are in {m,n}. It relies on the pattern being constant
6083 * length, with no parens to influence future backrefs
6087 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6089 ST.lastparen = rex->lastparen;
6090 ST.lastcloseparen = rex->lastcloseparen;
6092 /* if paren positive, emulate an OPEN/CLOSE around A */
6094 U32 paren = ST.me->flags;
6095 if (paren > maxopenparen)
6096 maxopenparen = paren;
6097 scan += NEXT_OFF(scan); /* Skip former OPEN. */
6105 ST.c1 = CHRTEST_UNINIT;
6108 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
6111 curlym_do_A: /* execute the A in /A{m,n}B/ */
6112 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
6113 assert(0); /* NOTREACHED */
6115 case CURLYM_A: /* we've just matched an A */
6117 /* after first match, determine A's length: u.curlym.alen */
6118 if (ST.count == 1) {
6119 if (reginfo->is_utf8_target) {
6120 char *s = st->locinput;
6121 while (s < locinput) {
6127 ST.alen = locinput - st->locinput;
6130 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
6133 PerlIO_printf(Perl_debug_log,
6134 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
6135 (int)(REPORT_CODE_OFF+(depth*2)), "",
6136 (IV) ST.count, (IV)ST.alen)
6139 if (cur_eval && cur_eval->u.eval.close_paren &&
6140 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6144 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
6145 if ( max == REG_INFTY || ST.count < max )
6146 goto curlym_do_A; /* try to match another A */
6148 goto curlym_do_B; /* try to match B */
6150 case CURLYM_A_fail: /* just failed to match an A */
6151 REGCP_UNWIND(ST.cp);
6153 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
6154 || (cur_eval && cur_eval->u.eval.close_paren &&
6155 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
6158 curlym_do_B: /* execute the B in /A{m,n}B/ */
6159 if (ST.c1 == CHRTEST_UNINIT) {
6160 /* calculate c1 and c2 for possible match of 1st char
6161 * following curly */
6162 ST.c1 = ST.c2 = CHRTEST_VOID;
6163 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
6164 regnode *text_node = ST.B;
6165 if (! HAS_TEXT(text_node))
6166 FIND_NEXT_IMPT(text_node);
6169 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
6171 But the former is redundant in light of the latter.
6173 if this changes back then the macro for
6174 IS_TEXT and friends need to change.
6176 if (PL_regkind[OP(text_node)] == EXACT) {
6177 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6178 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6188 PerlIO_printf(Perl_debug_log,
6189 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
6190 (int)(REPORT_CODE_OFF+(depth*2)),
6193 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
6194 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
6195 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6196 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6198 /* simulate B failing */
6200 PerlIO_printf(Perl_debug_log,
6201 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
6202 (int)(REPORT_CODE_OFF+(depth*2)),"",
6203 valid_utf8_to_uvchr((U8 *) locinput, NULL),
6204 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
6205 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
6207 state_num = CURLYM_B_fail;
6208 goto reenter_switch;
6211 else if (nextchr != ST.c1 && nextchr != ST.c2) {
6212 /* simulate B failing */
6214 PerlIO_printf(Perl_debug_log,
6215 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
6216 (int)(REPORT_CODE_OFF+(depth*2)),"",
6217 (int) nextchr, ST.c1, ST.c2)
6219 state_num = CURLYM_B_fail;
6220 goto reenter_switch;
6225 /* emulate CLOSE: mark current A as captured */
6226 I32 paren = ST.me->flags;
6228 rex->offs[paren].start
6229 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
6230 rex->offs[paren].end = locinput - reginfo->strbeg;
6231 if ((U32)paren > rex->lastparen)
6232 rex->lastparen = paren;
6233 rex->lastcloseparen = paren;
6236 rex->offs[paren].end = -1;
6237 if (cur_eval && cur_eval->u.eval.close_paren &&
6238 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6247 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
6248 assert(0); /* NOTREACHED */
6250 case CURLYM_B_fail: /* just failed to match a B */
6251 REGCP_UNWIND(ST.cp);
6252 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6254 I32 max = ARG2(ST.me);
6255 if (max != REG_INFTY && ST.count == max)
6257 goto curlym_do_A; /* try to match a further A */
6259 /* backtrack one A */
6260 if (ST.count == ARG1(ST.me) /* min */)
6263 SET_locinput(HOPc(locinput, -ST.alen));
6264 goto curlym_do_B; /* try to match B */
6267 #define ST st->u.curly
6269 #define CURLY_SETPAREN(paren, success) \
6272 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
6273 rex->offs[paren].end = locinput - reginfo->strbeg; \
6274 if (paren > rex->lastparen) \
6275 rex->lastparen = paren; \
6276 rex->lastcloseparen = paren; \
6279 rex->offs[paren].end = -1; \
6280 rex->lastparen = ST.lastparen; \
6281 rex->lastcloseparen = ST.lastcloseparen; \
6285 case STAR: /* /A*B/ where A is width 1 char */
6289 scan = NEXTOPER(scan);
6292 case PLUS: /* /A+B/ where A is width 1 char */
6296 scan = NEXTOPER(scan);
6299 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
6300 ST.paren = scan->flags; /* Which paren to set */
6301 ST.lastparen = rex->lastparen;
6302 ST.lastcloseparen = rex->lastcloseparen;
6303 if (ST.paren > maxopenparen)
6304 maxopenparen = ST.paren;
6305 ST.min = ARG1(scan); /* min to match */
6306 ST.max = ARG2(scan); /* max to match */
6307 if (cur_eval && cur_eval->u.eval.close_paren &&
6308 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6312 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
6315 case CURLY: /* /A{m,n}B/ where A is width 1 char */
6317 ST.min = ARG1(scan); /* min to match */
6318 ST.max = ARG2(scan); /* max to match */
6319 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6322 * Lookahead to avoid useless match attempts
6323 * when we know what character comes next.
6325 * Used to only do .*x and .*?x, but now it allows
6326 * for )'s, ('s and (?{ ... })'s to be in the way
6327 * of the quantifier and the EXACT-like node. -- japhy
6330 assert(ST.min <= ST.max);
6331 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
6332 ST.c1 = ST.c2 = CHRTEST_VOID;
6335 regnode *text_node = next;
6337 if (! HAS_TEXT(text_node))
6338 FIND_NEXT_IMPT(text_node);
6340 if (! HAS_TEXT(text_node))
6341 ST.c1 = ST.c2 = CHRTEST_VOID;
6343 if ( PL_regkind[OP(text_node)] != EXACT ) {
6344 ST.c1 = ST.c2 = CHRTEST_VOID;
6348 /* Currently we only get here when
6350 PL_rekind[OP(text_node)] == EXACT
6352 if this changes back then the macro for IS_TEXT and
6353 friends need to change. */
6354 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6355 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6367 char *li = locinput;
6370 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
6376 if (ST.c1 == CHRTEST_VOID)
6377 goto curly_try_B_min;
6379 ST.oldloc = locinput;
6381 /* set ST.maxpos to the furthest point along the
6382 * string that could possibly match */
6383 if (ST.max == REG_INFTY) {
6384 ST.maxpos = reginfo->strend - 1;
6386 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
6389 else if (utf8_target) {
6390 int m = ST.max - ST.min;
6391 for (ST.maxpos = locinput;
6392 m >0 && ST.maxpos < reginfo->strend; m--)
6393 ST.maxpos += UTF8SKIP(ST.maxpos);
6396 ST.maxpos = locinput + ST.max - ST.min;
6397 if (ST.maxpos >= reginfo->strend)
6398 ST.maxpos = reginfo->strend - 1;
6400 goto curly_try_B_min_known;
6404 /* avoid taking address of locinput, so it can remain
6406 char *li = locinput;
6407 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
6408 if (ST.count < ST.min)
6411 if ((ST.count > ST.min)
6412 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
6414 /* A{m,n} must come at the end of the string, there's
6415 * no point in backing off ... */
6417 /* ...except that $ and \Z can match before *and* after
6418 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
6419 We may back off by one in this case. */
6420 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
6424 goto curly_try_B_max;
6426 assert(0); /* NOTREACHED */
6429 case CURLY_B_min_known_fail:
6430 /* failed to find B in a non-greedy match where c1,c2 valid */
6432 REGCP_UNWIND(ST.cp);
6434 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6436 /* Couldn't or didn't -- move forward. */
6437 ST.oldloc = locinput;
6439 locinput += UTF8SKIP(locinput);
6443 curly_try_B_min_known:
6444 /* find the next place where 'B' could work, then call B */
6448 n = (ST.oldloc == locinput) ? 0 : 1;
6449 if (ST.c1 == ST.c2) {
6450 /* set n to utf8_distance(oldloc, locinput) */
6451 while (locinput <= ST.maxpos
6452 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
6454 locinput += UTF8SKIP(locinput);
6459 /* set n to utf8_distance(oldloc, locinput) */
6460 while (locinput <= ST.maxpos
6461 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6462 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6464 locinput += UTF8SKIP(locinput);
6469 else { /* Not utf8_target */
6470 if (ST.c1 == ST.c2) {
6471 while (locinput <= ST.maxpos &&
6472 UCHARAT(locinput) != ST.c1)
6476 while (locinput <= ST.maxpos
6477 && UCHARAT(locinput) != ST.c1
6478 && UCHARAT(locinput) != ST.c2)
6481 n = locinput - ST.oldloc;
6483 if (locinput > ST.maxpos)
6486 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
6487 * at b; check that everything between oldloc and
6488 * locinput matches */
6489 char *li = ST.oldloc;
6491 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
6493 assert(n == REG_INFTY || locinput == li);
6495 CURLY_SETPAREN(ST.paren, ST.count);
6496 if (cur_eval && cur_eval->u.eval.close_paren &&
6497 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6500 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
6502 assert(0); /* NOTREACHED */
6505 case CURLY_B_min_fail:
6506 /* failed to find B in a non-greedy match where c1,c2 invalid */
6508 REGCP_UNWIND(ST.cp);
6510 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6512 /* failed -- move forward one */
6514 char *li = locinput;
6515 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
6522 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
6523 ST.count > 0)) /* count overflow ? */
6526 CURLY_SETPAREN(ST.paren, ST.count);
6527 if (cur_eval && cur_eval->u.eval.close_paren &&
6528 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6531 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
6535 assert(0); /* NOTREACHED */
6539 /* a successful greedy match: now try to match B */
6540 if (cur_eval && cur_eval->u.eval.close_paren &&
6541 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6545 bool could_match = locinput < reginfo->strend;
6547 /* If it could work, try it. */
6548 if (ST.c1 != CHRTEST_VOID && could_match) {
6549 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
6551 could_match = memEQ(locinput,
6556 UTF8SKIP(locinput));
6559 could_match = UCHARAT(locinput) == ST.c1
6560 || UCHARAT(locinput) == ST.c2;
6563 if (ST.c1 == CHRTEST_VOID || could_match) {
6564 CURLY_SETPAREN(ST.paren, ST.count);
6565 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
6566 assert(0); /* NOTREACHED */
6571 case CURLY_B_max_fail:
6572 /* failed to find B in a greedy match */
6574 REGCP_UNWIND(ST.cp);
6576 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6579 if (--ST.count < ST.min)
6581 locinput = HOPc(locinput, -1);
6582 goto curly_try_B_max;
6586 case END: /* last op of main pattern */
6589 /* we've just finished A in /(??{A})B/; now continue with B */
6591 st->u.eval.prev_rex = rex_sv; /* inner */
6593 /* Save *all* the positions. */
6594 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
6595 rex_sv = cur_eval->u.eval.prev_rex;
6596 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6597 SET_reg_curpm(rex_sv);
6598 rex = ReANY(rex_sv);
6599 rexi = RXi_GET(rex);
6600 cur_curlyx = cur_eval->u.eval.prev_curlyx;
6602 REGCP_SET(st->u.eval.lastcp);
6604 /* Restore parens of the outer rex without popping the
6606 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
6609 st->u.eval.prev_eval = cur_eval;
6610 cur_eval = cur_eval->u.eval.prev_eval;
6612 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
6613 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
6614 if ( nochange_depth )
6617 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
6618 locinput); /* match B */
6621 if (locinput < reginfo->till) {
6622 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6623 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
6625 (long)(locinput - startpos),
6626 (long)(reginfo->till - startpos),
6629 sayNO_SILENT; /* Cannot match: too short. */
6631 sayYES; /* Success! */
6633 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
6635 PerlIO_printf(Perl_debug_log,
6636 "%*s %ssubpattern success...%s\n",
6637 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
6638 sayYES; /* Success! */
6641 #define ST st->u.ifmatch
6646 case SUSPEND: /* (?>A) */
6648 newstart = locinput;
6651 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
6653 goto ifmatch_trivial_fail_test;
6655 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
6657 ifmatch_trivial_fail_test:
6659 char * const s = HOPBACKc(locinput, scan->flags);
6664 sw = 1 - cBOOL(ST.wanted);
6668 next = scan + ARG(scan);
6676 newstart = locinput;
6680 ST.logical = logical;
6681 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
6683 /* execute body of (?...A) */
6684 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
6685 assert(0); /* NOTREACHED */
6688 case IFMATCH_A_fail: /* body of (?...A) failed */
6689 ST.wanted = !ST.wanted;
6692 case IFMATCH_A: /* body of (?...A) succeeded */
6694 sw = cBOOL(ST.wanted);
6696 else if (!ST.wanted)
6699 if (OP(ST.me) != SUSPEND) {
6700 /* restore old position except for (?>...) */
6701 locinput = st->locinput;
6703 scan = ST.me + ARG(ST.me);
6706 continue; /* execute B */
6710 case LONGJMP: /* alternative with many branches compiles to
6711 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
6712 next = scan + ARG(scan);
6717 case COMMIT: /* (*COMMIT) */
6718 reginfo->cutpoint = reginfo->strend;
6721 case PRUNE: /* (*PRUNE) */
6723 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6724 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
6725 assert(0); /* NOTREACHED */
6727 case COMMIT_next_fail:
6731 case OPFAIL: /* (*FAIL) */
6733 assert(0); /* NOTREACHED */
6735 #define ST st->u.mark
6736 case MARKPOINT: /* (*MARK:foo) */
6737 ST.prev_mark = mark_state;
6738 ST.mark_name = sv_commit = sv_yes_mark
6739 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6741 ST.mark_loc = locinput;
6742 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
6743 assert(0); /* NOTREACHED */
6745 case MARKPOINT_next:
6746 mark_state = ST.prev_mark;
6748 assert(0); /* NOTREACHED */
6750 case MARKPOINT_next_fail:
6751 if (popmark && sv_eq(ST.mark_name,popmark))
6753 if (ST.mark_loc > startpoint)
6754 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6755 popmark = NULL; /* we found our mark */
6756 sv_commit = ST.mark_name;
6759 PerlIO_printf(Perl_debug_log,
6760 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
6761 REPORT_CODE_OFF+depth*2, "",
6762 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
6765 mark_state = ST.prev_mark;
6766 sv_yes_mark = mark_state ?
6767 mark_state->u.mark.mark_name : NULL;
6769 assert(0); /* NOTREACHED */
6771 case SKIP: /* (*SKIP) */
6773 /* (*SKIP) : if we fail we cut here*/
6774 ST.mark_name = NULL;
6775 ST.mark_loc = locinput;
6776 PUSH_STATE_GOTO(SKIP_next,next, locinput);
6778 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
6779 otherwise do nothing. Meaning we need to scan
6781 regmatch_state *cur = mark_state;
6782 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6785 if ( sv_eq( cur->u.mark.mark_name,
6788 ST.mark_name = find;
6789 PUSH_STATE_GOTO( SKIP_next, next, locinput);
6791 cur = cur->u.mark.prev_mark;
6794 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
6797 case SKIP_next_fail:
6799 /* (*CUT:NAME) - Set up to search for the name as we
6800 collapse the stack*/
6801 popmark = ST.mark_name;
6803 /* (*CUT) - No name, we cut here.*/
6804 if (ST.mark_loc > startpoint)
6805 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6806 /* but we set sv_commit to latest mark_name if there
6807 is one so they can test to see how things lead to this
6810 sv_commit=mark_state->u.mark.mark_name;
6814 assert(0); /* NOTREACHED */
6817 case LNBREAK: /* \R */
6818 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
6825 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
6826 PTR2UV(scan), OP(scan));
6827 Perl_croak(aTHX_ "regexp memory corruption");
6829 /* this is a point to jump to in order to increment
6830 * locinput by one character */
6832 assert(!NEXTCHR_IS_EOS);
6834 locinput += PL_utf8skip[nextchr];
6835 /* locinput is allowed to go 1 char off the end, but not 2+ */
6836 if (locinput > reginfo->strend)
6845 /* switch break jumps here */
6846 scan = next; /* prepare to execute the next op and ... */
6847 continue; /* ... jump back to the top, reusing st */
6848 assert(0); /* NOTREACHED */
6851 /* push a state that backtracks on success */
6852 st->u.yes.prev_yes_state = yes_state;
6856 /* push a new regex state, then continue at scan */
6858 regmatch_state *newst;
6861 regmatch_state *cur = st;
6862 regmatch_state *curyes = yes_state;
6864 regmatch_slab *slab = PL_regmatch_slab;
6865 for (;curd > -1;cur--,curd--) {
6866 if (cur < SLAB_FIRST(slab)) {
6868 cur = SLAB_LAST(slab);
6870 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
6871 REPORT_CODE_OFF + 2 + depth * 2,"",
6872 curd, PL_reg_name[cur->resume_state],
6873 (curyes == cur) ? "yes" : ""
6876 curyes = cur->u.yes.prev_yes_state;
6879 DEBUG_STATE_pp("push")
6882 st->locinput = locinput;
6884 if (newst > SLAB_LAST(PL_regmatch_slab))
6885 newst = S_push_slab(aTHX);
6886 PL_regmatch_state = newst;
6888 locinput = pushinput;
6891 assert(0); /* NOTREACHED */
6896 * We get here only if there's trouble -- normally "case END" is
6897 * the terminating point.
6899 Perl_croak(aTHX_ "corrupted regexp pointers");
6905 /* we have successfully completed a subexpression, but we must now
6906 * pop to the state marked by yes_state and continue from there */
6907 assert(st != yes_state);
6909 while (st != yes_state) {
6911 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6912 PL_regmatch_slab = PL_regmatch_slab->prev;
6913 st = SLAB_LAST(PL_regmatch_slab);
6917 DEBUG_STATE_pp("pop (no final)");
6919 DEBUG_STATE_pp("pop (yes)");
6925 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
6926 || yes_state > SLAB_LAST(PL_regmatch_slab))
6928 /* not in this slab, pop slab */
6929 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
6930 PL_regmatch_slab = PL_regmatch_slab->prev;
6931 st = SLAB_LAST(PL_regmatch_slab);
6933 depth -= (st - yes_state);
6936 yes_state = st->u.yes.prev_yes_state;
6937 PL_regmatch_state = st;
6940 locinput= st->locinput;
6941 state_num = st->resume_state + no_final;
6942 goto reenter_switch;
6945 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6946 PL_colors[4], PL_colors[5]));
6948 if (reginfo->info_aux_eval) {
6949 /* each successfully executed (?{...}) block does the equivalent of
6950 * local $^R = do {...}
6951 * When popping the save stack, all these locals would be undone;
6952 * bypass this by setting the outermost saved $^R to the latest
6954 /* I dont know if this is needed or works properly now.
6955 * see code related to PL_replgv elsewhere in this file.
6958 if (oreplsv != GvSV(PL_replgv))
6959 sv_setsv(oreplsv, GvSV(PL_replgv));
6966 PerlIO_printf(Perl_debug_log,
6967 "%*s %sfailed...%s\n",
6968 REPORT_CODE_OFF+depth*2, "",
6969 PL_colors[4], PL_colors[5])
6981 /* there's a previous state to backtrack to */
6983 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6984 PL_regmatch_slab = PL_regmatch_slab->prev;
6985 st = SLAB_LAST(PL_regmatch_slab);
6987 PL_regmatch_state = st;
6988 locinput= st->locinput;
6990 DEBUG_STATE_pp("pop");
6992 if (yes_state == st)
6993 yes_state = st->u.yes.prev_yes_state;
6995 state_num = st->resume_state + 1; /* failure = success + 1 */
6996 goto reenter_switch;
7001 if (rex->intflags & PREGf_VERBARG_SEEN) {
7002 SV *sv_err = get_sv("REGERROR", 1);
7003 SV *sv_mrk = get_sv("REGMARK", 1);
7005 sv_commit = &PL_sv_no;
7007 sv_yes_mark = &PL_sv_yes;
7010 sv_commit = &PL_sv_yes;
7011 sv_yes_mark = &PL_sv_no;
7013 sv_setsv(sv_err, sv_commit);
7014 sv_setsv(sv_mrk, sv_yes_mark);
7018 if (last_pushed_cv) {
7021 PERL_UNUSED_VAR(SP);
7024 assert(!result || locinput - reginfo->strbeg >= 0);
7025 return result ? locinput - reginfo->strbeg : -1;
7029 - regrepeat - repeatedly match something simple, report how many
7031 * What 'simple' means is a node which can be the operand of a quantifier like
7034 * startposp - pointer a pointer to the start position. This is updated
7035 * to point to the byte following the highest successful
7037 * p - the regnode to be repeatedly matched against.
7038 * reginfo - struct holding match state, such as strend
7039 * max - maximum number of things to match.
7040 * depth - (for debugging) backtracking depth.
7043 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
7044 regmatch_info *const reginfo, I32 max, int depth)
7047 char *scan; /* Pointer to current position in target string */
7049 char *loceol = reginfo->strend; /* local version */
7050 I32 hardcount = 0; /* How many matches so far */
7051 bool utf8_target = reginfo->is_utf8_target;
7052 int to_complement = 0; /* Invert the result? */
7054 _char_class_number classnum;
7056 PERL_UNUSED_ARG(depth);
7059 PERL_ARGS_ASSERT_REGREPEAT;
7062 if (max == REG_INFTY)
7064 else if (! utf8_target && loceol - scan > max)
7065 loceol = scan + max;
7067 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
7068 * to the maximum of how far we should go in it (leaving it set to the real
7069 * end, if the maximum permissible would take us beyond that). This allows
7070 * us to make the loop exit condition that we haven't gone past <loceol> to
7071 * also mean that we haven't exceeded the max permissible count, saving a
7072 * test each time through the loop. But it assumes that the OP matches a
7073 * single byte, which is true for most of the OPs below when applied to a
7074 * non-UTF-8 target. Those relatively few OPs that don't have this
7075 * characteristic will have to compensate.
7077 * There is no adjustment for UTF-8 targets, as the number of bytes per
7078 * character varies. OPs will have to test both that the count is less
7079 * than the max permissible (using <hardcount> to keep track), and that we
7080 * are still within the bounds of the string (using <loceol>. A few OPs
7081 * match a single byte no matter what the encoding. They can omit the max
7082 * test if, for the UTF-8 case, they do the adjustment that was skipped
7085 * Thus, the code above sets things up for the common case; and exceptional
7086 * cases need extra work; the common case is to make sure <scan> doesn't
7087 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
7088 * count doesn't exceed the maximum permissible */
7093 while (scan < loceol && hardcount < max && *scan != '\n') {
7094 scan += UTF8SKIP(scan);
7098 while (scan < loceol && *scan != '\n')
7104 while (scan < loceol && hardcount < max) {
7105 scan += UTF8SKIP(scan);
7112 case CANY: /* Move <scan> forward <max> bytes, unless goes off end */
7113 if (utf8_target && loceol - scan > max) {
7115 /* <loceol> hadn't been adjusted in the UTF-8 case */
7123 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7127 /* Can use a simple loop if the pattern char to match on is invariant
7128 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
7129 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
7130 * true iff it doesn't matter if the argument is in UTF-8 or not */
7131 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
7132 if (utf8_target && loceol - scan > max) {
7133 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
7134 * since here, to match at all, 1 char == 1 byte */
7135 loceol = scan + max;
7137 while (scan < loceol && UCHARAT(scan) == c) {
7141 else if (reginfo->is_utf8_pat) {
7143 STRLEN scan_char_len;
7145 /* When both target and pattern are UTF-8, we have to do
7147 while (hardcount < max
7149 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
7150 && memEQ(scan, STRING(p), scan_char_len))
7152 scan += scan_char_len;
7156 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
7158 /* Target isn't utf8; convert the character in the UTF-8
7159 * pattern to non-UTF8, and do a simple loop */
7160 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
7161 while (scan < loceol && UCHARAT(scan) == c) {
7164 } /* else pattern char is above Latin1, can't possibly match the
7169 /* Here, the string must be utf8; pattern isn't, and <c> is
7170 * different in utf8 than not, so can't compare them directly.
7171 * Outside the loop, find the two utf8 bytes that represent c, and
7172 * then look for those in sequence in the utf8 string */
7173 U8 high = UTF8_TWO_BYTE_HI(c);
7174 U8 low = UTF8_TWO_BYTE_LO(c);
7176 while (hardcount < max
7177 && scan + 1 < loceol
7178 && UCHARAT(scan) == high
7179 && UCHARAT(scan + 1) == low)
7187 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
7188 assert(! reginfo->is_utf8_pat);
7191 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7195 utf8_flags = FOLDEQ_LOCALE;
7198 case EXACTF: /* This node only generated for non-utf8 patterns */
7199 assert(! reginfo->is_utf8_pat);
7205 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
7209 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
7211 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7213 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
7216 if (c1 == CHRTEST_VOID) {
7217 /* Use full Unicode fold matching */
7218 char *tmpeol = reginfo->strend;
7219 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
7220 while (hardcount < max
7221 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
7222 STRING(p), NULL, pat_len,
7223 reginfo->is_utf8_pat, utf8_flags))
7226 tmpeol = reginfo->strend;
7230 else if (utf8_target) {
7232 while (scan < loceol
7234 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
7236 scan += UTF8SKIP(scan);
7241 while (scan < loceol
7243 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
7244 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
7246 scan += UTF8SKIP(scan);
7251 else if (c1 == c2) {
7252 while (scan < loceol && UCHARAT(scan) == c1) {
7257 while (scan < loceol &&
7258 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
7268 while (hardcount < max
7270 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
7272 scan += UTF8SKIP(scan);
7276 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
7281 /* The argument (FLAGS) to all the POSIX node types is the class number */
7288 if (! utf8_target) {
7289 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
7295 while (hardcount < max && scan < loceol
7296 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
7299 scan += UTF8SKIP(scan);
7312 if (utf8_target && loceol - scan > max) {
7314 /* We didn't adjust <loceol> at the beginning of this routine
7315 * because is UTF-8, but it is actually ok to do so, since here, to
7316 * match, 1 char == 1 byte. */
7317 loceol = scan + max;
7319 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
7332 if (! utf8_target) {
7333 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
7339 /* The complement of something that matches only ASCII matches all
7340 * UTF-8 variant code points, plus everything in ASCII that isn't
7342 while (hardcount < max && scan < loceol
7343 && (! UTF8_IS_INVARIANT(*scan)
7344 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
7346 scan += UTF8SKIP(scan);
7357 if (! utf8_target) {
7358 while (scan < loceol && to_complement
7359 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
7366 classnum = (_char_class_number) FLAGS(p);
7367 if (classnum < _FIRST_NON_SWASH_CC) {
7369 /* Here, a swash is needed for above-Latin1 code points.
7370 * Process as many Latin1 code points using the built-in rules.
7371 * Go to another loop to finish processing upon encountering
7372 * the first Latin1 code point. We could do that in this loop
7373 * as well, but the other way saves having to test if the swash
7374 * has been loaded every time through the loop: extra space to
7376 while (hardcount < max && scan < loceol) {
7377 if (UTF8_IS_INVARIANT(*scan)) {
7378 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
7385 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
7386 if (! (to_complement
7387 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
7396 goto found_above_latin1;
7403 /* For these character classes, the knowledge of how to handle
7404 * every code point is compiled in to Perl via a macro. This
7405 * code is written for making the loops as tight as possible.
7406 * It could be refactored to save space instead */
7408 case _CC_ENUM_SPACE: /* XXX would require separate code
7409 if we revert the change of \v
7412 case _CC_ENUM_PSXSPC:
7413 while (hardcount < max
7415 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
7417 scan += UTF8SKIP(scan);
7421 case _CC_ENUM_BLANK:
7422 while (hardcount < max
7424 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
7426 scan += UTF8SKIP(scan);
7430 case _CC_ENUM_XDIGIT:
7431 while (hardcount < max
7433 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
7435 scan += UTF8SKIP(scan);
7439 case _CC_ENUM_VERTSPACE:
7440 while (hardcount < max
7442 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
7444 scan += UTF8SKIP(scan);
7448 case _CC_ENUM_CNTRL:
7449 while (hardcount < max
7451 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
7453 scan += UTF8SKIP(scan);
7458 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
7464 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
7466 /* Load the swash if not already present */
7467 if (! PL_utf8_swash_ptrs[classnum]) {
7468 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7469 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
7473 PL_XPosix_ptrs[classnum], &flags);
7476 while (hardcount < max && scan < loceol
7477 && to_complement ^ cBOOL(_generic_utf8(
7480 swash_fetch(PL_utf8_swash_ptrs[classnum],
7484 scan += UTF8SKIP(scan);
7491 while (hardcount < max && scan < loceol &&
7492 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
7497 /* LNBREAK can match one or two latin chars, which is ok, but we
7498 * have to use hardcount in this situation, and throw away the
7499 * adjustment to <loceol> done before the switch statement */
7500 loceol = reginfo->strend;
7501 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
7522 /* These are all 0 width, so match right here or not at all. */
7526 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
7527 assert(0); /* NOTREACHED */
7534 c = scan - *startposp;
7538 GET_RE_DEBUG_FLAGS_DECL;
7540 SV * const prop = sv_newmortal();
7541 regprop(prog, prop, p, reginfo);
7542 PerlIO_printf(Perl_debug_log,
7543 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
7544 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
7552 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
7554 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
7555 create a copy so that changes the caller makes won't change the shared one.
7556 If <altsvp> is non-null, will return NULL in it, for back-compat.
7559 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
7561 PERL_ARGS_ASSERT_REGCLASS_SWASH;
7567 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL));
7571 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
7572 const regnode* node,
7575 SV** only_utf8_locale_ptr)
7577 /* For internal core use only.
7578 * Returns the swash for the input 'node' in the regex 'prog'.
7579 * If <doinit> is 'true', will attempt to create the swash if not already
7581 * If <listsvp> is non-null, will return the printable contents of the
7582 * swash. This can be used to get debugging information even before the
7583 * swash exists, by calling this function with 'doinit' set to false, in
7584 * which case the components that will be used to eventually create the
7585 * swash are returned (in a printable form).
7586 * Tied intimately to how regcomp.c sets up the data structure */
7590 SV *si = NULL; /* Input swash initialization string */
7593 RXi_GET_DECL(prog,progi);
7594 const struct reg_data * const data = prog ? progi->data : NULL;
7596 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
7598 assert(ANYOF_FLAGS(node)
7599 & (ANYOF_UTF8|ANYOF_NONBITMAP_NON_UTF8|ANYOF_LOC_FOLD));
7601 if (data && data->count) {
7602 const U32 n = ARG(node);
7604 if (data->what[n] == 's') {
7605 SV * const rv = MUTABLE_SV(data->data[n]);
7606 AV * const av = MUTABLE_AV(SvRV(rv));
7607 SV **const ary = AvARRAY(av);
7608 U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7610 si = *ary; /* ary[0] = the string to initialize the swash with */
7612 /* Elements 3 and 4 are either both present or both absent. [3] is
7613 * any inversion list generated at compile time; [4] indicates if
7614 * that inversion list has any user-defined properties in it. */
7615 if (av_tindex(av) >= 2) {
7616 if (only_utf8_locale_ptr
7618 && ary[2] != &PL_sv_undef)
7620 *only_utf8_locale_ptr = ary[2];
7623 *only_utf8_locale_ptr = NULL;
7626 if (av_tindex(av) >= 3) {
7629 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
7637 /* Element [1] is reserved for the set-up swash. If already there,
7638 * return it; if not, create it and store it there */
7639 if (ary[1] && SvROK(ary[1])) {
7642 else if (doinit && ((si && si != &PL_sv_undef)
7643 || (invlist && invlist != &PL_sv_undef))) {
7645 sw = _core_swash_init("utf8", /* the utf8 package */
7649 0, /* not from tr/// */
7652 (void)av_store(av, 1, sw);
7657 /* If requested, return a printable version of what this swash matches */
7659 SV* matches_string = newSVpvn("", 0);
7661 /* The swash should be used, if possible, to get the data, as it
7662 * contains the resolved data. But this function can be called at
7663 * compile-time, before everything gets resolved, in which case we
7664 * return the currently best available information, which is the string
7665 * that will eventually be used to do that resolving, 'si' */
7666 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
7667 && (si && si != &PL_sv_undef))
7669 sv_catsv(matches_string, si);
7672 /* Add the inversion list to whatever we have. This may have come from
7673 * the swash, or from an input parameter */
7675 sv_catsv(matches_string, _invlist_contents(invlist));
7677 *listsvp = matches_string;
7682 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
7685 - reginclass - determine if a character falls into a character class
7687 n is the ANYOF regnode
7688 p is the target string
7689 p_end points to one byte beyond the end of the target string
7690 utf8_target tells whether p is in UTF-8.
7692 Returns true if matched; false otherwise.
7694 Note that this can be a synthetic start class, a combination of various
7695 nodes, so things you think might be mutually exclusive, such as locale,
7696 aren't. It can match both locale and non-locale
7701 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
7704 const char flags = ANYOF_FLAGS(n);
7708 PERL_ARGS_ASSERT_REGINCLASS;
7710 /* If c is not already the code point, get it. Note that
7711 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
7712 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
7714 c = utf8n_to_uvchr(p, p_end - p, &c_len,
7715 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
7716 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
7717 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
7718 * UTF8_ALLOW_FFFF */
7719 if (c_len == (STRLEN)-1)
7720 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
7723 /* If this character is potentially in the bitmap, check it */
7725 if (ANYOF_BITMAP_TEST(n, c))
7727 else if (flags & ANYOF_NON_UTF8_NON_ASCII_ALL
7733 else if (flags & ANYOF_LOCALE_FLAGS) {
7734 if (flags & ANYOF_LOC_FOLD) {
7735 if (ANYOF_BITMAP_TEST(n, PL_fold_locale[c])) {
7739 if (! match && ANYOF_POSIXL_TEST_ANY_SET(n)) {
7741 /* The data structure is arranged so bits 0, 2, 4, ... are set
7742 * if the class includes the Posix character class given by
7743 * bit/2; and 1, 3, 5, ... are set if the class includes the
7744 * complemented Posix class given by int(bit/2). So we loop
7745 * through the bits, each time changing whether we complement
7746 * the result or not. Suppose for the sake of illustration
7747 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
7748 * is set, it means there is a match for this ANYOF node if the
7749 * character is in the class given by the expression (0 / 2 = 0
7750 * = \w). If it is in that class, isFOO_lc() will return 1,
7751 * and since 'to_complement' is 0, the result will stay TRUE,
7752 * and we exit the loop. Suppose instead that bit 0 is 0, but
7753 * bit 1 is 1. That means there is a match if the character
7754 * matches \W. We won't bother to call isFOO_lc() on bit 0,
7755 * but will on bit 1. On the second iteration 'to_complement'
7756 * will be 1, so the exclusive or will reverse things, so we
7757 * are testing for \W. On the third iteration, 'to_complement'
7758 * will be 0, and we would be testing for \s; the fourth
7759 * iteration would test for \S, etc.
7761 * Note that this code assumes that all the classes are closed
7762 * under folding. For example, if a character matches \w, then
7763 * its fold does too; and vice versa. This should be true for
7764 * any well-behaved locale for all the currently defined Posix
7765 * classes, except for :lower: and :upper:, which are handled
7766 * by the pseudo-class :cased: which matches if either of the
7767 * other two does. To get rid of this assumption, an outer
7768 * loop could be used below to iterate over both the source
7769 * character, and its fold (if different) */
7772 int to_complement = 0;
7774 while (count < ANYOF_MAX) {
7775 if (ANYOF_POSIXL_TEST(n, count)
7776 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
7789 /* If the bitmap didn't (or couldn't) match, and something outside the
7790 * bitmap could match, try that. */
7792 if (c >= 256 && (flags & ANYOF_ABOVE_LATIN1_ALL)) {
7793 match = TRUE; /* Everything above 255 matches */
7795 else if ((flags & ANYOF_NONBITMAP_NON_UTF8)
7796 || (utf8_target && (flags & ANYOF_UTF8))
7797 || ((flags & ANYOF_LOC_FOLD)
7798 && IN_UTF8_CTYPE_LOCALE
7799 && ARG(n) != ANYOF_NONBITMAP_EMPTY))
7801 SV* only_utf8_locale = NULL;
7802 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
7808 } else { /* Convert to utf8 */
7810 utf8_p = bytes_to_utf8(p, &len);
7813 if (swash_fetch(sw, utf8_p, TRUE)) {
7817 /* If we allocated a string above, free it */
7818 if (! utf8_target) Safefree(utf8_p);
7820 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
7821 match = _invlist_contains_cp(only_utf8_locale, c);
7825 if (UNICODE_IS_SUPER(c)
7826 && (flags & ANYOF_WARN_SUPER)
7827 && ckWARN_d(WARN_NON_UNICODE))
7829 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7830 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
7834 #if ANYOF_INVERT != 1
7835 /* Depending on compiler optimization cBOOL takes time, so if don't have to
7837 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
7840 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
7841 return (flags & ANYOF_INVERT) ^ match;
7845 S_reghop3(U8 *s, SSize_t off, const U8* lim)
7847 /* return the position 'off' UTF-8 characters away from 's', forward if
7848 * 'off' >= 0, backwards if negative. But don't go outside of position
7849 * 'lim', which better be < s if off < 0 */
7853 PERL_ARGS_ASSERT_REGHOP3;
7856 while (off-- && s < lim) {
7857 /* XXX could check well-formedness here */
7862 while (off++ && s > lim) {
7864 if (UTF8_IS_CONTINUED(*s)) {
7865 while (s > lim && UTF8_IS_CONTINUATION(*s))
7868 /* XXX could check well-formedness here */
7875 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
7879 PERL_ARGS_ASSERT_REGHOP4;
7882 while (off-- && s < rlim) {
7883 /* XXX could check well-formedness here */
7888 while (off++ && s > llim) {
7890 if (UTF8_IS_CONTINUED(*s)) {
7891 while (s > llim && UTF8_IS_CONTINUATION(*s))
7894 /* XXX could check well-formedness here */
7900 /* like reghop3, but returns NULL on overrun, rather than returning last
7904 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
7908 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7911 while (off-- && s < lim) {
7912 /* XXX could check well-formedness here */
7919 while (off++ && s > lim) {
7921 if (UTF8_IS_CONTINUED(*s)) {
7922 while (s > lim && UTF8_IS_CONTINUATION(*s))
7925 /* XXX could check well-formedness here */
7934 /* when executing a regex that may have (?{}), extra stuff needs setting
7935 up that will be visible to the called code, even before the current
7936 match has finished. In particular:
7938 * $_ is localised to the SV currently being matched;
7939 * pos($_) is created if necessary, ready to be updated on each call-out
7941 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
7942 isn't set until the current pattern is successfully finished), so that
7943 $1 etc of the match-so-far can be seen;
7944 * save the old values of subbeg etc of the current regex, and set then
7945 to the current string (again, this is normally only done at the end
7950 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
7953 regexp *const rex = ReANY(reginfo->prog);
7954 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
7956 eval_state->rex = rex;
7959 /* Make $_ available to executed code. */
7960 if (reginfo->sv != DEFSV) {
7962 DEFSV_set(reginfo->sv);
7965 if (!(mg = mg_find_mglob(reginfo->sv))) {
7966 /* prepare for quick setting of pos */
7967 mg = sv_magicext_mglob(reginfo->sv);
7970 eval_state->pos_magic = mg;
7971 eval_state->pos = mg->mg_len;
7972 eval_state->pos_flags = mg->mg_flags;
7975 eval_state->pos_magic = NULL;
7977 if (!PL_reg_curpm) {
7978 /* PL_reg_curpm is a fake PMOP that we can attach the current
7979 * regex to and point PL_curpm at, so that $1 et al are visible
7980 * within a /(?{})/. It's just allocated once per interpreter the
7981 * first time its needed */
7982 Newxz(PL_reg_curpm, 1, PMOP);
7985 SV* const repointer = &PL_sv_undef;
7986 /* this regexp is also owned by the new PL_reg_curpm, which
7987 will try to free it. */
7988 av_push(PL_regex_padav, repointer);
7989 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
7990 PL_regex_pad = AvARRAY(PL_regex_padav);
7994 SET_reg_curpm(reginfo->prog);
7995 eval_state->curpm = PL_curpm;
7996 PL_curpm = PL_reg_curpm;
7997 if (RXp_MATCH_COPIED(rex)) {
7998 /* Here is a serious problem: we cannot rewrite subbeg,
7999 since it may be needed if this match fails. Thus
8000 $` inside (?{}) could fail... */
8001 eval_state->subbeg = rex->subbeg;
8002 eval_state->sublen = rex->sublen;
8003 eval_state->suboffset = rex->suboffset;
8004 eval_state->subcoffset = rex->subcoffset;
8006 eval_state->saved_copy = rex->saved_copy;
8008 RXp_MATCH_COPIED_off(rex);
8011 eval_state->subbeg = NULL;
8012 rex->subbeg = (char *)reginfo->strbeg;
8014 rex->subcoffset = 0;
8015 rex->sublen = reginfo->strend - reginfo->strbeg;
8019 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8022 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8025 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8026 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8029 Safefree(aux->poscache);
8033 /* undo the effects of S_setup_eval_state() */
8035 if (eval_state->subbeg) {
8036 regexp * const rex = eval_state->rex;
8037 rex->subbeg = eval_state->subbeg;
8038 rex->sublen = eval_state->sublen;
8039 rex->suboffset = eval_state->suboffset;
8040 rex->subcoffset = eval_state->subcoffset;
8042 rex->saved_copy = eval_state->saved_copy;
8044 RXp_MATCH_COPIED_on(rex);
8046 if (eval_state->pos_magic)
8048 eval_state->pos_magic->mg_len = eval_state->pos;
8049 eval_state->pos_magic->mg_flags =
8050 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8051 | (eval_state->pos_flags & MGf_BYTES);
8054 PL_curpm = eval_state->curpm;
8057 PL_regmatch_state = aux->old_regmatch_state;
8058 PL_regmatch_slab = aux->old_regmatch_slab;
8060 /* free all slabs above current one - this must be the last action
8061 * of this function, as aux and eval_state are allocated within
8062 * slabs and may be freed here */
8064 s = PL_regmatch_slab->next;
8066 PL_regmatch_slab->next = NULL;
8068 regmatch_slab * const osl = s;
8077 S_to_utf8_substr(pTHX_ regexp *prog)
8079 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8080 * on the converted value */
8084 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8087 if (prog->substrs->data[i].substr
8088 && !prog->substrs->data[i].utf8_substr) {
8089 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8090 prog->substrs->data[i].utf8_substr = sv;
8091 sv_utf8_upgrade(sv);
8092 if (SvVALID(prog->substrs->data[i].substr)) {
8093 if (SvTAIL(prog->substrs->data[i].substr)) {
8094 /* Trim the trailing \n that fbm_compile added last
8096 SvCUR_set(sv, SvCUR(sv) - 1);
8097 /* Whilst this makes the SV technically "invalid" (as its
8098 buffer is no longer followed by "\0") when fbm_compile()
8099 adds the "\n" back, a "\0" is restored. */
8100 fbm_compile(sv, FBMcf_TAIL);
8104 if (prog->substrs->data[i].substr == prog->check_substr)
8105 prog->check_utf8 = sv;
8111 S_to_byte_substr(pTHX_ regexp *prog)
8113 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8114 * on the converted value; returns FALSE if can't be converted. */
8119 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8122 if (prog->substrs->data[i].utf8_substr
8123 && !prog->substrs->data[i].substr) {
8124 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
8125 if (! sv_utf8_downgrade(sv, TRUE)) {
8128 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
8129 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
8130 /* Trim the trailing \n that fbm_compile added last
8132 SvCUR_set(sv, SvCUR(sv) - 1);
8133 fbm_compile(sv, FBMcf_TAIL);
8137 prog->substrs->data[i].substr = sv;
8138 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
8139 prog->check_substr = sv;
8148 * c-indentation-style: bsd
8150 * indent-tabs-mode: nil
8153 * ex: set ts=8 sts=4 sw=4 et: