5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
78 #ifdef PERL_IN_XSUB_RE
84 #include "inline_invlist.c"
85 #include "unicode_constants.h"
88 /* At least one required character in the target string is expressible only in
90 static const char* const non_utf8_target_but_utf8_required
91 = "Can't match, because target string needs to be in UTF-8\n";
94 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
95 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
99 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
102 #define STATIC static
105 /* Valid only for non-utf8 strings: avoids the reginclass
106 * call if there are no complications: i.e., if everything matchable is
107 * straight forward in the bitmap */
108 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
109 : ANYOF_BITMAP_TEST(p,*(c)))
115 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
116 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
118 #define HOPc(pos,off) \
119 (char *)(reginfo->is_utf8_target \
120 ? reghop3((U8*)pos, off, \
121 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
124 #define HOPBACKc(pos, off) \
125 (char*)(reginfo->is_utf8_target \
126 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
127 : (pos - off >= reginfo->strbeg) \
131 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
132 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
134 /* lim must be +ve. Returns NULL on overshoot */
135 #define HOPMAYBE3(pos,off,lim) \
136 (reginfo->is_utf8_target \
137 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
138 : ((U8*)pos + off <= lim) \
142 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
143 * off must be >=0; args should be vars rather than expressions */
144 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
145 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
146 : (U8*)((pos + off) > lim ? lim : (pos + off)))
148 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
149 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
151 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
153 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
154 #define NEXTCHR_IS_EOS (nextchr < 0)
156 #define SET_nextchr \
157 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
159 #define SET_locinput(p) \
164 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
166 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
167 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
168 1, 0, invlist, &flags); \
173 /* If in debug mode, we test that a known character properly matches */
175 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
178 utf8_char_in_property) \
179 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
180 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
182 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
185 utf8_char_in_property) \
186 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
189 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
190 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
192 PL_XPosix_ptrs[_CC_WORDCHAR], \
193 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
195 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
197 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_regular_begin, \
198 "_X_regular_begin", \
200 LATIN_CAPITAL_LETTER_SHARP_S_UTF8); \
201 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_extend, \
204 COMBINING_GRAVE_ACCENT_UTF8); \
207 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
208 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
210 /* for use after a quantifier and before an EXACT-like node -- japhy */
211 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
213 * NOTE that *nothing* that affects backtracking should be in here, specifically
214 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
215 * node that is in between two EXACT like nodes when ascertaining what the required
216 * "follow" character is. This should probably be moved to regex compile time
217 * although it may be done at run time beause of the REF possibility - more
218 * investigation required. -- demerphq
220 #define JUMPABLE(rn) ( \
222 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
224 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
225 OP(rn) == PLUS || OP(rn) == MINMOD || \
227 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
229 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
231 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
234 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
235 we don't need this definition. */
236 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
237 #define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFA || OP(rn)==EXACTFA_NO_TRIE || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
238 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
241 /* ... so we use this as its faster. */
242 #define IS_TEXT(rn) ( OP(rn)==EXACT )
243 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
244 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
245 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
250 Search for mandatory following text node; for lookahead, the text must
251 follow but for lookbehind (rn->flags != 0) we skip to the next step.
253 #define FIND_NEXT_IMPT(rn) STMT_START { \
254 while (JUMPABLE(rn)) { \
255 const OPCODE type = OP(rn); \
256 if (type == SUSPEND || PL_regkind[type] == CURLY) \
257 rn = NEXTOPER(NEXTOPER(rn)); \
258 else if (type == PLUS) \
260 else if (type == IFMATCH) \
261 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
262 else rn += NEXT_OFF(rn); \
266 /* These constants are for finding GCB=LV and GCB=LVT in the CLUMP regnode.
267 * These are for the pre-composed Hangul syllables, which are all in a
268 * contiguous block and arranged there in such a way so as to facilitate
269 * alorithmic determination of their characteristics. As such, they don't need
270 * a swash, but can be determined by simple arithmetic. Almost all are
271 * GCB=LVT, but every 28th one is a GCB=LV */
272 #define SBASE 0xAC00 /* Start of block */
273 #define SCount 11172 /* Length of block */
276 #define SLAB_FIRST(s) (&(s)->states[0])
277 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
279 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
280 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
281 static regmatch_state * S_push_slab(pTHX);
283 #define REGCP_PAREN_ELEMS 3
284 #define REGCP_OTHER_ELEMS 3
285 #define REGCP_FRAME_ELEMS 1
286 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
287 * are needed for the regexp context stack bookkeeping. */
290 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
293 const int retval = PL_savestack_ix;
294 const int paren_elems_to_push =
295 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
296 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
297 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
299 GET_RE_DEBUG_FLAGS_DECL;
301 PERL_ARGS_ASSERT_REGCPPUSH;
303 if (paren_elems_to_push < 0)
304 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %i",
305 paren_elems_to_push, maxopenparen, parenfloor, REGCP_PAREN_ELEMS);
307 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
308 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
309 " out of range (%lu-%ld)",
311 (unsigned long)maxopenparen,
314 SSGROW(total_elems + REGCP_FRAME_ELEMS);
317 if ((int)maxopenparen > (int)parenfloor)
318 PerlIO_printf(Perl_debug_log,
319 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
324 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
325 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
326 SSPUSHIV(rex->offs[p].end);
327 SSPUSHIV(rex->offs[p].start);
328 SSPUSHINT(rex->offs[p].start_tmp);
329 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
330 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
332 (IV)rex->offs[p].start,
333 (IV)rex->offs[p].start_tmp,
337 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
338 SSPUSHINT(maxopenparen);
339 SSPUSHINT(rex->lastparen);
340 SSPUSHINT(rex->lastcloseparen);
341 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
346 /* These are needed since we do not localize EVAL nodes: */
347 #define REGCP_SET(cp) \
349 PerlIO_printf(Perl_debug_log, \
350 " Setting an EVAL scope, savestack=%"IVdf"\n", \
351 (IV)PL_savestack_ix)); \
354 #define REGCP_UNWIND(cp) \
356 if (cp != PL_savestack_ix) \
357 PerlIO_printf(Perl_debug_log, \
358 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
359 (IV)(cp), (IV)PL_savestack_ix)); \
362 #define UNWIND_PAREN(lp, lcp) \
363 for (n = rex->lastparen; n > lp; n--) \
364 rex->offs[n].end = -1; \
365 rex->lastparen = n; \
366 rex->lastcloseparen = lcp;
370 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
375 GET_RE_DEBUG_FLAGS_DECL;
377 PERL_ARGS_ASSERT_REGCPPOP;
379 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
381 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
382 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
383 rex->lastcloseparen = SSPOPINT;
384 rex->lastparen = SSPOPINT;
385 *maxopenparen_p = SSPOPINT;
387 i -= REGCP_OTHER_ELEMS;
388 /* Now restore the parentheses context. */
390 if (i || rex->lastparen + 1 <= rex->nparens)
391 PerlIO_printf(Perl_debug_log,
392 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
397 paren = *maxopenparen_p;
398 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
400 rex->offs[paren].start_tmp = SSPOPINT;
401 rex->offs[paren].start = SSPOPIV;
403 if (paren <= rex->lastparen)
404 rex->offs[paren].end = tmps;
405 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
406 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
408 (IV)rex->offs[paren].start,
409 (IV)rex->offs[paren].start_tmp,
410 (IV)rex->offs[paren].end,
411 (paren > rex->lastparen ? "(skipped)" : ""));
416 /* It would seem that the similar code in regtry()
417 * already takes care of this, and in fact it is in
418 * a better location to since this code can #if 0-ed out
419 * but the code in regtry() is needed or otherwise tests
420 * requiring null fields (pat.t#187 and split.t#{13,14}
421 * (as of patchlevel 7877) will fail. Then again,
422 * this code seems to be necessary or otherwise
423 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
424 * --jhi updated by dapm */
425 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
426 if (i > *maxopenparen_p)
427 rex->offs[i].start = -1;
428 rex->offs[i].end = -1;
429 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
430 " \\%"UVuf": %s ..-1 undeffing\n",
432 (i > *maxopenparen_p) ? "-1" : " "
438 /* restore the parens and associated vars at savestack position ix,
439 * but without popping the stack */
442 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
444 I32 tmpix = PL_savestack_ix;
445 PL_savestack_ix = ix;
446 regcppop(rex, maxopenparen_p);
447 PL_savestack_ix = tmpix;
450 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
453 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
455 /* Returns a boolean as to whether or not 'character' is a member of the
456 * Posix character class given by 'classnum' that should be equivalent to a
457 * value in the typedef '_char_class_number'.
459 * Ideally this could be replaced by a just an array of function pointers
460 * to the C library functions that implement the macros this calls.
461 * However, to compile, the precise function signatures are required, and
462 * these may vary from platform to to platform. To avoid having to figure
463 * out what those all are on each platform, I (khw) am using this method,
464 * which adds an extra layer of function call overhead (unless the C
465 * optimizer strips it away). But we don't particularly care about
466 * performance with locales anyway. */
468 switch ((_char_class_number) classnum) {
469 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
470 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
471 case _CC_ENUM_ASCII: return isASCII_LC(character);
472 case _CC_ENUM_BLANK: return isBLANK_LC(character);
473 case _CC_ENUM_CASED: return isLOWER_LC(character)
474 || isUPPER_LC(character);
475 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
476 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
477 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
478 case _CC_ENUM_LOWER: return isLOWER_LC(character);
479 case _CC_ENUM_PRINT: return isPRINT_LC(character);
480 case _CC_ENUM_PSXSPC: return isPSXSPC_LC(character);
481 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
482 case _CC_ENUM_SPACE: return isSPACE_LC(character);
483 case _CC_ENUM_UPPER: return isUPPER_LC(character);
484 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
485 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
486 default: /* VERTSPACE should never occur in locales */
487 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
490 assert(0); /* NOTREACHED */
495 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
497 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
498 * 'character' is a member of the Posix character class given by 'classnum'
499 * that should be equivalent to a value in the typedef
500 * '_char_class_number'.
502 * This just calls isFOO_lc on the code point for the character if it is in
503 * the range 0-255. Outside that range, all characters avoid Unicode
504 * rules, ignoring any locale. So use the Unicode function if this class
505 * requires a swash, and use the Unicode macro otherwise. */
507 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
509 if (UTF8_IS_INVARIANT(*character)) {
510 return isFOO_lc(classnum, *character);
512 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
513 return isFOO_lc(classnum,
514 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
517 if (classnum < _FIRST_NON_SWASH_CC) {
519 /* Initialize the swash unless done already */
520 if (! PL_utf8_swash_ptrs[classnum]) {
521 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
522 PL_utf8_swash_ptrs[classnum] =
523 _core_swash_init("utf8",
526 PL_XPosix_ptrs[classnum], &flags);
529 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
531 TRUE /* is UTF */ ));
534 switch ((_char_class_number) classnum) {
536 case _CC_ENUM_PSXSPC: return is_XPERLSPACE_high(character);
538 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
539 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
540 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
541 default: return 0; /* Things like CNTRL are always
545 assert(0); /* NOTREACHED */
550 * pregexec and friends
553 #ifndef PERL_IN_XSUB_RE
555 - pregexec - match a regexp against a string
558 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
559 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
560 /* stringarg: the point in the string at which to begin matching */
561 /* strend: pointer to null at end of string */
562 /* strbeg: real beginning of string */
563 /* minend: end of match must be >= minend bytes after stringarg. */
564 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
565 * itself is accessed via the pointers above */
566 /* nosave: For optimizations. */
568 PERL_ARGS_ASSERT_PREGEXEC;
571 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
572 nosave ? 0 : REXEC_COPY_STR);
578 /* re_intuit_start():
580 * Based on some optimiser hints, try to find the earliest position in the
581 * string where the regex could match.
583 * rx: the regex to match against
584 * sv: the SV being matched: only used for utf8 flag; the string
585 * itself is accessed via the pointers below. Note that on
586 * something like an overloaded SV, SvPOK(sv) may be false
587 * and the string pointers may point to something unrelated to
589 * strbeg: real beginning of string
590 * strpos: the point in the string at which to begin matching
591 * strend: pointer to the byte following the last char of the string
592 * flags currently unused; set to 0
593 * data: currently unused; set to NULL
595 * The basic idea of re_intuit_start() is to use some known information
596 * about the pattern, namely:
598 * a) the longest known anchored substring (i.e. one that's at a
599 * constant offset from the beginning of the pattern; but not
600 * necessarily at a fixed offset from the beginning of the
602 * b) the longest floating substring (i.e. one that's not at a constant
603 * offset from the beginning of the pattern);
604 * c) Whether the pattern is anchored to the string; either
605 * an absolute anchor: /^../, or anchored to \n: /^.../m,
606 * or anchored to pos(): /\G/;
607 * d) A start class: a real or synthetic character class which
608 * represents which characters are legal at the start of the pattern;
610 * to either quickly reject the match, or to find the earliest position
611 * within the string at which the pattern might match, thus avoiding
612 * running the full NFA engine at those earlier locations, only to
613 * eventually fail and retry further along.
615 * Returns NULL if the pattern can't match, or returns the address within
616 * the string which is the earliest place the match could occur.
618 * The longest of the anchored and floating substrings is called 'check'
619 * and is checked first. The other is called 'other' and is checked
620 * second. The 'other' substring may not be present. For example,
622 * /(abc|xyz)ABC\d{0,3}DEFG/
626 * check substr (float) = "DEFG", offset 6..9 chars
627 * other substr (anchored) = "ABC", offset 3..3 chars
630 * Be aware that during the course of this function, sometimes 'anchored'
631 * refers to a substring being anchored relative to the start of the
632 * pattern, and sometimes to the pattern itself being anchored relative to
633 * the string. For example:
635 * /\dabc/: "abc" is anchored to the pattern;
636 * /^\dabc/: "abc" is anchored to the pattern and the string;
637 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
638 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
639 * but the pattern is anchored to the string.
643 Perl_re_intuit_start(pTHX_
646 const char * const strbeg,
650 re_scream_pos_data *data)
653 struct regexp *const prog = ReANY(rx);
654 SSize_t start_shift = prog->check_offset_min;
655 /* Should be nonnegative! */
656 SSize_t end_shift = 0;
657 /* current lowest pos in string where the regex can start matching */
658 char *rx_origin = strpos;
660 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
661 U8 other_ix = 1 - prog->substrs->check_ix;
663 char *other_last = strpos;/* latest pos 'other' substr already checked to */
664 char *check_at = NULL; /* check substr found at this pos */
665 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
666 RXi_GET_DECL(prog,progi);
667 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
668 regmatch_info *const reginfo = ®info_buf;
669 GET_RE_DEBUG_FLAGS_DECL;
671 PERL_ARGS_ASSERT_RE_INTUIT_START;
672 PERL_UNUSED_ARG(flags);
673 PERL_UNUSED_ARG(data);
675 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
676 "Intuit: trying to determine minimum start position...\n"));
678 /* for now, assume that all substr offsets are positive. If at some point
679 * in the future someone wants to do clever things with look-behind and
680 * -ve offsets, they'll need to fix up any code in this function
681 * which uses these offsets. See the thread beginning
682 * <20140113145929.GF27210@iabyn.com>
684 assert(prog->substrs->data[0].min_offset >= 0);
685 assert(prog->substrs->data[0].max_offset >= 0);
686 assert(prog->substrs->data[1].min_offset >= 0);
687 assert(prog->substrs->data[1].max_offset >= 0);
688 assert(prog->substrs->data[2].min_offset >= 0);
689 assert(prog->substrs->data[2].max_offset >= 0);
691 /* for now, assume that if both present, that the floating substring
692 * doesn't start before the anchored substring.
693 * If you break this assumption (e.g. doing better optimisations
694 * with lookahead/behind), then you'll need to audit the code in this
695 * function carefully first
698 ! ( (prog->anchored_utf8 || prog->anchored_substr)
699 && (prog->float_utf8 || prog->float_substr))
700 || (prog->float_min_offset >= prog->anchored_offset));
702 /* byte rather than char calculation for efficiency. It fails
703 * to quickly reject some cases that can't match, but will reject
704 * them later after doing full char arithmetic */
705 if (prog->minlen > strend - strpos) {
706 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
707 " String too short...\n"));
711 reginfo->is_utf8_target = cBOOL(utf8_target);
712 reginfo->info_aux = NULL;
713 reginfo->strbeg = strbeg;
714 reginfo->strend = strend;
715 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
717 /* not actually used within intuit, but zero for safety anyway */
718 reginfo->poscache_maxiter = 0;
721 if (!prog->check_utf8 && prog->check_substr)
722 to_utf8_substr(prog);
723 check = prog->check_utf8;
725 if (!prog->check_substr && prog->check_utf8) {
726 if (! to_byte_substr(prog)) {
727 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
730 check = prog->check_substr;
733 /* dump the various substring data */
734 DEBUG_OPTIMISE_MORE_r({
736 for (i=0; i<=2; i++) {
737 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
738 : prog->substrs->data[i].substr);
742 PerlIO_printf(Perl_debug_log,
743 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
744 " useful=%"IVdf" utf8=%d [%s]\n",
746 (IV)prog->substrs->data[i].min_offset,
747 (IV)prog->substrs->data[i].max_offset,
748 (IV)prog->substrs->data[i].end_shift,
755 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
757 /* ml_anch: check after \n?
759 * A note about IMPLICIT: on an un-anchored pattern beginning
760 * with /.*.../, these flags will have been added by the
762 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
763 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
765 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
766 && !(prog->intflags & PREGf_IMPLICIT);
768 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
769 /* we are only allowed to match at BOS or \G */
771 /* trivially reject if there's a BOS anchor and we're not at BOS.
773 * Note that we don't try to do a similar quick reject for
774 * \G, since generally the caller will have calculated strpos
775 * based on pos() and gofs, so the string is already correctly
776 * anchored by definition; and handling the exceptions would
777 * be too fiddly (e.g. REXEC_IGNOREPOS).
779 if ( strpos != strbeg
780 && (prog->intflags & (PREGf_ANCH_BOL|PREGf_ANCH_SBOL)))
782 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
783 " Not at start...\n"));
787 /* in the presence of an anchor, the anchored (relative to the
788 * start of the regex) substr must also be anchored relative
789 * to strpos. So quickly reject if substr isn't found there.
790 * This works for \G too, because the caller will already have
791 * subtracted gofs from pos, and gofs is the offset from the
792 * \G to the start of the regex. For example, in /.abc\Gdef/,
793 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
794 * caller will have set strpos=pos()-4; we look for the substr
795 * at position pos()-4+1, which lines up with the "a" */
797 if (prog->check_offset_min == prog->check_offset_max
798 && !(prog->intflags & PREGf_CANY_SEEN))
800 /* Substring at constant offset from beg-of-str... */
801 SSize_t slen = SvCUR(check);
802 char *s = HOP3c(strpos, prog->check_offset_min, strend);
804 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
805 " Looking for check substr at fixed offset %"IVdf"...\n",
806 (IV)prog->check_offset_min));
809 /* In this case, the regex is anchored at the end too.
810 * Unless it's a multiline match, the lengths must match
811 * exactly, give or take a \n. NB: slen >= 1 since
812 * the last char of check is \n */
814 && ( strend - s > slen
815 || strend - s < slen - 1
816 || (strend - s == slen && strend[-1] != '\n')))
818 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
819 " String too long...\n"));
822 /* Now should match s[0..slen-2] */
825 if (slen && (*SvPVX_const(check) != *s
826 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
828 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
829 " String not equal...\n"));
834 goto success_at_start;
839 end_shift = prog->check_end_shift;
841 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
843 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
844 (IV)end_shift, RX_PRECOMP(prog));
849 /* This is the (re)entry point of the main loop in this function.
850 * The goal of this loop is to:
851 * 1) find the "check" substring in the region rx_origin..strend
852 * (adjusted by start_shift / end_shift). If not found, reject
854 * 2) If it exists, look for the "other" substr too if defined; for
855 * example, if the check substr maps to the anchored substr, then
856 * check the floating substr, and vice-versa. If not found, go
857 * back to (1) with rx_origin suitably incremented.
858 * 3) If we find an rx_origin position that doesn't contradict
859 * either of the substrings, then check the possible additional
860 * constraints on rx_origin of /^.../m or a known start class.
861 * If these fail, then depending on which constraints fail, jump
862 * back to here, or to various other re-entry points further along
863 * that skip some of the first steps.
864 * 4) If we pass all those tests, update the BmUSEFUL() count on the
865 * substring. If the start position was determined to be at the
866 * beginning of the string - so, not rejected, but not optimised,
867 * since we have to run regmatch from position 0 - decrement the
868 * BmUSEFUL() count. Otherwise increment it.
872 /* first, look for the 'check' substring */
878 DEBUG_OPTIMISE_MORE_r({
879 PerlIO_printf(Perl_debug_log,
880 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
881 " Start shift: %"IVdf" End shift %"IVdf
882 " Real end Shift: %"IVdf"\n",
883 (IV)(rx_origin - strpos),
884 (IV)prog->check_offset_min,
887 (IV)prog->check_end_shift);
890 if (prog->intflags & PREGf_CANY_SEEN) {
891 start_point= (U8*)(rx_origin + start_shift);
892 end_point= (U8*)(strend - end_shift);
893 if (start_point > end_point)
896 end_point = HOP3(strend, -end_shift, strbeg);
897 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
903 /* If the regex is absolutely anchored to either the start of the
904 * string (BOL,SBOL) or to pos() (ANCH_GPOS), then
905 * check_offset_max represents an upper bound on the string where
906 * the substr could start. For the ANCH_GPOS case, we assume that
907 * the caller of intuit will have already set strpos to
908 * pos()-gofs, so in this case strpos + offset_max will still be
909 * an upper bound on the substr.
912 && prog->intflags & PREGf_ANCH
913 && prog->check_offset_max != SSize_t_MAX)
915 SSize_t len = SvCUR(check) - !!SvTAIL(check);
916 const char * const anchor =
917 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
919 /* do a bytes rather than chars comparison. It's conservative;
920 * so it skips doing the HOP if the result can't possibly end
921 * up earlier than the old value of end_point.
923 if ((char*)end_point - anchor > prog->check_offset_max) {
924 end_point = HOP3lim((U8*)anchor,
925 prog->check_offset_max,
931 DEBUG_OPTIMISE_MORE_r({
932 PerlIO_printf(Perl_debug_log, " fbm_instr len=%d str=<%.*s>\n",
933 (int)(end_point - start_point),
934 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
938 check_at = fbm_instr( start_point, end_point,
939 check, multiline ? FBMrf_MULTILINE : 0);
941 /* Update the count-of-usability, remove useless subpatterns,
945 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
946 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
947 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
948 (check_at ? "Found" : "Did not find"),
949 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
950 ? "anchored" : "floating"),
953 (check_at ? " at offset " : "...\n") );
958 /* Finish the diagnostic message */
959 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(check_at - strpos)) );
961 /* set rx_origin to the minimum position where the regex could start
962 * matching, given the constraint of the just-matched check substring.
963 * But don't set it lower than previously.
966 if (check_at - rx_origin > prog->check_offset_max)
967 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
971 /* now look for the 'other' substring if defined */
973 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
974 : prog->substrs->data[other_ix].substr)
976 /* Take into account the "other" substring. */
980 struct reg_substr_datum *other;
983 other = &prog->substrs->data[other_ix];
985 /* if "other" is anchored:
986 * we've previously found a floating substr starting at check_at.
987 * This means that the regex origin must lie somewhere
988 * between min (rx_origin): HOP3(check_at, -check_offset_max)
989 * and max: HOP3(check_at, -check_offset_min)
990 * (except that min will be >= strpos)
991 * So the fixed substr must lie somewhere between
992 * HOP3(min, anchored_offset)
993 * HOP3(max, anchored_offset) + SvCUR(substr)
996 /* if "other" is floating
997 * Calculate last1, the absolute latest point where the
998 * floating substr could start in the string, ignoring any
999 * constraints from the earlier fixed match. It is calculated
1002 * strend - prog->minlen (in chars) is the absolute latest
1003 * position within the string where the origin of the regex
1004 * could appear. The latest start point for the floating
1005 * substr is float_min_offset(*) on from the start of the
1006 * regex. last1 simply combines thee two offsets.
1008 * (*) You might think the latest start point should be
1009 * float_max_offset from the regex origin, and technically
1010 * you'd be correct. However, consider
1012 * Here, float min, max are 3,5 and minlen is 7.
1013 * This can match either
1017 * In the first case, the regex matches minlen chars; in the
1018 * second, minlen+1, in the third, minlen+2.
1019 * In the first case, the floating offset is 3 (which equals
1020 * float_min), in the second, 4, and in the third, 5 (which
1021 * equals float_max). In all cases, the floating string bcd
1022 * can never start more than 4 chars from the end of the
1023 * string, which equals minlen - float_min. As the substring
1024 * starts to match more than float_min from the start of the
1025 * regex, it makes the regex match more than minlen chars,
1026 * and the two cancel each other out. So we can always use
1027 * float_min - minlen, rather than float_max - minlen for the
1028 * latest position in the string.
1030 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1031 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1034 assert(prog->minlen >= other->min_offset);
1035 last1 = HOP3c(strend,
1036 other->min_offset - prog->minlen, strbeg);
1038 if (other_ix) {/* i.e. if (other-is-float) */
1039 /* last is the latest point where the floating substr could
1040 * start, *given* any constraints from the earlier fixed
1041 * match. This constraint is that the floating string starts
1042 * <= float_max_offset chars from the regex origin (rx_origin).
1043 * If this value is less than last1, use it instead.
1045 assert(rx_origin <= last1);
1047 /* this condition handles the offset==infinity case, and
1048 * is a short-cut otherwise. Although it's comparing a
1049 * byte offset to a char length, it does so in a safe way,
1050 * since 1 char always occupies 1 or more bytes,
1051 * so if a string range is (last1 - rx_origin) bytes,
1052 * it will be less than or equal to (last1 - rx_origin)
1053 * chars; meaning it errs towards doing the accurate HOP3
1054 * rather than just using last1 as a short-cut */
1055 (last1 - rx_origin) < other->max_offset
1057 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1060 assert(strpos + start_shift <= check_at);
1061 last = HOP4c(check_at, other->min_offset - start_shift,
1065 s = HOP3c(rx_origin, other->min_offset, strend);
1066 if (s < other_last) /* These positions already checked */
1069 must = utf8_target ? other->utf8_substr : other->substr;
1070 assert(SvPOK(must));
1073 (unsigned char*)last + SvCUR(must) - (SvTAIL(must)!=0),
1075 multiline ? FBMrf_MULTILINE : 0
1078 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1079 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1080 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1081 s ? "Found" : "Contradicts",
1082 other_ix ? "floating" : "anchored",
1083 quoted, RE_SV_TAIL(must));
1088 /* last1 is latest possible substr location. If we didn't
1089 * find it before there, we never will */
1090 if (last >= last1) {
1091 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1092 ", giving up...\n"));
1096 /* try to find the check substr again at a later
1097 * position. Maybe next time we'll find the "other" substr
1099 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1100 ", trying %s at offset %ld...\n",
1101 (other_ix ? "floating" : "anchored"),
1102 (long)(HOP3c(check_at, 1, strend) - strpos)));
1104 other_last = HOP3c(last, 1, strend) /* highest failure */;
1106 other_ix /* i.e. if other-is-float */
1107 ? HOP3c(rx_origin, 1, strend)
1108 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1112 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
1113 (long)(s - strpos)));
1115 if (other_ix) { /* if (other-is-float) */
1116 /* other_last is set to s, not s+1, since its possible for
1117 * a floating substr to fail first time, then succeed
1118 * second time at the same floating position; e.g.:
1119 * "-AB--AABZ" =~ /\wAB\d*Z/
1120 * The first time round, anchored and float match at
1121 * "-(AB)--AAB(Z)" then fail on the initial \w character
1122 * class. Second time round, they match at "-AB--A(AB)(Z)".
1127 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1128 other_last = HOP3c(s, 1, strend);
1133 DEBUG_OPTIMISE_MORE_r(
1134 PerlIO_printf(Perl_debug_log,
1135 " Check-only match: offset min:%"IVdf" max:%"IVdf
1136 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1137 " strend-strpos:%"IVdf"\n",
1138 (IV)prog->check_offset_min,
1139 (IV)prog->check_offset_max,
1140 (IV)(check_at-strpos),
1141 (IV)(rx_origin-strpos),
1142 (IV)(rx_origin-check_at),
1148 postprocess_substr_matches:
1150 /* handle the extra constraint of /^.../m if present */
1152 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1155 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1156 " looking for /^/m anchor"));
1158 /* we have failed the constraint of a \n before rx_origin.
1159 * Find the next \n, if any, even if it's beyond the current
1160 * anchored and/or floating substrings. Whether we should be
1161 * scanning ahead for the next \n or the next substr is debatable.
1162 * On the one hand you'd expect rare substrings to appear less
1163 * often than \n's. On the other hand, searching for \n means
1164 * we're effectively flipping been check_substr and "\n" on each
1165 * iteration as the current "rarest" string candidate, which
1166 * means for example that we'll quickly reject the whole string if
1167 * hasn't got a \n, rather than trying every substr position
1171 s = HOP3c(strend, - prog->minlen, strpos);
1172 if (s <= rx_origin ||
1173 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1175 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1176 " Did not find /%s^%s/m...\n",
1177 PL_colors[0], PL_colors[1]));
1181 /* earliest possible origin is 1 char after the \n.
1182 * (since *rx_origin == '\n', it's safe to ++ here rather than
1183 * HOP(rx_origin, 1)) */
1186 if (prog->substrs->check_ix == 0 /* check is anchored */
1187 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1189 /* Position contradicts check-string; either because
1190 * check was anchored (and thus has no wiggle room),
1191 * or check was float and rx_origin is above the float range */
1192 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1193 " Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
1194 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
1198 /* if we get here, the check substr must have been float,
1199 * is in range, and we may or may not have had an anchored
1200 * "other" substr which still contradicts */
1201 assert(prog->substrs->check_ix); /* check is float */
1203 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1204 /* whoops, the anchored "other" substr exists, so we still
1205 * contradict. On the other hand, the float "check" substr
1206 * didn't contradict, so just retry the anchored "other"
1208 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1209 " Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
1210 PL_colors[0], PL_colors[1],
1211 (long)(rx_origin - strpos),
1212 (long)(rx_origin - strpos + prog->anchored_offset)));
1213 goto do_other_substr;
1216 /* success: we don't contradict the found floating substring
1217 * (and there's no anchored substr). */
1218 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1219 " Found /%s^%s/m at offset %ld...\n",
1220 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
1223 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1224 " (multiline anchor test skipped)\n"));
1230 /* if we have a starting character class, then test that extra constraint.
1231 * (trie stclasses are too expensive to use here, we are better off to
1232 * leave it to regmatch itself) */
1234 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1235 const U8* const str = (U8*)STRING(progi->regstclass);
1237 /* XXX this value could be pre-computed */
1238 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1239 ? (reginfo->is_utf8_pat
1240 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1241 : STR_LEN(progi->regstclass))
1245 /* latest pos that a matching float substr constrains rx start to */
1246 char *rx_max_float = NULL;
1248 /* if the current rx_origin is anchored, either by satisfying an
1249 * anchored substring constraint, or a /^.../m constraint, then we
1250 * can reject the current origin if the start class isn't found
1251 * at the current position. If we have a float-only match, then
1252 * rx_origin is constrained to a range; so look for the start class
1253 * in that range. if neither, then look for the start class in the
1254 * whole rest of the string */
1256 /* XXX DAPM it's not clear what the minlen test is for, and why
1257 * it's not used in the floating case. Nothing in the test suite
1258 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1259 * Here are some old comments, which may or may not be correct:
1261 * minlen == 0 is possible if regstclass is \b or \B,
1262 * and the fixed substr is ''$.
1263 * Since minlen is already taken into account, rx_origin+1 is
1264 * before strend; accidentally, minlen >= 1 guaranties no false
1265 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1266 * 0) below assumes that regstclass does not come from lookahead...
1267 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1268 * This leaves EXACTF-ish only, which are dealt with in
1272 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1273 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1274 else if (prog->float_substr || prog->float_utf8) {
1275 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1276 endpos= HOP3c(rx_max_float, cl_l, strend);
1281 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1282 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1283 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1284 (IV)start_shift, (IV)(check_at - strbeg),
1285 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1287 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1290 if (endpos == strend) {
1291 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1292 " Could not match STCLASS...\n") );
1295 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1296 " This position contradicts STCLASS...\n") );
1297 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1298 && !(prog->intflags & PREGf_IMPLICIT))
1301 /* Contradict one of substrings */
1302 if (prog->anchored_substr || prog->anchored_utf8) {
1303 if (prog->substrs->check_ix == 1) { /* check is float */
1304 /* Have both, check_string is floating */
1305 assert(rx_origin + start_shift <= check_at);
1306 if (rx_origin + start_shift != check_at) {
1307 /* not at latest position float substr could match:
1308 * Recheck anchored substring, but not floating.
1309 * The condition above is in bytes rather than
1310 * chars for efficiency. It's conservative, in
1311 * that it errs on the side of doing 'goto
1312 * do_other_substr', where a more accurate
1313 * char-based calculation will be done */
1314 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1315 " Looking for anchored substr starting at offset %ld...\n",
1316 (long)(other_last - strpos)) );
1317 goto do_other_substr;
1325 /* In the presence of ml_anch, we might be able to
1326 * find another \n without breaking the current float
1329 /* strictly speaking this should be HOP3c(..., 1, ...),
1330 * but since we goto a block of code that's going to
1331 * search for the next \n if any, its safe here */
1333 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1334 " Looking for /%s^%s/m starting at offset %ld...\n",
1335 PL_colors[0], PL_colors[1],
1336 (long)(rx_origin - strpos)) );
1337 goto postprocess_substr_matches;
1340 /* strictly speaking this can never be true; but might
1341 * be if we ever allow intuit without substrings */
1342 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1345 rx_origin = rx_max_float;
1348 /* at this point, any matching substrings have been
1349 * contradicted. Start again... */
1351 rx_origin = HOP3c(rx_origin, 1, strend);
1353 /* uses bytes rather than char calculations for efficiency.
1354 * It's conservative: it errs on the side of doing 'goto restart',
1355 * where there is code that does a proper char-based test */
1356 if (rx_origin + start_shift + end_shift > strend) {
1357 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1358 " Could not match STCLASS...\n") );
1361 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1362 " Looking for %s substr starting at offset %ld...\n",
1363 (prog->substrs->check_ix ? "floating" : "anchored"),
1364 (long)(rx_origin + start_shift - strpos)) );
1370 if (rx_origin != s) {
1371 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1372 " By STCLASS: moving %ld --> %ld\n",
1373 (long)(rx_origin - strpos), (long)(s - strpos))
1377 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1378 " Does not contradict STCLASS...\n");
1383 /* Decide whether using the substrings helped */
1385 if (rx_origin != strpos) {
1386 /* Fixed substring is found far enough so that the match
1387 cannot start at strpos. */
1389 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1390 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1393 /* The found rx_origin position does not prohibit matching at
1394 * strpos, so calling intuit didn't gain us anything. Decrement
1395 * the BmUSEFUL() count on the check substring, and if we reach
1397 if (!(prog->intflags & PREGf_NAUGHTY)
1399 prog->check_utf8 /* Could be deleted already */
1400 && --BmUSEFUL(prog->check_utf8) < 0
1401 && (prog->check_utf8 == prog->float_utf8)
1403 prog->check_substr /* Could be deleted already */
1404 && --BmUSEFUL(prog->check_substr) < 0
1405 && (prog->check_substr == prog->float_substr)
1408 /* If flags & SOMETHING - do not do it many times on the same match */
1409 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1410 /* XXX Does the destruction order has to change with utf8_target? */
1411 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1412 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1413 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1414 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1415 check = NULL; /* abort */
1416 /* XXXX This is a remnant of the old implementation. It
1417 looks wasteful, since now INTUIT can use many
1418 other heuristics. */
1419 prog->extflags &= ~RXf_USE_INTUIT;
1423 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1424 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1425 PL_colors[4], PL_colors[5], (long)(rx_origin - strpos)) );
1429 fail_finish: /* Substring not found */
1430 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1431 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1433 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1434 PL_colors[4], PL_colors[5]));
1439 #define DECL_TRIE_TYPE(scan) \
1440 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1441 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold } \
1442 trie_type = ((scan->flags == EXACT) \
1443 ? (utf8_target ? trie_utf8 : trie_plain) \
1444 : (scan->flags == EXACTFA) \
1445 ? (utf8_target ? trie_utf8_exactfa_fold : trie_latin_utf8_exactfa_fold) \
1446 : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
1448 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1451 U8 flags = FOLD_FLAGS_FULL; \
1452 switch (trie_type) { \
1453 case trie_utf8_exactfa_fold: \
1454 flags |= FOLD_FLAGS_NOMIX_ASCII; \
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);
2590 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2591 reginfo->intuit = 0;
2592 reginfo->is_utf8_target = cBOOL(utf8_target);
2593 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2594 reginfo->warned = FALSE;
2595 reginfo->strbeg = strbeg;
2597 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2598 reginfo->strend = strend;
2599 /* see how far we have to get to not match where we matched before */
2600 reginfo->till = stringarg + minend;
2602 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2603 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2604 S_cleanup_regmatch_info_aux has executed (registered by
2605 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2606 magic belonging to this SV.
2607 Not newSVsv, either, as it does not COW.
2609 assert(!IS_PADGV(sv));
2610 reginfo->sv = newSV(0);
2611 SvSetSV_nosteal(reginfo->sv, sv);
2612 SAVEFREESV(reginfo->sv);
2615 /* reserve next 2 or 3 slots in PL_regmatch_state:
2616 * slot N+0: may currently be in use: skip it
2617 * slot N+1: use for regmatch_info_aux struct
2618 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2619 * slot N+3: ready for use by regmatch()
2623 regmatch_state *old_regmatch_state;
2624 regmatch_slab *old_regmatch_slab;
2625 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2627 /* on first ever match, allocate first slab */
2628 if (!PL_regmatch_slab) {
2629 Newx(PL_regmatch_slab, 1, regmatch_slab);
2630 PL_regmatch_slab->prev = NULL;
2631 PL_regmatch_slab->next = NULL;
2632 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2635 old_regmatch_state = PL_regmatch_state;
2636 old_regmatch_slab = PL_regmatch_slab;
2638 for (i=0; i <= max; i++) {
2640 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2642 reginfo->info_aux_eval =
2643 reginfo->info_aux->info_aux_eval =
2644 &(PL_regmatch_state->u.info_aux_eval);
2646 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2647 PL_regmatch_state = S_push_slab(aTHX);
2650 /* note initial PL_regmatch_state position; at end of match we'll
2651 * pop back to there and free any higher slabs */
2653 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
2654 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
2655 reginfo->info_aux->poscache = NULL;
2657 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
2659 if ((prog->extflags & RXf_EVAL_SEEN))
2660 S_setup_eval_state(aTHX_ reginfo);
2662 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
2665 /* If there is a "must appear" string, look for it. */
2667 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2668 /* We have to be careful. If the previous successful match
2669 was from this regex we don't want a subsequent partially
2670 successful match to clobber the old results.
2671 So when we detect this possibility we add a swap buffer
2672 to the re, and switch the buffer each match. If we fail,
2673 we switch it back; otherwise we leave it swapped.
2676 /* do we need a save destructor here for eval dies? */
2677 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2678 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2679 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2686 /* Simplest case: anchored match need be tried only once. */
2687 /* [unless only anchor is BOL and multiline is set] */
2688 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
2689 if (s == startpos && regtry(reginfo, &s))
2691 else if (multiline || (prog->intflags & (PREGf_IMPLICIT | PREGf_ANCH_MBOL))) /* XXXX SBOL? */
2696 dontbother = minlen - 1;
2697 end = HOP3c(strend, -dontbother, strbeg) - 1;
2698 /* for multiline we only have to try after newlines */
2699 if (prog->check_substr || prog->check_utf8) {
2700 /* because of the goto we can not easily reuse the macros for bifurcating the
2701 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2704 goto after_try_utf8;
2706 if (regtry(reginfo, &s)) {
2713 if (prog->extflags & RXf_USE_INTUIT) {
2714 s = re_intuit_start(rx, sv, strbeg,
2715 s + UTF8SKIP(s), strend, flags, NULL);
2724 } /* end search for check string in unicode */
2726 if (s == startpos) {
2727 goto after_try_latin;
2730 if (regtry(reginfo, &s)) {
2737 if (prog->extflags & RXf_USE_INTUIT) {
2738 s = re_intuit_start(rx, sv, strbeg,
2739 s + 1, strend, flags, NULL);
2748 } /* end search for check string in latin*/
2749 } /* end search for check string */
2750 else { /* search for newline */
2752 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2755 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2756 while (s <= end) { /* note it could be possible to match at the end of the string */
2757 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2758 if (regtry(reginfo, &s))
2762 } /* end search for newline */
2763 } /* end anchored/multiline check string search */
2765 } else if (prog->intflags & PREGf_ANCH_GPOS)
2767 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
2768 assert(prog->intflags & PREGf_GPOS_SEEN);
2769 /* For anchored \G, the only position it can match from is
2770 * (ganch-gofs); we already set startpos to this above; if intuit
2771 * moved us on from there, we can't possibly succeed */
2772 assert(startpos == reginfo->ganch - prog->gofs);
2773 if (s == startpos && regtry(reginfo, &s))
2778 /* Messy cases: unanchored match. */
2779 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2780 /* we have /x+whatever/ */
2781 /* it must be a one character string (XXXX Except is_utf8_pat?) */
2787 if (! prog->anchored_utf8) {
2788 to_utf8_substr(prog);
2790 ch = SvPVX_const(prog->anchored_utf8)[0];
2793 DEBUG_EXECUTE_r( did_match = 1 );
2794 if (regtry(reginfo, &s)) goto got_it;
2796 while (s < strend && *s == ch)
2803 if (! prog->anchored_substr) {
2804 if (! to_byte_substr(prog)) {
2805 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2808 ch = SvPVX_const(prog->anchored_substr)[0];
2811 DEBUG_EXECUTE_r( did_match = 1 );
2812 if (regtry(reginfo, &s)) goto got_it;
2814 while (s < strend && *s == ch)
2819 DEBUG_EXECUTE_r(if (!did_match)
2820 PerlIO_printf(Perl_debug_log,
2821 "Did not find anchored character...\n")
2824 else if (prog->anchored_substr != NULL
2825 || prog->anchored_utf8 != NULL
2826 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2827 && prog->float_max_offset < strend - s)) {
2832 char *last1; /* Last position checked before */
2836 if (prog->anchored_substr || prog->anchored_utf8) {
2838 if (! prog->anchored_utf8) {
2839 to_utf8_substr(prog);
2841 must = prog->anchored_utf8;
2844 if (! prog->anchored_substr) {
2845 if (! to_byte_substr(prog)) {
2846 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2849 must = prog->anchored_substr;
2851 back_max = back_min = prog->anchored_offset;
2854 if (! prog->float_utf8) {
2855 to_utf8_substr(prog);
2857 must = prog->float_utf8;
2860 if (! prog->float_substr) {
2861 if (! to_byte_substr(prog)) {
2862 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2865 must = prog->float_substr;
2867 back_max = prog->float_max_offset;
2868 back_min = prog->float_min_offset;
2874 last = HOP3c(strend, /* Cannot start after this */
2875 -(SSize_t)(CHR_SVLEN(must)
2876 - (SvTAIL(must) != 0) + back_min), strbeg);
2878 if (s > reginfo->strbeg)
2879 last1 = HOPc(s, -1);
2881 last1 = s - 1; /* bogus */
2883 /* XXXX check_substr already used to find "s", can optimize if
2884 check_substr==must. */
2886 strend = HOPc(strend, -dontbother);
2887 while ( (s <= last) &&
2888 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
2889 (unsigned char*)strend, must,
2890 multiline ? FBMrf_MULTILINE : 0)) ) {
2891 DEBUG_EXECUTE_r( did_match = 1 );
2892 if (HOPc(s, -back_max) > last1) {
2893 last1 = HOPc(s, -back_min);
2894 s = HOPc(s, -back_max);
2897 char * const t = (last1 >= reginfo->strbeg)
2898 ? HOPc(last1, 1) : last1 + 1;
2900 last1 = HOPc(s, -back_min);
2904 while (s <= last1) {
2905 if (regtry(reginfo, &s))
2908 s++; /* to break out of outer loop */
2915 while (s <= last1) {
2916 if (regtry(reginfo, &s))
2922 DEBUG_EXECUTE_r(if (!did_match) {
2923 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2924 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2925 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2926 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2927 ? "anchored" : "floating"),
2928 quoted, RE_SV_TAIL(must));
2932 else if ( (c = progi->regstclass) ) {
2934 const OPCODE op = OP(progi->regstclass);
2935 /* don't bother with what can't match */
2936 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2937 strend = HOPc(strend, -(minlen - 1));
2940 SV * const prop = sv_newmortal();
2941 regprop(prog, prop, c, reginfo);
2943 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2945 PerlIO_printf(Perl_debug_log,
2946 "Matching stclass %.*s against %s (%d bytes)\n",
2947 (int)SvCUR(prop), SvPVX_const(prop),
2948 quoted, (int)(strend - s));
2951 if (find_byclass(prog, c, s, strend, reginfo))
2953 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2957 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2965 if (! prog->float_utf8) {
2966 to_utf8_substr(prog);
2968 float_real = prog->float_utf8;
2971 if (! prog->float_substr) {
2972 if (! to_byte_substr(prog)) {
2973 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
2976 float_real = prog->float_substr;
2979 little = SvPV_const(float_real, len);
2980 if (SvTAIL(float_real)) {
2981 /* This means that float_real contains an artificial \n on
2982 * the end due to the presence of something like this:
2983 * /foo$/ where we can match both "foo" and "foo\n" at the
2984 * end of the string. So we have to compare the end of the
2985 * string first against the float_real without the \n and
2986 * then against the full float_real with the string. We
2987 * have to watch out for cases where the string might be
2988 * smaller than the float_real or the float_real without
2990 char *checkpos= strend - len;
2992 PerlIO_printf(Perl_debug_log,
2993 "%sChecking for float_real.%s\n",
2994 PL_colors[4], PL_colors[5]));
2995 if (checkpos + 1 < strbeg) {
2996 /* can't match, even if we remove the trailing \n
2997 * string is too short to match */
2999 PerlIO_printf(Perl_debug_log,
3000 "%sString shorter than required trailing substring, cannot match.%s\n",
3001 PL_colors[4], PL_colors[5]));
3003 } else if (memEQ(checkpos + 1, little, len - 1)) {
3004 /* can match, the end of the string matches without the
3006 last = checkpos + 1;
3007 } else if (checkpos < strbeg) {
3008 /* cant match, string is too short when the "\n" is
3011 PerlIO_printf(Perl_debug_log,
3012 "%sString does not contain required trailing substring, cannot match.%s\n",
3013 PL_colors[4], PL_colors[5]));
3015 } else if (!multiline) {
3016 /* non multiline match, so compare with the "\n" at the
3017 * end of the string */
3018 if (memEQ(checkpos, little, len)) {
3022 PerlIO_printf(Perl_debug_log,
3023 "%sString does not contain required trailing substring, cannot match.%s\n",
3024 PL_colors[4], PL_colors[5]));
3028 /* multiline match, so we have to search for a place
3029 * where the full string is located */
3035 last = rninstr(s, strend, little, little + len);
3037 last = strend; /* matching "$" */
3040 /* at one point this block contained a comment which was
3041 * probably incorrect, which said that this was a "should not
3042 * happen" case. Even if it was true when it was written I am
3043 * pretty sure it is not anymore, so I have removed the comment
3044 * and replaced it with this one. Yves */
3046 PerlIO_printf(Perl_debug_log,
3047 "String does not contain required substring, cannot match.\n"
3051 dontbother = strend - last + prog->float_min_offset;
3053 if (minlen && (dontbother < minlen))
3054 dontbother = minlen - 1;
3055 strend -= dontbother; /* this one's always in bytes! */
3056 /* We don't know much -- general case. */
3059 if (regtry(reginfo, &s))
3068 if (regtry(reginfo, &s))
3070 } while (s++ < strend);
3078 /* s/// doesn't like it if $& is earlier than where we asked it to
3079 * start searching (which can happen on something like /.\G/) */
3080 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3081 && (prog->offs[0].start < stringarg - strbeg))
3083 /* this should only be possible under \G */
3084 assert(prog->intflags & PREGf_GPOS_SEEN);
3085 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3086 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3092 PerlIO_printf(Perl_debug_log,
3093 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3100 /* clean up; this will trigger destructors that will free all slabs
3101 * above the current one, and cleanup the regmatch_info_aux
3102 * and regmatch_info_aux_eval sructs */
3104 LEAVE_SCOPE(oldsave);
3106 if (RXp_PAREN_NAMES(prog))
3107 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3109 RX_MATCH_UTF8_set(rx, utf8_target);
3111 /* make sure $`, $&, $', and $digit will work later */
3112 if ( !(flags & REXEC_NOT_FIRST) )
3113 S_reg_set_capture_string(aTHX_ rx,
3114 strbeg, reginfo->strend,
3115 sv, flags, utf8_target);
3120 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3121 PL_colors[4], PL_colors[5]));
3123 /* clean up; this will trigger destructors that will free all slabs
3124 * above the current one, and cleanup the regmatch_info_aux
3125 * and regmatch_info_aux_eval sructs */
3127 LEAVE_SCOPE(oldsave);
3130 /* we failed :-( roll it back */
3131 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3132 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3137 Safefree(prog->offs);
3144 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3145 * Do inc before dec, in case old and new rex are the same */
3146 #define SET_reg_curpm(Re2) \
3147 if (reginfo->info_aux_eval) { \
3148 (void)ReREFCNT_inc(Re2); \
3149 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3150 PM_SETRE((PL_reg_curpm), (Re2)); \
3155 - regtry - try match at specific point
3157 STATIC I32 /* 0 failure, 1 success */
3158 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3162 REGEXP *const rx = reginfo->prog;
3163 regexp *const prog = ReANY(rx);
3165 RXi_GET_DECL(prog,progi);
3166 GET_RE_DEBUG_FLAGS_DECL;
3168 PERL_ARGS_ASSERT_REGTRY;
3170 reginfo->cutpoint=NULL;
3172 prog->offs[0].start = *startposp - reginfo->strbeg;
3173 prog->lastparen = 0;
3174 prog->lastcloseparen = 0;
3176 /* XXXX What this code is doing here?!!! There should be no need
3177 to do this again and again, prog->lastparen should take care of
3180 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3181 * Actually, the code in regcppop() (which Ilya may be meaning by
3182 * prog->lastparen), is not needed at all by the test suite
3183 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3184 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3185 * Meanwhile, this code *is* needed for the
3186 * above-mentioned test suite tests to succeed. The common theme
3187 * on those tests seems to be returning null fields from matches.
3188 * --jhi updated by dapm */
3190 if (prog->nparens) {
3191 regexp_paren_pair *pp = prog->offs;
3193 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3201 result = regmatch(reginfo, *startposp, progi->program + 1);
3203 prog->offs[0].end = result;
3206 if (reginfo->cutpoint)
3207 *startposp= reginfo->cutpoint;
3208 REGCP_UNWIND(lastcp);
3213 #define sayYES goto yes
3214 #define sayNO goto no
3215 #define sayNO_SILENT goto no_silent
3217 /* we dont use STMT_START/END here because it leads to
3218 "unreachable code" warnings, which are bogus, but distracting. */
3219 #define CACHEsayNO \
3220 if (ST.cache_mask) \
3221 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3224 /* this is used to determine how far from the left messages like
3225 'failed...' are printed. It should be set such that messages
3226 are inline with the regop output that created them.
3228 #define REPORT_CODE_OFF 32
3231 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3232 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3233 #define CHRTEST_NOT_A_CP_1 -999
3234 #define CHRTEST_NOT_A_CP_2 -998
3236 /* grab a new slab and return the first slot in it */
3238 STATIC regmatch_state *
3241 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3244 regmatch_slab *s = PL_regmatch_slab->next;
3246 Newx(s, 1, regmatch_slab);
3247 s->prev = PL_regmatch_slab;
3249 PL_regmatch_slab->next = s;
3251 PL_regmatch_slab = s;
3252 return SLAB_FIRST(s);
3256 /* push a new state then goto it */
3258 #define PUSH_STATE_GOTO(state, node, input) \
3259 pushinput = input; \
3261 st->resume_state = state; \
3264 /* push a new state with success backtracking, then goto it */
3266 #define PUSH_YES_STATE_GOTO(state, node, input) \
3267 pushinput = input; \
3269 st->resume_state = state; \
3270 goto push_yes_state;
3277 regmatch() - main matching routine
3279 This is basically one big switch statement in a loop. We execute an op,
3280 set 'next' to point the next op, and continue. If we come to a point which
3281 we may need to backtrack to on failure such as (A|B|C), we push a
3282 backtrack state onto the backtrack stack. On failure, we pop the top
3283 state, and re-enter the loop at the state indicated. If there are no more
3284 states to pop, we return failure.
3286 Sometimes we also need to backtrack on success; for example /A+/, where
3287 after successfully matching one A, we need to go back and try to
3288 match another one; similarly for lookahead assertions: if the assertion
3289 completes successfully, we backtrack to the state just before the assertion
3290 and then carry on. In these cases, the pushed state is marked as
3291 'backtrack on success too'. This marking is in fact done by a chain of
3292 pointers, each pointing to the previous 'yes' state. On success, we pop to
3293 the nearest yes state, discarding any intermediate failure-only states.
3294 Sometimes a yes state is pushed just to force some cleanup code to be
3295 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3296 it to free the inner regex.
3298 Note that failure backtracking rewinds the cursor position, while
3299 success backtracking leaves it alone.
3301 A pattern is complete when the END op is executed, while a subpattern
3302 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3303 ops trigger the "pop to last yes state if any, otherwise return true"
3306 A common convention in this function is to use A and B to refer to the two
3307 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3308 the subpattern to be matched possibly multiple times, while B is the entire
3309 rest of the pattern. Variable and state names reflect this convention.
3311 The states in the main switch are the union of ops and failure/success of
3312 substates associated with with that op. For example, IFMATCH is the op
3313 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3314 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3315 successfully matched A and IFMATCH_A_fail is a state saying that we have
3316 just failed to match A. Resume states always come in pairs. The backtrack
3317 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3318 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3319 on success or failure.
3321 The struct that holds a backtracking state is actually a big union, with
3322 one variant for each major type of op. The variable st points to the
3323 top-most backtrack struct. To make the code clearer, within each
3324 block of code we #define ST to alias the relevant union.
3326 Here's a concrete example of a (vastly oversimplified) IFMATCH
3332 #define ST st->u.ifmatch
3334 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3335 ST.foo = ...; // some state we wish to save
3337 // push a yes backtrack state with a resume value of
3338 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3340 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3343 case IFMATCH_A: // we have successfully executed A; now continue with B
3345 bar = ST.foo; // do something with the preserved value
3348 case IFMATCH_A_fail: // A failed, so the assertion failed
3349 ...; // do some housekeeping, then ...
3350 sayNO; // propagate the failure
3357 For any old-timers reading this who are familiar with the old recursive
3358 approach, the code above is equivalent to:
3360 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3369 ...; // do some housekeeping, then ...
3370 sayNO; // propagate the failure
3373 The topmost backtrack state, pointed to by st, is usually free. If you
3374 want to claim it, populate any ST.foo fields in it with values you wish to
3375 save, then do one of
3377 PUSH_STATE_GOTO(resume_state, node, newinput);
3378 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3380 which sets that backtrack state's resume value to 'resume_state', pushes a
3381 new free entry to the top of the backtrack stack, then goes to 'node'.
3382 On backtracking, the free slot is popped, and the saved state becomes the
3383 new free state. An ST.foo field in this new top state can be temporarily
3384 accessed to retrieve values, but once the main loop is re-entered, it
3385 becomes available for reuse.
3387 Note that the depth of the backtrack stack constantly increases during the
3388 left-to-right execution of the pattern, rather than going up and down with
3389 the pattern nesting. For example the stack is at its maximum at Z at the
3390 end of the pattern, rather than at X in the following:
3392 /(((X)+)+)+....(Y)+....Z/
3394 The only exceptions to this are lookahead/behind assertions and the cut,
3395 (?>A), which pop all the backtrack states associated with A before
3398 Backtrack state structs are allocated in slabs of about 4K in size.
3399 PL_regmatch_state and st always point to the currently active state,
3400 and PL_regmatch_slab points to the slab currently containing
3401 PL_regmatch_state. The first time regmatch() is called, the first slab is
3402 allocated, and is never freed until interpreter destruction. When the slab
3403 is full, a new one is allocated and chained to the end. At exit from
3404 regmatch(), slabs allocated since entry are freed.
3409 #define DEBUG_STATE_pp(pp) \
3411 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3412 PerlIO_printf(Perl_debug_log, \
3413 " %*s"pp" %s%s%s%s%s\n", \
3415 PL_reg_name[st->resume_state], \
3416 ((st==yes_state||st==mark_state) ? "[" : ""), \
3417 ((st==yes_state) ? "Y" : ""), \
3418 ((st==mark_state) ? "M" : ""), \
3419 ((st==yes_state||st==mark_state) ? "]" : "") \
3424 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3429 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3430 const char *start, const char *end, const char *blurb)
3432 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3434 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3439 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3440 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3442 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3443 start, end - start, 60);
3445 PerlIO_printf(Perl_debug_log,
3446 "%s%s REx%s %s against %s\n",
3447 PL_colors[4], blurb, PL_colors[5], s0, s1);
3449 if (utf8_target||utf8_pat)
3450 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3451 utf8_pat ? "pattern" : "",
3452 utf8_pat && utf8_target ? " and " : "",
3453 utf8_target ? "string" : ""
3459 S_dump_exec_pos(pTHX_ const char *locinput,
3460 const regnode *scan,
3461 const char *loc_regeol,
3462 const char *loc_bostr,
3463 const char *loc_reg_starttry,
3464 const bool utf8_target)
3466 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3467 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3468 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3469 /* The part of the string before starttry has one color
3470 (pref0_len chars), between starttry and current
3471 position another one (pref_len - pref0_len chars),
3472 after the current position the third one.
3473 We assume that pref0_len <= pref_len, otherwise we
3474 decrease pref0_len. */
3475 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3476 ? (5 + taill) - l : locinput - loc_bostr;
3479 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3481 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3483 pref0_len = pref_len - (locinput - loc_reg_starttry);
3484 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3485 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3486 ? (5 + taill) - pref_len : loc_regeol - locinput);
3487 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3491 if (pref0_len > pref_len)
3492 pref0_len = pref_len;
3494 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3496 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3497 (locinput - pref_len),pref0_len, 60, 4, 5);
3499 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3500 (locinput - pref_len + pref0_len),
3501 pref_len - pref0_len, 60, 2, 3);
3503 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3504 locinput, loc_regeol - locinput, 10, 0, 1);
3506 const STRLEN tlen=len0+len1+len2;
3507 PerlIO_printf(Perl_debug_log,
3508 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3509 (IV)(locinput - loc_bostr),
3512 (docolor ? "" : "> <"),
3514 (int)(tlen > 19 ? 0 : 19 - tlen),
3521 /* reg_check_named_buff_matched()
3522 * Checks to see if a named buffer has matched. The data array of
3523 * buffer numbers corresponding to the buffer is expected to reside
3524 * in the regexp->data->data array in the slot stored in the ARG() of
3525 * node involved. Note that this routine doesn't actually care about the
3526 * name, that information is not preserved from compilation to execution.
3527 * Returns the index of the leftmost defined buffer with the given name
3528 * or 0 if non of the buffers matched.
3531 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
3534 RXi_GET_DECL(rex,rexi);
3535 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3536 I32 *nums=(I32*)SvPVX(sv_dat);
3538 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3540 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3541 if ((I32)rex->lastparen >= nums[n] &&
3542 rex->offs[nums[n]].end != -1)
3552 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3553 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3555 /* This function determines if there are one or two characters that match
3556 * the first character of the passed-in EXACTish node <text_node>, and if
3557 * so, returns them in the passed-in pointers.
3559 * If it determines that no possible character in the target string can
3560 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3561 * the first character in <text_node> requires UTF-8 to represent, and the
3562 * target string isn't in UTF-8.)
3564 * If there are more than two characters that could match the beginning of
3565 * <text_node>, or if more context is required to determine a match or not,
3566 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3568 * The motiviation behind this function is to allow the caller to set up
3569 * tight loops for matching. If <text_node> is of type EXACT, there is
3570 * only one possible character that can match its first character, and so
3571 * the situation is quite simple. But things get much more complicated if
3572 * folding is involved. It may be that the first character of an EXACTFish
3573 * node doesn't participate in any possible fold, e.g., punctuation, so it
3574 * can be matched only by itself. The vast majority of characters that are
3575 * in folds match just two things, their lower and upper-case equivalents.
3576 * But not all are like that; some have multiple possible matches, or match
3577 * sequences of more than one character. This function sorts all that out.
3579 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3580 * loop of trying to match A*, we know we can't exit where the thing
3581 * following it isn't a B. And something can't be a B unless it is the
3582 * beginning of B. By putting a quick test for that beginning in a tight
3583 * loop, we can rule out things that can't possibly be B without having to
3584 * break out of the loop, thus avoiding work. Similarly, if A is a single
3585 * character, we can make a tight loop matching A*, using the outputs of
3588 * If the target string to match isn't in UTF-8, and there aren't
3589 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3590 * the one or two possible octets (which are characters in this situation)
3591 * that can match. In all cases, if there is only one character that can
3592 * match, *<c1p> and *<c2p> will be identical.
3594 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3595 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3596 * can match the beginning of <text_node>. They should be declared with at
3597 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3598 * undefined what these contain.) If one or both of the buffers are
3599 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3600 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3601 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3602 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3603 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3605 const bool utf8_target = reginfo->is_utf8_target;
3607 UV c1 = CHRTEST_NOT_A_CP_1;
3608 UV c2 = CHRTEST_NOT_A_CP_2;
3609 bool use_chrtest_void = FALSE;
3610 const bool is_utf8_pat = reginfo->is_utf8_pat;
3612 /* Used when we have both utf8 input and utf8 output, to avoid converting
3613 * to/from code points */
3614 bool utf8_has_been_setup = FALSE;
3618 U8 *pat = (U8*)STRING(text_node);
3619 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3621 if (OP(text_node) == EXACT) {
3623 /* In an exact node, only one thing can be matched, that first
3624 * character. If both the pat and the target are UTF-8, we can just
3625 * copy the input to the output, avoiding finding the code point of
3630 else if (utf8_target) {
3631 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3632 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3633 utf8_has_been_setup = TRUE;
3636 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3639 else { /* an EXACTFish node */
3640 U8 *pat_end = pat + STR_LEN(text_node);
3642 /* An EXACTFL node has at least some characters unfolded, because what
3643 * they match is not known until now. So, now is the time to fold
3644 * the first few of them, as many as are needed to determine 'c1' and
3645 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3646 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3647 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3648 * need to fold as many characters as a single character can fold to,
3649 * so that later we can check if the first ones are such a multi-char
3650 * fold. But, in such a pattern only locale-problematic characters
3651 * aren't folded, so we can skip this completely if the first character
3652 * in the node isn't one of the tricky ones */
3653 if (OP(text_node) == EXACTFL) {
3655 if (! is_utf8_pat) {
3656 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3658 folded[0] = folded[1] = 's';
3660 pat_end = folded + 2;
3663 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3668 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3670 *(d++) = (U8) toFOLD_LC(*s);
3675 _to_utf8_fold_flags(s,
3678 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
3689 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
3690 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
3692 /* Multi-character folds require more context to sort out. Also
3693 * PL_utf8_foldclosures used below doesn't handle them, so have to
3694 * be handled outside this routine */
3695 use_chrtest_void = TRUE;
3697 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
3698 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
3700 /* Load the folds hash, if not already done */
3702 if (! PL_utf8_foldclosures) {
3703 if (! PL_utf8_tofold) {
3704 U8 dummy[UTF8_MAXBYTES_CASE+1];
3706 /* Force loading this by folding an above-Latin1 char */
3707 to_utf8_fold((U8*) HYPHEN_UTF8, dummy, NULL);
3708 assert(PL_utf8_tofold); /* Verify that worked */
3710 PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
3713 /* The fold closures data structure is a hash with the keys
3714 * being the UTF-8 of every character that is folded to, like
3715 * 'k', and the values each an array of all code points that
3716 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
3717 * Multi-character folds are not included */
3718 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
3723 /* Not found in the hash, therefore there are no folds
3724 * containing it, so there is only a single character that
3728 else { /* Does participate in folds */
3729 AV* list = (AV*) *listp;
3730 if (av_tindex(list) != 1) {
3732 /* If there aren't exactly two folds to this, it is
3733 * outside the scope of this function */
3734 use_chrtest_void = TRUE;
3736 else { /* There are two. Get them */
3737 SV** c_p = av_fetch(list, 0, FALSE);
3739 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3743 c_p = av_fetch(list, 1, FALSE);
3745 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3749 /* Folds that cross the 255/256 boundary are forbidden
3750 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
3751 * one is ASCIII. Since the pattern character is above
3752 * 256, and its only other match is below 256, the only
3753 * legal match will be to itself. We have thrown away
3754 * the original, so have to compute which is the one
3756 if ((c1 < 256) != (c2 < 256)) {
3757 if ((OP(text_node) == EXACTFL
3758 && ! IN_UTF8_CTYPE_LOCALE)
3759 || ((OP(text_node) == EXACTFA
3760 || OP(text_node) == EXACTFA_NO_TRIE)
3761 && (isASCII(c1) || isASCII(c2))))
3774 else /* Here, c1 is < 255 */
3776 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
3777 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
3778 && ((OP(text_node) != EXACTFA
3779 && OP(text_node) != EXACTFA_NO_TRIE)
3782 /* Here, there could be something above Latin1 in the target
3783 * which folds to this character in the pattern. All such
3784 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
3785 * than two characters involved in their folds, so are outside
3786 * the scope of this function */
3787 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
3788 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
3791 use_chrtest_void = TRUE;
3794 else { /* Here nothing above Latin1 can fold to the pattern
3796 switch (OP(text_node)) {
3798 case EXACTFL: /* /l rules */
3799 c2 = PL_fold_locale[c1];
3802 case EXACTF: /* This node only generated for non-utf8
3804 assert(! is_utf8_pat);
3805 if (! utf8_target) { /* /d rules */
3810 /* /u rules for all these. This happens to work for
3811 * EXACTFA as nothing in Latin1 folds to ASCII */
3812 case EXACTFA_NO_TRIE: /* This node only generated for
3813 non-utf8 patterns */
3814 assert(! is_utf8_pat);
3819 c2 = PL_fold_latin1[c1];
3823 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
3824 assert(0); /* NOTREACHED */
3830 /* Here have figured things out. Set up the returns */
3831 if (use_chrtest_void) {
3832 *c2p = *c1p = CHRTEST_VOID;
3834 else if (utf8_target) {
3835 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
3836 uvchr_to_utf8(c1_utf8, c1);
3837 uvchr_to_utf8(c2_utf8, c2);
3840 /* Invariants are stored in both the utf8 and byte outputs; Use
3841 * negative numbers otherwise for the byte ones. Make sure that the
3842 * byte ones are the same iff the utf8 ones are the same */
3843 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
3844 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
3847 ? CHRTEST_NOT_A_CP_1
3848 : CHRTEST_NOT_A_CP_2;
3850 else if (c1 > 255) {
3851 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
3856 *c1p = *c2p = c2; /* c2 is the only representable value */
3858 else { /* c1 is representable; see about c2 */
3860 *c2p = (c2 < 256) ? c2 : c1;
3866 /* returns -1 on failure, $+[0] on success */
3868 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
3870 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3874 const bool utf8_target = reginfo->is_utf8_target;
3875 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3876 REGEXP *rex_sv = reginfo->prog;
3877 regexp *rex = ReANY(rex_sv);
3878 RXi_GET_DECL(rex,rexi);
3879 /* the current state. This is a cached copy of PL_regmatch_state */
3881 /* cache heavy used fields of st in registers */
3884 U32 n = 0; /* general value; init to avoid compiler warning */
3885 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
3886 char *locinput = startpos;
3887 char *pushinput; /* where to continue after a PUSH */
3888 I32 nextchr; /* is always set to UCHARAT(locinput) */
3890 bool result = 0; /* return value of S_regmatch */
3891 int depth = 0; /* depth of backtrack stack */
3892 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3893 const U32 max_nochange_depth =
3894 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3895 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3896 regmatch_state *yes_state = NULL; /* state to pop to on success of
3898 /* mark_state piggy backs on the yes_state logic so that when we unwind
3899 the stack on success we can update the mark_state as we go */
3900 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3901 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3902 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3904 bool no_final = 0; /* prevent failure from backtracking? */
3905 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3906 char *startpoint = locinput;
3907 SV *popmark = NULL; /* are we looking for a mark? */
3908 SV *sv_commit = NULL; /* last mark name seen in failure */
3909 SV *sv_yes_mark = NULL; /* last mark name we have seen
3910 during a successful match */
3911 U32 lastopen = 0; /* last open we saw */
3912 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3913 SV* const oreplsv = GvSVn(PL_replgv);
3914 /* these three flags are set by various ops to signal information to
3915 * the very next op. They have a useful lifetime of exactly one loop
3916 * iteration, and are not preserved or restored by state pushes/pops
3918 bool sw = 0; /* the condition value in (?(cond)a|b) */
3919 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3920 int logical = 0; /* the following EVAL is:
3924 or the following IFMATCH/UNLESSM is:
3925 false: plain (?=foo)
3926 true: used as a condition: (?(?=foo))
3928 PAD* last_pad = NULL;
3930 I32 gimme = G_SCALAR;
3931 CV *caller_cv = NULL; /* who called us */
3932 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
3933 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
3934 U32 maxopenparen = 0; /* max '(' index seen so far */
3935 int to_complement; /* Invert the result? */
3936 _char_class_number classnum;
3937 bool is_utf8_pat = reginfo->is_utf8_pat;
3940 GET_RE_DEBUG_FLAGS_DECL;
3943 /* protect against undef(*^R) */
3944 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
3946 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3947 multicall_oldcatch = 0;
3948 multicall_cv = NULL;
3950 PERL_UNUSED_VAR(multicall_cop);
3951 PERL_UNUSED_VAR(newsp);
3954 PERL_ARGS_ASSERT_REGMATCH;
3956 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3957 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3960 st = PL_regmatch_state;
3962 /* Note that nextchr is a byte even in UTF */
3965 while (scan != NULL) {
3968 SV * const prop = sv_newmortal();
3969 regnode *rnext=regnext(scan);
3970 DUMP_EXEC_POS( locinput, scan, utf8_target );
3971 regprop(rex, prop, scan, reginfo);
3973 PerlIO_printf(Perl_debug_log,
3974 "%3"IVdf":%*s%s(%"IVdf")\n",
3975 (IV)(scan - rexi->program), depth*2, "",
3977 (PL_regkind[OP(scan)] == END || !rnext) ?
3978 0 : (IV)(rnext - rexi->program));
3981 next = scan + NEXT_OFF(scan);
3984 state_num = OP(scan);
3986 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
3991 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
3993 switch (state_num) {
3994 case BOL: /* /^../ */
3995 case SBOL: /* /^../s */
3996 if (locinput == reginfo->strbeg)
4000 case MBOL: /* /^../m */
4001 if (locinput == reginfo->strbeg ||
4002 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4009 if (locinput == reginfo->ganch)
4013 case KEEPS: /* \K */
4014 /* update the startpoint */
4015 st->u.keeper.val = rex->offs[0].start;
4016 rex->offs[0].start = locinput - reginfo->strbeg;
4017 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4018 assert(0); /*NOTREACHED*/
4019 case KEEPS_next_fail:
4020 /* rollback the start point change */
4021 rex->offs[0].start = st->u.keeper.val;
4023 assert(0); /*NOTREACHED*/
4025 case MEOL: /* /..$/m */
4026 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4030 case EOL: /* /..$/ */
4032 case SEOL: /* /..$/s */
4033 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4035 if (reginfo->strend - locinput > 1)
4040 if (!NEXTCHR_IS_EOS)
4044 case SANY: /* /./s */
4047 goto increment_locinput;
4055 case REG_ANY: /* /./ */
4056 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4058 goto increment_locinput;
4062 #define ST st->u.trie
4063 case TRIEC: /* (ab|cd) with known charclass */
4064 /* In this case the charclass data is available inline so
4065 we can fail fast without a lot of extra overhead.
4067 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
4069 PerlIO_printf(Perl_debug_log,
4070 "%*s %sfailed to match trie start class...%s\n",
4071 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4074 assert(0); /* NOTREACHED */
4077 case TRIE: /* (ab|cd) */
4078 /* the basic plan of execution of the trie is:
4079 * At the beginning, run though all the states, and
4080 * find the longest-matching word. Also remember the position
4081 * of the shortest matching word. For example, this pattern:
4084 * when matched against the string "abcde", will generate
4085 * accept states for all words except 3, with the longest
4086 * matching word being 4, and the shortest being 2 (with
4087 * the position being after char 1 of the string).
4089 * Then for each matching word, in word order (i.e. 1,2,4,5),
4090 * we run the remainder of the pattern; on each try setting
4091 * the current position to the character following the word,
4092 * returning to try the next word on failure.
4094 * We avoid having to build a list of words at runtime by
4095 * using a compile-time structure, wordinfo[].prev, which
4096 * gives, for each word, the previous accepting word (if any).
4097 * In the case above it would contain the mappings 1->2, 2->0,
4098 * 3->0, 4->5, 5->1. We can use this table to generate, from
4099 * the longest word (4 above), a list of all words, by
4100 * following the list of prev pointers; this gives us the
4101 * unordered list 4,5,1,2. Then given the current word we have
4102 * just tried, we can go through the list and find the
4103 * next-biggest word to try (so if we just failed on word 2,
4104 * the next in the list is 4).
4106 * Since at runtime we don't record the matching position in
4107 * the string for each word, we have to work that out for
4108 * each word we're about to process. The wordinfo table holds
4109 * the character length of each word; given that we recorded
4110 * at the start: the position of the shortest word and its
4111 * length in chars, we just need to move the pointer the
4112 * difference between the two char lengths. Depending on
4113 * Unicode status and folding, that's cheap or expensive.
4115 * This algorithm is optimised for the case where are only a
4116 * small number of accept states, i.e. 0,1, or maybe 2.
4117 * With lots of accepts states, and having to try all of them,
4118 * it becomes quadratic on number of accept states to find all
4123 /* what type of TRIE am I? (utf8 makes this contextual) */
4124 DECL_TRIE_TYPE(scan);
4126 /* what trie are we using right now */
4127 reg_trie_data * const trie
4128 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
4129 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
4130 U32 state = trie->startstate;
4133 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
4135 if (trie->states[ state ].wordnum) {
4137 PerlIO_printf(Perl_debug_log,
4138 "%*s %smatched empty string...%s\n",
4139 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4145 PerlIO_printf(Perl_debug_log,
4146 "%*s %sfailed to match trie start class...%s\n",
4147 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4154 U8 *uc = ( U8* )locinput;
4158 U8 *uscan = (U8*)NULL;
4159 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
4160 U32 charcount = 0; /* how many input chars we have matched */
4161 U32 accepted = 0; /* have we seen any accepting states? */
4163 ST.jump = trie->jump;
4166 ST.longfold = FALSE; /* char longer if folded => it's harder */
4169 /* fully traverse the TRIE; note the position of the
4170 shortest accept state and the wordnum of the longest
4173 while ( state && uc <= (U8*)(reginfo->strend) ) {
4174 U32 base = trie->states[ state ].trans.base;
4178 wordnum = trie->states[ state ].wordnum;
4180 if (wordnum) { /* it's an accept state */
4183 /* record first match position */
4185 ST.firstpos = (U8*)locinput;
4190 ST.firstchars = charcount;
4193 if (!ST.nextword || wordnum < ST.nextword)
4194 ST.nextword = wordnum;
4195 ST.topword = wordnum;
4198 DEBUG_TRIE_EXECUTE_r({
4199 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
4200 PerlIO_printf( Perl_debug_log,
4201 "%*s %sState: %4"UVxf" Accepted: %c ",
4202 2+depth * 2, "", PL_colors[4],
4203 (UV)state, (accepted ? 'Y' : 'N'));
4206 /* read a char and goto next state */
4207 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
4209 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
4210 uscan, len, uvc, charid, foldlen,
4217 base + charid - 1 - trie->uniquecharcount)) >= 0)
4219 && ((U32)offset < trie->lasttrans)
4220 && trie->trans[offset].check == state)
4222 state = trie->trans[offset].next;
4233 DEBUG_TRIE_EXECUTE_r(
4234 PerlIO_printf( Perl_debug_log,
4235 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
4236 charid, uvc, (UV)state, PL_colors[5] );
4242 /* calculate total number of accept states */
4247 w = trie->wordinfo[w].prev;
4250 ST.accepted = accepted;
4254 PerlIO_printf( Perl_debug_log,
4255 "%*s %sgot %"IVdf" possible matches%s\n",
4256 REPORT_CODE_OFF + depth * 2, "",
4257 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
4259 goto trie_first_try; /* jump into the fail handler */
4261 assert(0); /* NOTREACHED */
4263 case TRIE_next_fail: /* we failed - try next alternative */
4267 REGCP_UNWIND(ST.cp);
4268 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
4270 if (!--ST.accepted) {
4272 PerlIO_printf( Perl_debug_log,
4273 "%*s %sTRIE failed...%s\n",
4274 REPORT_CODE_OFF+depth*2, "",
4281 /* Find next-highest word to process. Note that this code
4282 * is O(N^2) per trie run (O(N) per branch), so keep tight */
4285 U16 const nextword = ST.nextword;
4286 reg_trie_wordinfo * const wordinfo
4287 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
4288 for (word=ST.topword; word; word=wordinfo[word].prev) {
4289 if (word > nextword && (!min || word < min))
4302 ST.lastparen = rex->lastparen;
4303 ST.lastcloseparen = rex->lastcloseparen;
4307 /* find start char of end of current word */
4309 U32 chars; /* how many chars to skip */
4310 reg_trie_data * const trie
4311 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
4313 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
4315 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
4320 /* the hard option - fold each char in turn and find
4321 * its folded length (which may be different */
4322 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
4330 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
4338 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
4343 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
4359 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
4360 ? ST.jump[ST.nextword]
4364 PerlIO_printf( Perl_debug_log,
4365 "%*s %sTRIE matched word #%d, continuing%s\n",
4366 REPORT_CODE_OFF+depth*2, "",
4373 if (ST.accepted > 1 || has_cutgroup) {
4374 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
4375 assert(0); /* NOTREACHED */
4377 /* only one choice left - just continue */
4379 AV *const trie_words
4380 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
4381 SV ** const tmp = av_fetch( trie_words,
4383 SV *sv= tmp ? sv_newmortal() : NULL;
4385 PerlIO_printf( Perl_debug_log,
4386 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
4387 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
4389 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
4390 PL_colors[0], PL_colors[1],
4391 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
4393 : "not compiled under -Dr",
4397 locinput = (char*)uc;
4398 continue; /* execute rest of RE */
4399 assert(0); /* NOTREACHED */
4403 case EXACT: { /* /abc/ */
4404 char *s = STRING(scan);
4406 if (utf8_target != is_utf8_pat) {
4407 /* The target and the pattern have differing utf8ness. */
4409 const char * const e = s + ln;
4412 /* The target is utf8, the pattern is not utf8.
4413 * Above-Latin1 code points can't match the pattern;
4414 * invariants match exactly, and the other Latin1 ones need
4415 * to be downgraded to a single byte in order to do the
4416 * comparison. (If we could be confident that the target
4417 * is not malformed, this could be refactored to have fewer
4418 * tests by just assuming that if the first bytes match, it
4419 * is an invariant, but there are tests in the test suite
4420 * dealing with (??{...}) which violate this) */
4422 if (l >= reginfo->strend
4423 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
4427 if (UTF8_IS_INVARIANT(*(U8*)l)) {
4434 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
4444 /* The target is not utf8, the pattern is utf8. */
4446 if (l >= reginfo->strend
4447 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
4451 if (UTF8_IS_INVARIANT(*(U8*)s)) {
4458 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
4470 /* The target and the pattern have the same utf8ness. */
4471 /* Inline the first character, for speed. */
4472 if (reginfo->strend - locinput < ln
4473 || UCHARAT(s) != nextchr
4474 || (ln > 1 && memNE(s, locinput, ln)))
4483 case EXACTFL: { /* /abc/il */
4485 const U8 * fold_array;
4487 U32 fold_utf8_flags;
4489 folder = foldEQ_locale;
4490 fold_array = PL_fold_locale;
4491 fold_utf8_flags = FOLDEQ_LOCALE;
4494 case EXACTFU_SS: /* /\x{df}/iu */
4495 case EXACTFU: /* /abc/iu */
4496 folder = foldEQ_latin1;
4497 fold_array = PL_fold_latin1;
4498 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
4501 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
4503 assert(! is_utf8_pat);
4505 case EXACTFA: /* /abc/iaa */
4506 folder = foldEQ_latin1;
4507 fold_array = PL_fold_latin1;
4508 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4511 case EXACTF: /* /abc/i This node only generated for
4512 non-utf8 patterns */
4513 assert(! is_utf8_pat);
4515 fold_array = PL_fold;
4516 fold_utf8_flags = 0;
4524 || state_num == EXACTFU_SS
4525 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
4527 /* Either target or the pattern are utf8, or has the issue where
4528 * the fold lengths may differ. */
4529 const char * const l = locinput;
4530 char *e = reginfo->strend;
4532 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
4533 l, &e, 0, utf8_target, fold_utf8_flags))
4541 /* Neither the target nor the pattern are utf8 */
4542 if (UCHARAT(s) != nextchr
4544 && UCHARAT(s) != fold_array[nextchr])
4548 if (reginfo->strend - locinput < ln)
4550 if (ln > 1 && ! folder(s, locinput, ln))
4556 /* XXX Could improve efficiency by separating these all out using a
4557 * macro or in-line function. At that point regcomp.c would no longer
4558 * have to set the FLAGS fields of these */
4559 case BOUNDL: /* /\b/l */
4560 case NBOUNDL: /* /\B/l */
4561 case BOUND: /* /\b/ */
4562 case BOUNDU: /* /\b/u */
4563 case BOUNDA: /* /\b/a */
4564 case NBOUND: /* /\B/ */
4565 case NBOUNDU: /* /\B/u */
4566 case NBOUNDA: /* /\B/a */
4567 /* was last char in word? */
4569 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
4570 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
4572 if (locinput == reginfo->strbeg)
4575 const U8 * const r =
4576 reghop3((U8*)locinput, -1, (U8*)(reginfo->strbeg));
4578 ln = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,
4581 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
4582 ln = isWORDCHAR_uni(ln);
4586 LOAD_UTF8_CHARCLASS_ALNUM();
4587 n = swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)locinput,
4592 ln = isWORDCHAR_LC_uvchr(ln);
4593 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC_utf8((U8*)locinput);
4598 /* Here the string isn't utf8, or is utf8 and only ascii
4599 * characters are to match \w. In the latter case looking at
4600 * the byte just prior to the current one may be just the final
4601 * byte of a multi-byte character. This is ok. There are two
4603 * 1) it is a single byte character, and then the test is doing
4604 * just what it's supposed to.
4605 * 2) it is a multi-byte character, in which case the final
4606 * byte is never mistakable for ASCII, and so the test
4607 * will say it is not a word character, which is the
4608 * correct answer. */
4609 ln = (locinput != reginfo->strbeg) ?
4610 UCHARAT(locinput - 1) : '\n';
4611 switch (FLAGS(scan)) {
4612 case REGEX_UNICODE_CHARSET:
4613 ln = isWORDCHAR_L1(ln);
4614 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_L1(nextchr);
4616 case REGEX_LOCALE_CHARSET:
4617 ln = isWORDCHAR_LC(ln);
4618 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC(nextchr);
4620 case REGEX_DEPENDS_CHARSET:
4621 ln = isWORDCHAR(ln);
4622 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR(nextchr);
4624 case REGEX_ASCII_RESTRICTED_CHARSET:
4625 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
4626 ln = isWORDCHAR_A(ln);
4627 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_A(nextchr);
4630 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
4634 /* Note requires that all BOUNDs be lower than all NBOUNDs in
4636 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
4640 case ANYOF: /* /[abc]/ */
4644 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
4647 locinput += UTF8SKIP(locinput);
4650 if (!REGINCLASS(rex, scan, (U8*)locinput))
4656 /* The argument (FLAGS) to all the POSIX node types is the class number
4659 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
4663 case POSIXL: /* \w or [:punct:] etc. under /l */
4667 /* Use isFOO_lc() for characters within Latin1. (Note that
4668 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4669 * wouldn't be invariant) */
4670 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4671 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
4675 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4676 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
4677 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4678 *(locinput + 1))))))
4683 else { /* Here, must be an above Latin-1 code point */
4684 goto utf8_posix_not_eos;
4687 /* Here, must be utf8 */
4688 locinput += UTF8SKIP(locinput);
4691 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
4695 case POSIXD: /* \w or [:punct:] etc. under /d */
4701 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
4703 if (NEXTCHR_IS_EOS) {
4707 /* All UTF-8 variants match */
4708 if (! UTF8_IS_INVARIANT(nextchr)) {
4709 goto increment_locinput;
4715 case POSIXA: /* \w or [:punct:] etc. under /a */
4718 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
4719 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
4720 * character is a single byte */
4723 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
4729 /* Here we are either not in utf8, or we matched a utf8-invariant,
4730 * so the next char is the next byte */
4734 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
4738 case POSIXU: /* \w or [:punct:] etc. under /u */
4740 if (NEXTCHR_IS_EOS) {
4745 /* Use _generic_isCC() for characters within Latin1. (Note that
4746 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4747 * wouldn't be invariant) */
4748 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4749 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
4756 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4757 if (! (to_complement
4758 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
4766 else { /* Handle above Latin-1 code points */
4767 classnum = (_char_class_number) FLAGS(scan);
4768 if (classnum < _FIRST_NON_SWASH_CC) {
4770 /* Here, uses a swash to find such code points. Load if if
4771 * not done already */
4772 if (! PL_utf8_swash_ptrs[classnum]) {
4773 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
4774 PL_utf8_swash_ptrs[classnum]
4775 = _core_swash_init("utf8",
4778 PL_XPosix_ptrs[classnum], &flags);
4780 if (! (to_complement
4781 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
4782 (U8 *) locinput, TRUE))))
4787 else { /* Here, uses macros to find above Latin-1 code points */
4789 case _CC_ENUM_SPACE: /* XXX would require separate
4790 code if we revert the change
4791 of \v matching this */
4792 case _CC_ENUM_PSXSPC:
4793 if (! (to_complement
4794 ^ cBOOL(is_XPERLSPACE_high(locinput))))
4799 case _CC_ENUM_BLANK:
4800 if (! (to_complement
4801 ^ cBOOL(is_HORIZWS_high(locinput))))
4806 case _CC_ENUM_XDIGIT:
4807 if (! (to_complement
4808 ^ cBOOL(is_XDIGIT_high(locinput))))
4813 case _CC_ENUM_VERTSPACE:
4814 if (! (to_complement
4815 ^ cBOOL(is_VERTWS_high(locinput))))
4820 default: /* The rest, e.g. [:cntrl:], can't match
4822 if (! to_complement) {
4828 locinput += UTF8SKIP(locinput);
4832 case CLUMP: /* Match \X: logical Unicode character. This is defined as
4833 a Unicode extended Grapheme Cluster */
4834 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
4835 extended Grapheme Cluster is:
4838 | Prepend* Begin Extend*
4841 Begin is: ( Special_Begin | ! Control )
4842 Special_Begin is: ( Regional-Indicator+ | Hangul-syllable )
4843 Extend is: ( Grapheme_Extend | Spacing_Mark )
4844 Control is: [ GCB_Control | CR | LF ]
4845 Hangul-syllable is: ( T+ | ( L* ( L | ( LVT | ( V | LV ) V* ) T* ) ))
4847 If we create a 'Regular_Begin' = Begin - Special_Begin, then
4850 Begin is ( Regular_Begin + Special Begin )
4852 It turns out that 98.4% of all Unicode code points match
4853 Regular_Begin. Doing it this way eliminates a table match in
4854 the previous implementation for almost all Unicode code points.
4856 There is a subtlety with Prepend* which showed up in testing.
4857 Note that the Begin, and only the Begin is required in:
4858 | Prepend* Begin Extend*
4859 Also, Begin contains '! Control'. A Prepend must be a
4860 '! Control', which means it must also be a Begin. What it
4861 comes down to is that if we match Prepend* and then find no
4862 suitable Begin afterwards, that if we backtrack the last
4863 Prepend, that one will be a suitable Begin.
4868 if (! utf8_target) {
4870 /* Match either CR LF or '.', as all the other possibilities
4872 locinput++; /* Match the . or CR */
4873 if (nextchr == '\r' /* And if it was CR, and the next is LF,
4875 && locinput < reginfo->strend
4876 && UCHARAT(locinput) == '\n')
4883 /* Utf8: See if is ( CR LF ); already know that locinput <
4884 * reginfo->strend, so locinput+1 is in bounds */
4885 if ( nextchr == '\r' && locinput+1 < reginfo->strend
4886 && UCHARAT(locinput + 1) == '\n')
4893 /* In case have to backtrack to beginning, then match '.' */
4894 char *starting = locinput;
4896 /* In case have to backtrack the last prepend */
4897 char *previous_prepend = NULL;
4899 LOAD_UTF8_CHARCLASS_GCB();
4901 /* Match (prepend)* */
4902 while (locinput < reginfo->strend
4903 && (len = is_GCB_Prepend_utf8(locinput)))
4905 previous_prepend = locinput;
4909 /* As noted above, if we matched a prepend character, but
4910 * the next thing won't match, back off the last prepend we
4911 * matched, as it is guaranteed to match the begin */
4912 if (previous_prepend
4913 && (locinput >= reginfo->strend
4914 || (! swash_fetch(PL_utf8_X_regular_begin,
4915 (U8*)locinput, utf8_target)
4916 && ! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)))
4919 locinput = previous_prepend;
4922 /* Note that here we know reginfo->strend > locinput, as we
4923 * tested that upon input to this switch case, and if we
4924 * moved locinput forward, we tested the result just above
4925 * and it either passed, or we backed off so that it will
4927 if (swash_fetch(PL_utf8_X_regular_begin,
4928 (U8*)locinput, utf8_target)) {
4929 locinput += UTF8SKIP(locinput);
4931 else if (! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)) {
4933 /* Here did not match the required 'Begin' in the
4934 * second term. So just match the very first
4935 * character, the '.' of the final term of the regex */
4936 locinput = starting + UTF8SKIP(starting);
4940 /* Here is a special begin. It can be composed of
4941 * several individual characters. One possibility is
4943 if ((len = is_GCB_RI_utf8(locinput))) {
4945 while (locinput < reginfo->strend
4946 && (len = is_GCB_RI_utf8(locinput)))
4950 } else if ((len = is_GCB_T_utf8(locinput))) {
4951 /* Another possibility is T+ */
4953 while (locinput < reginfo->strend
4954 && (len = is_GCB_T_utf8(locinput)))
4960 /* Here, neither RI+ nor T+; must be some other
4961 * Hangul. That means it is one of the others: L,
4962 * LV, LVT or V, and matches:
4963 * L* (L | LVT T* | V * V* T* | LV V* T*) */
4966 while (locinput < reginfo->strend
4967 && (len = is_GCB_L_utf8(locinput)))
4972 /* Here, have exhausted L*. If the next character
4973 * is not an LV, LVT nor V, it means we had to have
4974 * at least one L, so matches L+ in the original
4975 * equation, we have a complete hangul syllable.
4978 if (locinput < reginfo->strend
4979 && is_GCB_LV_LVT_V_utf8(locinput))
4981 /* Otherwise keep going. Must be LV, LVT or V.
4982 * See if LVT, by first ruling out V, then LV */
4983 if (! is_GCB_V_utf8(locinput)
4984 /* All but every TCount one is LV */
4985 && (valid_utf8_to_uvchr((U8 *) locinput,
4990 locinput += UTF8SKIP(locinput);
4993 /* Must be V or LV. Take it, then match
4995 locinput += UTF8SKIP(locinput);
4996 while (locinput < reginfo->strend
4997 && (len = is_GCB_V_utf8(locinput)))
5003 /* And any of LV, LVT, or V can be followed
5005 while (locinput < reginfo->strend
5006 && (len = is_GCB_T_utf8(locinput)))
5014 /* Match any extender */
5015 while (locinput < reginfo->strend
5016 && swash_fetch(PL_utf8_X_extend,
5017 (U8*)locinput, utf8_target))
5019 locinput += UTF8SKIP(locinput);
5023 if (locinput > reginfo->strend) sayNO;
5027 case NREFFL: /* /\g{name}/il */
5028 { /* The capture buffer cases. The ones beginning with N for the
5029 named buffers just convert to the equivalent numbered and
5030 pretend they were called as the corresponding numbered buffer
5032 /* don't initialize these in the declaration, it makes C++
5037 const U8 *fold_array;
5040 folder = foldEQ_locale;
5041 fold_array = PL_fold_locale;
5043 utf8_fold_flags = FOLDEQ_LOCALE;
5046 case NREFFA: /* /\g{name}/iaa */
5047 folder = foldEQ_latin1;
5048 fold_array = PL_fold_latin1;
5050 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5053 case NREFFU: /* /\g{name}/iu */
5054 folder = foldEQ_latin1;
5055 fold_array = PL_fold_latin1;
5057 utf8_fold_flags = 0;
5060 case NREFF: /* /\g{name}/i */
5062 fold_array = PL_fold;
5064 utf8_fold_flags = 0;
5067 case NREF: /* /\g{name}/ */
5071 utf8_fold_flags = 0;
5074 /* For the named back references, find the corresponding buffer
5076 n = reg_check_named_buff_matched(rex,scan);
5081 goto do_nref_ref_common;
5083 case REFFL: /* /\1/il */
5084 folder = foldEQ_locale;
5085 fold_array = PL_fold_locale;
5086 utf8_fold_flags = FOLDEQ_LOCALE;
5089 case REFFA: /* /\1/iaa */
5090 folder = foldEQ_latin1;
5091 fold_array = PL_fold_latin1;
5092 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5095 case REFFU: /* /\1/iu */
5096 folder = foldEQ_latin1;
5097 fold_array = PL_fold_latin1;
5098 utf8_fold_flags = 0;
5101 case REFF: /* /\1/i */
5103 fold_array = PL_fold;
5104 utf8_fold_flags = 0;
5107 case REF: /* /\1/ */
5110 utf8_fold_flags = 0;
5114 n = ARG(scan); /* which paren pair */
5117 ln = rex->offs[n].start;
5118 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5119 if (rex->lastparen < n || ln == -1)
5120 sayNO; /* Do not match unless seen CLOSEn. */
5121 if (ln == rex->offs[n].end)
5124 s = reginfo->strbeg + ln;
5125 if (type != REF /* REF can do byte comparison */
5126 && (utf8_target || type == REFFU || type == REFFL))
5128 char * limit = reginfo->strend;
5130 /* This call case insensitively compares the entire buffer
5131 * at s, with the current input starting at locinput, but
5132 * not going off the end given by reginfo->strend, and
5133 * returns in <limit> upon success, how much of the
5134 * current input was matched */
5135 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
5136 locinput, &limit, 0, utf8_target, utf8_fold_flags))
5144 /* Not utf8: Inline the first character, for speed. */
5145 if (!NEXTCHR_IS_EOS &&
5146 UCHARAT(s) != nextchr &&
5148 UCHARAT(s) != fold_array[nextchr]))
5150 ln = rex->offs[n].end - ln;
5151 if (locinput + ln > reginfo->strend)
5153 if (ln > 1 && (type == REF
5154 ? memNE(s, locinput, ln)
5155 : ! folder(s, locinput, ln)))
5161 case NOTHING: /* null op; e.g. the 'nothing' following
5162 * the '*' in m{(a+|b)*}' */
5164 case TAIL: /* placeholder while compiling (A|B|C) */
5167 case BACK: /* ??? doesn't appear to be used ??? */
5171 #define ST st->u.eval
5176 regexp_internal *rei;
5177 regnode *startpoint;
5179 case GOSTART: /* (?R) */
5180 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
5181 if (cur_eval && cur_eval->locinput==locinput) {
5182 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
5183 Perl_croak(aTHX_ "Infinite recursion in regex");
5184 if ( ++nochange_depth > max_nochange_depth )
5186 "Pattern subroutine nesting without pos change"
5187 " exceeded limit in regex");
5194 if (OP(scan)==GOSUB) {
5195 startpoint = scan + ARG2L(scan);
5196 ST.close_paren = ARG(scan);
5198 startpoint = rei->program+1;
5202 /* Save all the positions seen so far. */
5203 ST.cp = regcppush(rex, 0, maxopenparen);
5204 REGCP_SET(ST.lastcp);
5206 /* and then jump to the code we share with EVAL */
5207 goto eval_recurse_doit;
5209 assert(0); /* NOTREACHED */
5211 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
5212 if (cur_eval && cur_eval->locinput==locinput) {
5213 if ( ++nochange_depth > max_nochange_depth )
5214 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
5219 /* execute the code in the {...} */
5223 OP * const oop = PL_op;
5224 COP * const ocurcop = PL_curcop;
5228 /* save *all* paren positions */
5229 regcppush(rex, 0, maxopenparen);
5230 REGCP_SET(runops_cp);
5233 caller_cv = find_runcv(NULL);
5237 if (rexi->data->what[n] == 'r') { /* code from an external qr */
5239 (REGEXP*)(rexi->data->data[n])
5242 nop = (OP*)rexi->data->data[n+1];
5244 else if (rexi->data->what[n] == 'l') { /* literal code */
5246 nop = (OP*)rexi->data->data[n];
5247 assert(CvDEPTH(newcv));
5250 /* literal with own CV */
5251 assert(rexi->data->what[n] == 'L');
5252 newcv = rex->qr_anoncv;
5253 nop = (OP*)rexi->data->data[n];
5256 /* normally if we're about to execute code from the same
5257 * CV that we used previously, we just use the existing
5258 * CX stack entry. However, its possible that in the
5259 * meantime we may have backtracked, popped from the save
5260 * stack, and undone the SAVECOMPPAD(s) associated with
5261 * PUSH_MULTICALL; in which case PL_comppad no longer
5262 * points to newcv's pad. */
5263 if (newcv != last_pushed_cv || PL_comppad != last_pad)
5265 U8 flags = (CXp_SUB_RE |
5266 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
5267 if (last_pushed_cv) {
5268 CHANGE_MULTICALL_FLAGS(newcv, flags);
5271 PUSH_MULTICALL_FLAGS(newcv, flags);
5273 last_pushed_cv = newcv;
5276 /* these assignments are just to silence compiler
5278 multicall_cop = NULL;
5281 last_pad = PL_comppad;
5283 /* the initial nextstate you would normally execute
5284 * at the start of an eval (which would cause error
5285 * messages to come from the eval), may be optimised
5286 * away from the execution path in the regex code blocks;
5287 * so manually set PL_curcop to it initially */
5289 OP *o = cUNOPx(nop)->op_first;
5290 assert(o->op_type == OP_NULL);
5291 if (o->op_targ == OP_SCOPE) {
5292 o = cUNOPo->op_first;
5295 assert(o->op_targ == OP_LEAVE);
5296 o = cUNOPo->op_first;
5297 assert(o->op_type == OP_ENTER);
5301 if (o->op_type != OP_STUB) {
5302 assert( o->op_type == OP_NEXTSTATE
5303 || o->op_type == OP_DBSTATE
5304 || (o->op_type == OP_NULL
5305 && ( o->op_targ == OP_NEXTSTATE
5306 || o->op_targ == OP_DBSTATE
5310 PL_curcop = (COP*)o;
5315 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
5316 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
5318 rex->offs[0].end = locinput - reginfo->strbeg;
5319 if (reginfo->info_aux_eval->pos_magic)
5320 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
5321 reginfo->sv, reginfo->strbeg,
5322 locinput - reginfo->strbeg);
5325 SV *sv_mrk = get_sv("REGMARK", 1);
5326 sv_setsv(sv_mrk, sv_yes_mark);
5329 /* we don't use MULTICALL here as we want to call the
5330 * first op of the block of interest, rather than the
5331 * first op of the sub */
5332 before = (IV)(SP-PL_stack_base);
5334 CALLRUNOPS(aTHX); /* Scalar context. */
5336 if ((IV)(SP-PL_stack_base) == before)
5337 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
5343 /* before restoring everything, evaluate the returned
5344 * value, so that 'uninit' warnings don't use the wrong
5345 * PL_op or pad. Also need to process any magic vars
5346 * (e.g. $1) *before* parentheses are restored */
5351 if (logical == 0) /* (?{})/ */
5352 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
5353 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
5354 sw = cBOOL(SvTRUE(ret));
5357 else { /* /(??{}) */
5358 /* if its overloaded, let the regex compiler handle
5359 * it; otherwise extract regex, or stringify */
5360 if (SvGMAGICAL(ret))
5361 ret = sv_mortalcopy(ret);
5362 if (!SvAMAGIC(ret)) {
5366 if (SvTYPE(sv) == SVt_REGEXP)
5367 re_sv = (REGEXP*) sv;
5368 else if (SvSMAGICAL(ret)) {
5369 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
5371 re_sv = (REGEXP *) mg->mg_obj;
5374 /* force any undef warnings here */
5375 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
5376 ret = sv_mortalcopy(ret);
5377 (void) SvPV_force_nolen(ret);
5383 /* *** Note that at this point we don't restore
5384 * PL_comppad, (or pop the CxSUB) on the assumption it may
5385 * be used again soon. This is safe as long as nothing
5386 * in the regexp code uses the pad ! */
5388 PL_curcop = ocurcop;
5389 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
5390 PL_curpm = PL_reg_curpm;
5396 /* only /(??{})/ from now on */
5399 /* extract RE object from returned value; compiling if
5403 re_sv = reg_temp_copy(NULL, re_sv);
5408 if (SvUTF8(ret) && IN_BYTES) {
5409 /* In use 'bytes': make a copy of the octet
5410 * sequence, but without the flag on */
5412 const char *const p = SvPV(ret, len);
5413 ret = newSVpvn_flags(p, len, SVs_TEMP);
5415 if (rex->intflags & PREGf_USE_RE_EVAL)
5416 pm_flags |= PMf_USE_RE_EVAL;
5418 /* if we got here, it should be an engine which
5419 * supports compiling code blocks and stuff */
5420 assert(rex->engine && rex->engine->op_comp);
5421 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
5422 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
5423 rex->engine, NULL, NULL,
5424 /* copy /msix etc to inner pattern */
5429 & (SVs_TEMP | SVs_GMG | SVf_ROK))
5430 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
5431 /* This isn't a first class regexp. Instead, it's
5432 caching a regexp onto an existing, Perl visible
5434 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
5440 RXp_MATCH_COPIED_off(re);
5441 re->subbeg = rex->subbeg;
5442 re->sublen = rex->sublen;
5443 re->suboffset = rex->suboffset;
5444 re->subcoffset = rex->subcoffset;
5446 re->lastcloseparen = 0;
5449 debug_start_match(re_sv, utf8_target, locinput,
5450 reginfo->strend, "Matching embedded");
5452 startpoint = rei->program + 1;
5453 ST.close_paren = 0; /* only used for GOSUB */
5454 /* Save all the seen positions so far. */
5455 ST.cp = regcppush(rex, 0, maxopenparen);
5456 REGCP_SET(ST.lastcp);
5457 /* and set maxopenparen to 0, since we are starting a "fresh" match */
5459 /* run the pattern returned from (??{...}) */
5461 eval_recurse_doit: /* Share code with GOSUB below this line
5462 * At this point we expect the stack context to be
5463 * set up correctly */
5465 /* invalidate the S-L poscache. We're now executing a
5466 * different set of WHILEM ops (and their associated
5467 * indexes) against the same string, so the bits in the
5468 * cache are meaningless. Setting maxiter to zero forces
5469 * the cache to be invalidated and zeroed before reuse.
5470 * XXX This is too dramatic a measure. Ideally we should
5471 * save the old cache and restore when running the outer
5473 reginfo->poscache_maxiter = 0;
5475 /* the new regexp might have a different is_utf8_pat than we do */
5476 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
5478 ST.prev_rex = rex_sv;
5479 ST.prev_curlyx = cur_curlyx;
5481 SET_reg_curpm(rex_sv);
5486 ST.prev_eval = cur_eval;
5488 /* now continue from first node in postoned RE */
5489 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
5490 assert(0); /* NOTREACHED */
5493 case EVAL_AB: /* cleanup after a successful (??{A})B */
5494 /* note: this is called twice; first after popping B, then A */
5495 rex_sv = ST.prev_rex;
5496 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5497 SET_reg_curpm(rex_sv);
5498 rex = ReANY(rex_sv);
5499 rexi = RXi_GET(rex);
5501 /* preserve $^R across LEAVE's. See Bug 121070. */
5502 SV *save_sv= GvSV(PL_replgv);
5503 SvREFCNT_inc(save_sv);
5504 regcpblow(ST.cp); /* LEAVE in disguise */
5505 sv_setsv(GvSV(PL_replgv), save_sv);
5506 SvREFCNT_dec(save_sv);
5508 cur_eval = ST.prev_eval;
5509 cur_curlyx = ST.prev_curlyx;
5511 /* Invalidate cache. See "invalidate" comment above. */
5512 reginfo->poscache_maxiter = 0;
5513 if ( nochange_depth )
5518 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
5519 /* note: this is called twice; first after popping B, then A */
5520 rex_sv = ST.prev_rex;
5521 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
5522 SET_reg_curpm(rex_sv);
5523 rex = ReANY(rex_sv);
5524 rexi = RXi_GET(rex);
5526 REGCP_UNWIND(ST.lastcp);
5527 regcppop(rex, &maxopenparen);
5528 cur_eval = ST.prev_eval;
5529 cur_curlyx = ST.prev_curlyx;
5530 /* Invalidate cache. See "invalidate" comment above. */
5531 reginfo->poscache_maxiter = 0;
5532 if ( nochange_depth )
5538 n = ARG(scan); /* which paren pair */
5539 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
5540 if (n > maxopenparen)
5542 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
5543 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
5547 (IV)rex->offs[n].start_tmp,
5553 /* XXX really need to log other places start/end are set too */
5554 #define CLOSE_CAPTURE \
5555 rex->offs[n].start = rex->offs[n].start_tmp; \
5556 rex->offs[n].end = locinput - reginfo->strbeg; \
5557 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
5558 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
5560 PTR2UV(rex->offs), \
5562 (IV)rex->offs[n].start, \
5563 (IV)rex->offs[n].end \
5567 n = ARG(scan); /* which paren pair */
5569 if (n > rex->lastparen)
5571 rex->lastcloseparen = n;
5572 if (cur_eval && cur_eval->u.eval.close_paren == n) {
5577 case ACCEPT: /* (*ACCEPT) */
5581 cursor && OP(cursor)!=END;
5582 cursor=regnext(cursor))
5584 if ( OP(cursor)==CLOSE ){
5586 if ( n <= lastopen ) {
5588 if (n > rex->lastparen)
5590 rex->lastcloseparen = n;
5591 if ( n == ARG(scan) || (cur_eval &&
5592 cur_eval->u.eval.close_paren == n))
5601 case GROUPP: /* (?(1)) */
5602 n = ARG(scan); /* which paren pair */
5603 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
5606 case NGROUPP: /* (?(<name>)) */
5607 /* reg_check_named_buff_matched returns 0 for no match */
5608 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
5611 case INSUBP: /* (?(R)) */
5613 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
5616 case DEFINEP: /* (?(DEFINE)) */
5620 case IFTHEN: /* (?(cond)A|B) */
5621 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
5623 next = NEXTOPER(NEXTOPER(scan));
5625 next = scan + ARG(scan);
5626 if (OP(next) == IFTHEN) /* Fake one. */
5627 next = NEXTOPER(NEXTOPER(next));
5631 case LOGICAL: /* modifier for EVAL and IFMATCH */
5632 logical = scan->flags;
5635 /*******************************************************************
5637 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
5638 pattern, where A and B are subpatterns. (For simple A, CURLYM or
5639 STAR/PLUS/CURLY/CURLYN are used instead.)
5641 A*B is compiled as <CURLYX><A><WHILEM><B>
5643 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
5644 state, which contains the current count, initialised to -1. It also sets
5645 cur_curlyx to point to this state, with any previous value saved in the
5648 CURLYX then jumps straight to the WHILEM op, rather than executing A,
5649 since the pattern may possibly match zero times (i.e. it's a while {} loop
5650 rather than a do {} while loop).
5652 Each entry to WHILEM represents a successful match of A. The count in the
5653 CURLYX block is incremented, another WHILEM state is pushed, and execution
5654 passes to A or B depending on greediness and the current count.
5656 For example, if matching against the string a1a2a3b (where the aN are
5657 substrings that match /A/), then the match progresses as follows: (the
5658 pushed states are interspersed with the bits of strings matched so far):
5661 <CURLYX cnt=0><WHILEM>
5662 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
5663 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
5664 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
5665 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
5667 (Contrast this with something like CURLYM, which maintains only a single
5671 a1 <CURLYM cnt=1> a2
5672 a1 a2 <CURLYM cnt=2> a3
5673 a1 a2 a3 <CURLYM cnt=3> b
5676 Each WHILEM state block marks a point to backtrack to upon partial failure
5677 of A or B, and also contains some minor state data related to that
5678 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
5679 overall state, such as the count, and pointers to the A and B ops.
5681 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
5682 must always point to the *current* CURLYX block, the rules are:
5684 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
5685 and set cur_curlyx to point the new block.
5687 When popping the CURLYX block after a successful or unsuccessful match,
5688 restore the previous cur_curlyx.
5690 When WHILEM is about to execute B, save the current cur_curlyx, and set it
5691 to the outer one saved in the CURLYX block.
5693 When popping the WHILEM block after a successful or unsuccessful B match,
5694 restore the previous cur_curlyx.
5696 Here's an example for the pattern (AI* BI)*BO
5697 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
5700 curlyx backtrack stack
5701 ------ ---------------
5703 CO <CO prev=NULL> <WO>
5704 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5705 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5706 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
5708 At this point the pattern succeeds, and we work back down the stack to
5709 clean up, restoring as we go:
5711 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5712 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5713 CO <CO prev=NULL> <WO>
5716 *******************************************************************/
5718 #define ST st->u.curlyx
5720 case CURLYX: /* start of /A*B/ (for complex A) */
5722 /* No need to save/restore up to this paren */
5723 I32 parenfloor = scan->flags;
5725 assert(next); /* keep Coverity happy */
5726 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
5729 /* XXXX Probably it is better to teach regpush to support
5730 parenfloor > maxopenparen ... */
5731 if (parenfloor > (I32)rex->lastparen)
5732 parenfloor = rex->lastparen; /* Pessimization... */
5734 ST.prev_curlyx= cur_curlyx;
5736 ST.cp = PL_savestack_ix;
5738 /* these fields contain the state of the current curly.
5739 * they are accessed by subsequent WHILEMs */
5740 ST.parenfloor = parenfloor;
5745 ST.count = -1; /* this will be updated by WHILEM */
5746 ST.lastloc = NULL; /* this will be updated by WHILEM */
5748 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
5749 assert(0); /* NOTREACHED */
5752 case CURLYX_end: /* just finished matching all of A*B */
5753 cur_curlyx = ST.prev_curlyx;
5755 assert(0); /* NOTREACHED */
5757 case CURLYX_end_fail: /* just failed to match all of A*B */
5759 cur_curlyx = ST.prev_curlyx;
5761 assert(0); /* NOTREACHED */
5765 #define ST st->u.whilem
5767 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
5769 /* see the discussion above about CURLYX/WHILEM */
5771 int min = ARG1(cur_curlyx->u.curlyx.me);
5772 int max = ARG2(cur_curlyx->u.curlyx.me);
5773 regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
5775 assert(cur_curlyx); /* keep Coverity happy */
5776 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
5777 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
5778 ST.cache_offset = 0;
5782 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5783 "%*s whilem: matched %ld out of %d..%d\n",
5784 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
5787 /* First just match a string of min A's. */
5790 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5792 cur_curlyx->u.curlyx.lastloc = locinput;
5793 REGCP_SET(ST.lastcp);
5795 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
5796 assert(0); /* NOTREACHED */
5799 /* If degenerate A matches "", assume A done. */
5801 if (locinput == cur_curlyx->u.curlyx.lastloc) {
5802 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5803 "%*s whilem: empty match detected, trying continuation...\n",
5804 REPORT_CODE_OFF+depth*2, "")
5806 goto do_whilem_B_max;
5809 /* super-linear cache processing.
5811 * The idea here is that for certain types of CURLYX/WHILEM -
5812 * principally those whose upper bound is infinity (and
5813 * excluding regexes that have things like \1 and other very
5814 * non-regular expresssiony things), then if a pattern like
5815 * /....A*.../ fails and we backtrack to the WHILEM, then we
5816 * make a note that this particular WHILEM op was at string
5817 * position 47 (say) when the rest of pattern failed. Then, if
5818 * we ever find ourselves back at that WHILEM, and at string
5819 * position 47 again, we can just fail immediately rather than
5820 * running the rest of the pattern again.
5822 * This is very handy when patterns start to go
5823 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
5824 * with a combinatorial explosion of backtracking.
5826 * The cache is implemented as a bit array, with one bit per
5827 * string byte position per WHILEM op (up to 16) - so its
5828 * between 0.25 and 2x the string size.
5830 * To avoid allocating a poscache buffer every time, we do an
5831 * initially countdown; only after we have executed a WHILEM
5832 * op (string-length x #WHILEMs) times do we allocate the
5835 * The top 4 bits of scan->flags byte say how many different
5836 * relevant CURLLYX/WHILEM op pairs there are, while the
5837 * bottom 4-bits is the identifying index number of this
5843 if (!reginfo->poscache_maxiter) {
5844 /* start the countdown: Postpone detection until we
5845 * know the match is not *that* much linear. */
5846 reginfo->poscache_maxiter
5847 = (reginfo->strend - reginfo->strbeg + 1)
5849 /* possible overflow for long strings and many CURLYX's */
5850 if (reginfo->poscache_maxiter < 0)
5851 reginfo->poscache_maxiter = I32_MAX;
5852 reginfo->poscache_iter = reginfo->poscache_maxiter;
5855 if (reginfo->poscache_iter-- == 0) {
5856 /* initialise cache */
5857 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
5858 regmatch_info_aux *const aux = reginfo->info_aux;
5859 if (aux->poscache) {
5860 if ((SSize_t)reginfo->poscache_size < size) {
5861 Renew(aux->poscache, size, char);
5862 reginfo->poscache_size = size;
5864 Zero(aux->poscache, size, char);
5867 reginfo->poscache_size = size;
5868 Newxz(aux->poscache, size, char);
5870 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5871 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
5872 PL_colors[4], PL_colors[5])
5876 if (reginfo->poscache_iter < 0) {
5877 /* have we already failed at this position? */
5878 SSize_t offset, mask;
5880 reginfo->poscache_iter = -1; /* stop eventual underflow */
5881 offset = (scan->flags & 0xf) - 1
5882 + (locinput - reginfo->strbeg)
5884 mask = 1 << (offset % 8);
5886 if (reginfo->info_aux->poscache[offset] & mask) {
5887 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5888 "%*s whilem: (cache) already tried at this position...\n",
5889 REPORT_CODE_OFF+depth*2, "")
5891 sayNO; /* cache records failure */
5893 ST.cache_offset = offset;
5894 ST.cache_mask = mask;
5898 /* Prefer B over A for minimal matching. */
5900 if (cur_curlyx->u.curlyx.minmod) {
5901 ST.save_curlyx = cur_curlyx;
5902 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5903 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
5905 REGCP_SET(ST.lastcp);
5906 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
5908 assert(0); /* NOTREACHED */
5911 /* Prefer A over B for maximal matching. */
5913 if (n < max) { /* More greed allowed? */
5914 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5916 cur_curlyx->u.curlyx.lastloc = locinput;
5917 REGCP_SET(ST.lastcp);
5918 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
5919 assert(0); /* NOTREACHED */
5921 goto do_whilem_B_max;
5923 assert(0); /* NOTREACHED */
5925 case WHILEM_B_min: /* just matched B in a minimal match */
5926 case WHILEM_B_max: /* just matched B in a maximal match */
5927 cur_curlyx = ST.save_curlyx;
5929 assert(0); /* NOTREACHED */
5931 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
5932 cur_curlyx = ST.save_curlyx;
5933 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5934 cur_curlyx->u.curlyx.count--;
5936 assert(0); /* NOTREACHED */
5938 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
5940 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
5941 REGCP_UNWIND(ST.lastcp);
5942 regcppop(rex, &maxopenparen);
5943 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5944 cur_curlyx->u.curlyx.count--;
5946 assert(0); /* NOTREACHED */
5948 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5949 REGCP_UNWIND(ST.lastcp);
5950 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
5951 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5952 "%*s whilem: failed, trying continuation...\n",
5953 REPORT_CODE_OFF+depth*2, "")
5956 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5957 && ckWARN(WARN_REGEXP)
5958 && !reginfo->warned)
5960 reginfo->warned = TRUE;
5961 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5962 "Complex regular subexpression recursion limit (%d) "
5968 ST.save_curlyx = cur_curlyx;
5969 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5970 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
5972 assert(0); /* NOTREACHED */
5974 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
5975 cur_curlyx = ST.save_curlyx;
5976 REGCP_UNWIND(ST.lastcp);
5977 regcppop(rex, &maxopenparen);
5979 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
5980 /* Maximum greed exceeded */
5981 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5982 && ckWARN(WARN_REGEXP)
5983 && !reginfo->warned)
5985 reginfo->warned = TRUE;
5986 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5987 "Complex regular subexpression recursion "
5988 "limit (%d) exceeded",
5991 cur_curlyx->u.curlyx.count--;
5995 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5996 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
5998 /* Try grabbing another A and see if it helps. */
5999 cur_curlyx->u.curlyx.lastloc = locinput;
6000 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6002 REGCP_SET(ST.lastcp);
6003 PUSH_STATE_GOTO(WHILEM_A_min,
6004 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6006 assert(0); /* NOTREACHED */
6009 #define ST st->u.branch
6011 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6012 next = scan + ARG(scan);
6015 scan = NEXTOPER(scan);
6018 case BRANCH: /* /(...|A|...)/ */
6019 scan = NEXTOPER(scan); /* scan now points to inner node */
6020 ST.lastparen = rex->lastparen;
6021 ST.lastcloseparen = rex->lastcloseparen;
6022 ST.next_branch = next;
6025 /* Now go into the branch */
6027 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
6029 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
6031 assert(0); /* NOTREACHED */
6033 case CUTGROUP: /* /(*THEN)/ */
6034 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
6035 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6036 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
6037 assert(0); /* NOTREACHED */
6039 case CUTGROUP_next_fail:
6042 if (st->u.mark.mark_name)
6043 sv_commit = st->u.mark.mark_name;
6045 assert(0); /* NOTREACHED */
6049 assert(0); /* NOTREACHED */
6051 case BRANCH_next_fail: /* that branch failed; try the next, if any */
6056 REGCP_UNWIND(ST.cp);
6057 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6058 scan = ST.next_branch;
6059 /* no more branches? */
6060 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
6062 PerlIO_printf( Perl_debug_log,
6063 "%*s %sBRANCH failed...%s\n",
6064 REPORT_CODE_OFF+depth*2, "",
6070 continue; /* execute next BRANCH[J] op */
6071 assert(0); /* NOTREACHED */
6073 case MINMOD: /* next op will be non-greedy, e.g. A*? */
6078 #define ST st->u.curlym
6080 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
6082 /* This is an optimisation of CURLYX that enables us to push
6083 * only a single backtracking state, no matter how many matches
6084 * there are in {m,n}. It relies on the pattern being constant
6085 * length, with no parens to influence future backrefs
6089 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6091 ST.lastparen = rex->lastparen;
6092 ST.lastcloseparen = rex->lastcloseparen;
6094 /* if paren positive, emulate an OPEN/CLOSE around A */
6096 U32 paren = ST.me->flags;
6097 if (paren > maxopenparen)
6098 maxopenparen = paren;
6099 scan += NEXT_OFF(scan); /* Skip former OPEN. */
6107 ST.c1 = CHRTEST_UNINIT;
6110 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
6113 curlym_do_A: /* execute the A in /A{m,n}B/ */
6114 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
6115 assert(0); /* NOTREACHED */
6117 case CURLYM_A: /* we've just matched an A */
6119 /* after first match, determine A's length: u.curlym.alen */
6120 if (ST.count == 1) {
6121 if (reginfo->is_utf8_target) {
6122 char *s = st->locinput;
6123 while (s < locinput) {
6129 ST.alen = locinput - st->locinput;
6132 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
6135 PerlIO_printf(Perl_debug_log,
6136 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
6137 (int)(REPORT_CODE_OFF+(depth*2)), "",
6138 (IV) ST.count, (IV)ST.alen)
6141 if (cur_eval && cur_eval->u.eval.close_paren &&
6142 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6146 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
6147 if ( max == REG_INFTY || ST.count < max )
6148 goto curlym_do_A; /* try to match another A */
6150 goto curlym_do_B; /* try to match B */
6152 case CURLYM_A_fail: /* just failed to match an A */
6153 REGCP_UNWIND(ST.cp);
6155 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
6156 || (cur_eval && cur_eval->u.eval.close_paren &&
6157 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
6160 curlym_do_B: /* execute the B in /A{m,n}B/ */
6161 if (ST.c1 == CHRTEST_UNINIT) {
6162 /* calculate c1 and c2 for possible match of 1st char
6163 * following curly */
6164 ST.c1 = ST.c2 = CHRTEST_VOID;
6165 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
6166 regnode *text_node = ST.B;
6167 if (! HAS_TEXT(text_node))
6168 FIND_NEXT_IMPT(text_node);
6171 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
6173 But the former is redundant in light of the latter.
6175 if this changes back then the macro for
6176 IS_TEXT and friends need to change.
6178 if (PL_regkind[OP(text_node)] == EXACT) {
6179 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6180 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6190 PerlIO_printf(Perl_debug_log,
6191 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
6192 (int)(REPORT_CODE_OFF+(depth*2)),
6195 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
6196 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
6197 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6198 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6200 /* simulate B failing */
6202 PerlIO_printf(Perl_debug_log,
6203 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
6204 (int)(REPORT_CODE_OFF+(depth*2)),"",
6205 valid_utf8_to_uvchr((U8 *) locinput, NULL),
6206 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
6207 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
6209 state_num = CURLYM_B_fail;
6210 goto reenter_switch;
6213 else if (nextchr != ST.c1 && nextchr != ST.c2) {
6214 /* simulate B failing */
6216 PerlIO_printf(Perl_debug_log,
6217 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
6218 (int)(REPORT_CODE_OFF+(depth*2)),"",
6219 (int) nextchr, ST.c1, ST.c2)
6221 state_num = CURLYM_B_fail;
6222 goto reenter_switch;
6227 /* emulate CLOSE: mark current A as captured */
6228 I32 paren = ST.me->flags;
6230 rex->offs[paren].start
6231 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
6232 rex->offs[paren].end = locinput - reginfo->strbeg;
6233 if ((U32)paren > rex->lastparen)
6234 rex->lastparen = paren;
6235 rex->lastcloseparen = paren;
6238 rex->offs[paren].end = -1;
6239 if (cur_eval && cur_eval->u.eval.close_paren &&
6240 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
6249 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
6250 assert(0); /* NOTREACHED */
6252 case CURLYM_B_fail: /* just failed to match a B */
6253 REGCP_UNWIND(ST.cp);
6254 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6256 I32 max = ARG2(ST.me);
6257 if (max != REG_INFTY && ST.count == max)
6259 goto curlym_do_A; /* try to match a further A */
6261 /* backtrack one A */
6262 if (ST.count == ARG1(ST.me) /* min */)
6265 SET_locinput(HOPc(locinput, -ST.alen));
6266 goto curlym_do_B; /* try to match B */
6269 #define ST st->u.curly
6271 #define CURLY_SETPAREN(paren, success) \
6274 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
6275 rex->offs[paren].end = locinput - reginfo->strbeg; \
6276 if (paren > rex->lastparen) \
6277 rex->lastparen = paren; \
6278 rex->lastcloseparen = paren; \
6281 rex->offs[paren].end = -1; \
6282 rex->lastparen = ST.lastparen; \
6283 rex->lastcloseparen = ST.lastcloseparen; \
6287 case STAR: /* /A*B/ where A is width 1 char */
6291 scan = NEXTOPER(scan);
6294 case PLUS: /* /A+B/ where A is width 1 char */
6298 scan = NEXTOPER(scan);
6301 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
6302 ST.paren = scan->flags; /* Which paren to set */
6303 ST.lastparen = rex->lastparen;
6304 ST.lastcloseparen = rex->lastcloseparen;
6305 if (ST.paren > maxopenparen)
6306 maxopenparen = ST.paren;
6307 ST.min = ARG1(scan); /* min to match */
6308 ST.max = ARG2(scan); /* max to match */
6309 if (cur_eval && cur_eval->u.eval.close_paren &&
6310 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6314 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
6317 case CURLY: /* /A{m,n}B/ where A is width 1 char */
6319 ST.min = ARG1(scan); /* min to match */
6320 ST.max = ARG2(scan); /* max to match */
6321 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
6324 * Lookahead to avoid useless match attempts
6325 * when we know what character comes next.
6327 * Used to only do .*x and .*?x, but now it allows
6328 * for )'s, ('s and (?{ ... })'s to be in the way
6329 * of the quantifier and the EXACT-like node. -- japhy
6332 assert(ST.min <= ST.max);
6333 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
6334 ST.c1 = ST.c2 = CHRTEST_VOID;
6337 regnode *text_node = next;
6339 if (! HAS_TEXT(text_node))
6340 FIND_NEXT_IMPT(text_node);
6342 if (! HAS_TEXT(text_node))
6343 ST.c1 = ST.c2 = CHRTEST_VOID;
6345 if ( PL_regkind[OP(text_node)] != EXACT ) {
6346 ST.c1 = ST.c2 = CHRTEST_VOID;
6350 /* Currently we only get here when
6352 PL_rekind[OP(text_node)] == EXACT
6354 if this changes back then the macro for IS_TEXT and
6355 friends need to change. */
6356 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
6357 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
6369 char *li = locinput;
6372 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
6378 if (ST.c1 == CHRTEST_VOID)
6379 goto curly_try_B_min;
6381 ST.oldloc = locinput;
6383 /* set ST.maxpos to the furthest point along the
6384 * string that could possibly match */
6385 if (ST.max == REG_INFTY) {
6386 ST.maxpos = reginfo->strend - 1;
6388 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
6391 else if (utf8_target) {
6392 int m = ST.max - ST.min;
6393 for (ST.maxpos = locinput;
6394 m >0 && ST.maxpos < reginfo->strend; m--)
6395 ST.maxpos += UTF8SKIP(ST.maxpos);
6398 ST.maxpos = locinput + ST.max - ST.min;
6399 if (ST.maxpos >= reginfo->strend)
6400 ST.maxpos = reginfo->strend - 1;
6402 goto curly_try_B_min_known;
6406 /* avoid taking address of locinput, so it can remain
6408 char *li = locinput;
6409 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
6410 if (ST.count < ST.min)
6413 if ((ST.count > ST.min)
6414 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
6416 /* A{m,n} must come at the end of the string, there's
6417 * no point in backing off ... */
6419 /* ...except that $ and \Z can match before *and* after
6420 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
6421 We may back off by one in this case. */
6422 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
6426 goto curly_try_B_max;
6428 assert(0); /* NOTREACHED */
6431 case CURLY_B_min_known_fail:
6432 /* failed to find B in a non-greedy match where c1,c2 valid */
6434 REGCP_UNWIND(ST.cp);
6436 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6438 /* Couldn't or didn't -- move forward. */
6439 ST.oldloc = locinput;
6441 locinput += UTF8SKIP(locinput);
6445 curly_try_B_min_known:
6446 /* find the next place where 'B' could work, then call B */
6450 n = (ST.oldloc == locinput) ? 0 : 1;
6451 if (ST.c1 == ST.c2) {
6452 /* set n to utf8_distance(oldloc, locinput) */
6453 while (locinput <= ST.maxpos
6454 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
6456 locinput += UTF8SKIP(locinput);
6461 /* set n to utf8_distance(oldloc, locinput) */
6462 while (locinput <= ST.maxpos
6463 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6464 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6466 locinput += UTF8SKIP(locinput);
6471 else { /* Not utf8_target */
6472 if (ST.c1 == ST.c2) {
6473 while (locinput <= ST.maxpos &&
6474 UCHARAT(locinput) != ST.c1)
6478 while (locinput <= ST.maxpos
6479 && UCHARAT(locinput) != ST.c1
6480 && UCHARAT(locinput) != ST.c2)
6483 n = locinput - ST.oldloc;
6485 if (locinput > ST.maxpos)
6488 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
6489 * at b; check that everything between oldloc and
6490 * locinput matches */
6491 char *li = ST.oldloc;
6493 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
6495 assert(n == REG_INFTY || locinput == li);
6497 CURLY_SETPAREN(ST.paren, ST.count);
6498 if (cur_eval && cur_eval->u.eval.close_paren &&
6499 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6502 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
6504 assert(0); /* NOTREACHED */
6507 case CURLY_B_min_fail:
6508 /* failed to find B in a non-greedy match where c1,c2 invalid */
6510 REGCP_UNWIND(ST.cp);
6512 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6514 /* failed -- move forward one */
6516 char *li = locinput;
6517 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
6524 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
6525 ST.count > 0)) /* count overflow ? */
6528 CURLY_SETPAREN(ST.paren, ST.count);
6529 if (cur_eval && cur_eval->u.eval.close_paren &&
6530 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6533 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
6537 assert(0); /* NOTREACHED */
6541 /* a successful greedy match: now try to match B */
6542 if (cur_eval && cur_eval->u.eval.close_paren &&
6543 cur_eval->u.eval.close_paren == (U32)ST.paren) {
6547 bool could_match = locinput < reginfo->strend;
6549 /* If it could work, try it. */
6550 if (ST.c1 != CHRTEST_VOID && could_match) {
6551 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
6553 could_match = memEQ(locinput,
6558 UTF8SKIP(locinput));
6561 could_match = UCHARAT(locinput) == ST.c1
6562 || UCHARAT(locinput) == ST.c2;
6565 if (ST.c1 == CHRTEST_VOID || could_match) {
6566 CURLY_SETPAREN(ST.paren, ST.count);
6567 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
6568 assert(0); /* NOTREACHED */
6573 case CURLY_B_max_fail:
6574 /* failed to find B in a greedy match */
6576 REGCP_UNWIND(ST.cp);
6578 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6581 if (--ST.count < ST.min)
6583 locinput = HOPc(locinput, -1);
6584 goto curly_try_B_max;
6588 case END: /* last op of main pattern */
6591 /* we've just finished A in /(??{A})B/; now continue with B */
6593 st->u.eval.prev_rex = rex_sv; /* inner */
6595 /* Save *all* the positions. */
6596 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
6597 rex_sv = cur_eval->u.eval.prev_rex;
6598 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6599 SET_reg_curpm(rex_sv);
6600 rex = ReANY(rex_sv);
6601 rexi = RXi_GET(rex);
6602 cur_curlyx = cur_eval->u.eval.prev_curlyx;
6604 REGCP_SET(st->u.eval.lastcp);
6606 /* Restore parens of the outer rex without popping the
6608 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
6611 st->u.eval.prev_eval = cur_eval;
6612 cur_eval = cur_eval->u.eval.prev_eval;
6614 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
6615 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
6616 if ( nochange_depth )
6619 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
6620 locinput); /* match B */
6623 if (locinput < reginfo->till) {
6624 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6625 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
6627 (long)(locinput - startpos),
6628 (long)(reginfo->till - startpos),
6631 sayNO_SILENT; /* Cannot match: too short. */
6633 sayYES; /* Success! */
6635 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
6637 PerlIO_printf(Perl_debug_log,
6638 "%*s %ssubpattern success...%s\n",
6639 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
6640 sayYES; /* Success! */
6643 #define ST st->u.ifmatch
6648 case SUSPEND: /* (?>A) */
6650 newstart = locinput;
6653 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
6655 goto ifmatch_trivial_fail_test;
6657 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
6659 ifmatch_trivial_fail_test:
6661 char * const s = HOPBACKc(locinput, scan->flags);
6666 sw = 1 - cBOOL(ST.wanted);
6670 next = scan + ARG(scan);
6678 newstart = locinput;
6682 ST.logical = logical;
6683 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
6685 /* execute body of (?...A) */
6686 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
6687 assert(0); /* NOTREACHED */
6690 case IFMATCH_A_fail: /* body of (?...A) failed */
6691 ST.wanted = !ST.wanted;
6694 case IFMATCH_A: /* body of (?...A) succeeded */
6696 sw = cBOOL(ST.wanted);
6698 else if (!ST.wanted)
6701 if (OP(ST.me) != SUSPEND) {
6702 /* restore old position except for (?>...) */
6703 locinput = st->locinput;
6705 scan = ST.me + ARG(ST.me);
6708 continue; /* execute B */
6712 case LONGJMP: /* alternative with many branches compiles to
6713 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
6714 next = scan + ARG(scan);
6719 case COMMIT: /* (*COMMIT) */
6720 reginfo->cutpoint = reginfo->strend;
6723 case PRUNE: /* (*PRUNE) */
6725 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6726 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
6727 assert(0); /* NOTREACHED */
6729 case COMMIT_next_fail:
6733 case OPFAIL: /* (*FAIL) */
6735 assert(0); /* NOTREACHED */
6737 #define ST st->u.mark
6738 case MARKPOINT: /* (*MARK:foo) */
6739 ST.prev_mark = mark_state;
6740 ST.mark_name = sv_commit = sv_yes_mark
6741 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6743 ST.mark_loc = locinput;
6744 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
6745 assert(0); /* NOTREACHED */
6747 case MARKPOINT_next:
6748 mark_state = ST.prev_mark;
6750 assert(0); /* NOTREACHED */
6752 case MARKPOINT_next_fail:
6753 if (popmark && sv_eq(ST.mark_name,popmark))
6755 if (ST.mark_loc > startpoint)
6756 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6757 popmark = NULL; /* we found our mark */
6758 sv_commit = ST.mark_name;
6761 PerlIO_printf(Perl_debug_log,
6762 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
6763 REPORT_CODE_OFF+depth*2, "",
6764 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
6767 mark_state = ST.prev_mark;
6768 sv_yes_mark = mark_state ?
6769 mark_state->u.mark.mark_name : NULL;
6771 assert(0); /* NOTREACHED */
6773 case SKIP: /* (*SKIP) */
6775 /* (*SKIP) : if we fail we cut here*/
6776 ST.mark_name = NULL;
6777 ST.mark_loc = locinput;
6778 PUSH_STATE_GOTO(SKIP_next,next, locinput);
6780 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
6781 otherwise do nothing. Meaning we need to scan
6783 regmatch_state *cur = mark_state;
6784 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6787 if ( sv_eq( cur->u.mark.mark_name,
6790 ST.mark_name = find;
6791 PUSH_STATE_GOTO( SKIP_next, next, locinput);
6793 cur = cur->u.mark.prev_mark;
6796 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
6799 case SKIP_next_fail:
6801 /* (*CUT:NAME) - Set up to search for the name as we
6802 collapse the stack*/
6803 popmark = ST.mark_name;
6805 /* (*CUT) - No name, we cut here.*/
6806 if (ST.mark_loc > startpoint)
6807 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6808 /* but we set sv_commit to latest mark_name if there
6809 is one so they can test to see how things lead to this
6812 sv_commit=mark_state->u.mark.mark_name;
6816 assert(0); /* NOTREACHED */
6819 case LNBREAK: /* \R */
6820 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
6827 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
6828 PTR2UV(scan), OP(scan));
6829 Perl_croak(aTHX_ "regexp memory corruption");
6831 /* this is a point to jump to in order to increment
6832 * locinput by one character */
6834 assert(!NEXTCHR_IS_EOS);
6836 locinput += PL_utf8skip[nextchr];
6837 /* locinput is allowed to go 1 char off the end, but not 2+ */
6838 if (locinput > reginfo->strend)
6847 /* switch break jumps here */
6848 scan = next; /* prepare to execute the next op and ... */
6849 continue; /* ... jump back to the top, reusing st */
6850 assert(0); /* NOTREACHED */
6853 /* push a state that backtracks on success */
6854 st->u.yes.prev_yes_state = yes_state;
6858 /* push a new regex state, then continue at scan */
6860 regmatch_state *newst;
6863 regmatch_state *cur = st;
6864 regmatch_state *curyes = yes_state;
6866 regmatch_slab *slab = PL_regmatch_slab;
6867 for (;curd > -1;cur--,curd--) {
6868 if (cur < SLAB_FIRST(slab)) {
6870 cur = SLAB_LAST(slab);
6872 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
6873 REPORT_CODE_OFF + 2 + depth * 2,"",
6874 curd, PL_reg_name[cur->resume_state],
6875 (curyes == cur) ? "yes" : ""
6878 curyes = cur->u.yes.prev_yes_state;
6881 DEBUG_STATE_pp("push")
6884 st->locinput = locinput;
6886 if (newst > SLAB_LAST(PL_regmatch_slab))
6887 newst = S_push_slab(aTHX);
6888 PL_regmatch_state = newst;
6890 locinput = pushinput;
6893 assert(0); /* NOTREACHED */
6898 * We get here only if there's trouble -- normally "case END" is
6899 * the terminating point.
6901 Perl_croak(aTHX_ "corrupted regexp pointers");
6907 /* we have successfully completed a subexpression, but we must now
6908 * pop to the state marked by yes_state and continue from there */
6909 assert(st != yes_state);
6911 while (st != yes_state) {
6913 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6914 PL_regmatch_slab = PL_regmatch_slab->prev;
6915 st = SLAB_LAST(PL_regmatch_slab);
6919 DEBUG_STATE_pp("pop (no final)");
6921 DEBUG_STATE_pp("pop (yes)");
6927 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
6928 || yes_state > SLAB_LAST(PL_regmatch_slab))
6930 /* not in this slab, pop slab */
6931 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
6932 PL_regmatch_slab = PL_regmatch_slab->prev;
6933 st = SLAB_LAST(PL_regmatch_slab);
6935 depth -= (st - yes_state);
6938 yes_state = st->u.yes.prev_yes_state;
6939 PL_regmatch_state = st;
6942 locinput= st->locinput;
6943 state_num = st->resume_state + no_final;
6944 goto reenter_switch;
6947 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6948 PL_colors[4], PL_colors[5]));
6950 if (reginfo->info_aux_eval) {
6951 /* each successfully executed (?{...}) block does the equivalent of
6952 * local $^R = do {...}
6953 * When popping the save stack, all these locals would be undone;
6954 * bypass this by setting the outermost saved $^R to the latest
6956 /* I dont know if this is needed or works properly now.
6957 * see code related to PL_replgv elsewhere in this file.
6960 if (oreplsv != GvSV(PL_replgv))
6961 sv_setsv(oreplsv, GvSV(PL_replgv));
6968 PerlIO_printf(Perl_debug_log,
6969 "%*s %sfailed...%s\n",
6970 REPORT_CODE_OFF+depth*2, "",
6971 PL_colors[4], PL_colors[5])
6983 /* there's a previous state to backtrack to */
6985 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6986 PL_regmatch_slab = PL_regmatch_slab->prev;
6987 st = SLAB_LAST(PL_regmatch_slab);
6989 PL_regmatch_state = st;
6990 locinput= st->locinput;
6992 DEBUG_STATE_pp("pop");
6994 if (yes_state == st)
6995 yes_state = st->u.yes.prev_yes_state;
6997 state_num = st->resume_state + 1; /* failure = success + 1 */
6998 goto reenter_switch;
7003 if (rex->intflags & PREGf_VERBARG_SEEN) {
7004 SV *sv_err = get_sv("REGERROR", 1);
7005 SV *sv_mrk = get_sv("REGMARK", 1);
7007 sv_commit = &PL_sv_no;
7009 sv_yes_mark = &PL_sv_yes;
7012 sv_commit = &PL_sv_yes;
7013 sv_yes_mark = &PL_sv_no;
7015 sv_setsv(sv_err, sv_commit);
7016 sv_setsv(sv_mrk, sv_yes_mark);
7020 if (last_pushed_cv) {
7023 PERL_UNUSED_VAR(SP);
7026 assert(!result || locinput - reginfo->strbeg >= 0);
7027 return result ? locinput - reginfo->strbeg : -1;
7031 - regrepeat - repeatedly match something simple, report how many
7033 * What 'simple' means is a node which can be the operand of a quantifier like
7036 * startposp - pointer a pointer to the start position. This is updated
7037 * to point to the byte following the highest successful
7039 * p - the regnode to be repeatedly matched against.
7040 * reginfo - struct holding match state, such as strend
7041 * max - maximum number of things to match.
7042 * depth - (for debugging) backtracking depth.
7045 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
7046 regmatch_info *const reginfo, I32 max, int depth)
7049 char *scan; /* Pointer to current position in target string */
7051 char *loceol = reginfo->strend; /* local version */
7052 I32 hardcount = 0; /* How many matches so far */
7053 bool utf8_target = reginfo->is_utf8_target;
7054 int to_complement = 0; /* Invert the result? */
7056 _char_class_number classnum;
7058 PERL_UNUSED_ARG(depth);
7061 PERL_ARGS_ASSERT_REGREPEAT;
7064 if (max == REG_INFTY)
7066 else if (! utf8_target && loceol - scan > max)
7067 loceol = scan + max;
7069 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
7070 * to the maximum of how far we should go in it (leaving it set to the real
7071 * end, if the maximum permissible would take us beyond that). This allows
7072 * us to make the loop exit condition that we haven't gone past <loceol> to
7073 * also mean that we haven't exceeded the max permissible count, saving a
7074 * test each time through the loop. But it assumes that the OP matches a
7075 * single byte, which is true for most of the OPs below when applied to a
7076 * non-UTF-8 target. Those relatively few OPs that don't have this
7077 * characteristic will have to compensate.
7079 * There is no adjustment for UTF-8 targets, as the number of bytes per
7080 * character varies. OPs will have to test both that the count is less
7081 * than the max permissible (using <hardcount> to keep track), and that we
7082 * are still within the bounds of the string (using <loceol>. A few OPs
7083 * match a single byte no matter what the encoding. They can omit the max
7084 * test if, for the UTF-8 case, they do the adjustment that was skipped
7087 * Thus, the code above sets things up for the common case; and exceptional
7088 * cases need extra work; the common case is to make sure <scan> doesn't
7089 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
7090 * count doesn't exceed the maximum permissible */
7095 while (scan < loceol && hardcount < max && *scan != '\n') {
7096 scan += UTF8SKIP(scan);
7100 while (scan < loceol && *scan != '\n')
7106 while (scan < loceol && hardcount < max) {
7107 scan += UTF8SKIP(scan);
7114 case CANY: /* Move <scan> forward <max> bytes, unless goes off end */
7115 if (utf8_target && loceol - scan > max) {
7117 /* <loceol> hadn't been adjusted in the UTF-8 case */
7125 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7129 /* Can use a simple loop if the pattern char to match on is invariant
7130 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
7131 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
7132 * true iff it doesn't matter if the argument is in UTF-8 or not */
7133 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
7134 if (utf8_target && loceol - scan > max) {
7135 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
7136 * since here, to match at all, 1 char == 1 byte */
7137 loceol = scan + max;
7139 while (scan < loceol && UCHARAT(scan) == c) {
7143 else if (reginfo->is_utf8_pat) {
7145 STRLEN scan_char_len;
7147 /* When both target and pattern are UTF-8, we have to do
7149 while (hardcount < max
7151 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
7152 && memEQ(scan, STRING(p), scan_char_len))
7154 scan += scan_char_len;
7158 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
7160 /* Target isn't utf8; convert the character in the UTF-8
7161 * pattern to non-UTF8, and do a simple loop */
7162 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
7163 while (scan < loceol && UCHARAT(scan) == c) {
7166 } /* else pattern char is above Latin1, can't possibly match the
7171 /* Here, the string must be utf8; pattern isn't, and <c> is
7172 * different in utf8 than not, so can't compare them directly.
7173 * Outside the loop, find the two utf8 bytes that represent c, and
7174 * then look for those in sequence in the utf8 string */
7175 U8 high = UTF8_TWO_BYTE_HI(c);
7176 U8 low = UTF8_TWO_BYTE_LO(c);
7178 while (hardcount < max
7179 && scan + 1 < loceol
7180 && UCHARAT(scan) == high
7181 && UCHARAT(scan + 1) == low)
7189 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
7190 assert(! reginfo->is_utf8_pat);
7193 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7197 utf8_flags = FOLDEQ_LOCALE;
7200 case EXACTF: /* This node only generated for non-utf8 patterns */
7201 assert(! reginfo->is_utf8_pat);
7207 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
7211 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
7213 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
7215 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
7218 if (c1 == CHRTEST_VOID) {
7219 /* Use full Unicode fold matching */
7220 char *tmpeol = reginfo->strend;
7221 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
7222 while (hardcount < max
7223 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
7224 STRING(p), NULL, pat_len,
7225 reginfo->is_utf8_pat, utf8_flags))
7228 tmpeol = reginfo->strend;
7232 else if (utf8_target) {
7234 while (scan < loceol
7236 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
7238 scan += UTF8SKIP(scan);
7243 while (scan < loceol
7245 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
7246 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
7248 scan += UTF8SKIP(scan);
7253 else if (c1 == c2) {
7254 while (scan < loceol && UCHARAT(scan) == c1) {
7259 while (scan < loceol &&
7260 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
7270 while (hardcount < max
7272 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
7274 scan += UTF8SKIP(scan);
7278 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
7283 /* The argument (FLAGS) to all the POSIX node types is the class number */
7290 if (! utf8_target) {
7291 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
7297 while (hardcount < max && scan < loceol
7298 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
7301 scan += UTF8SKIP(scan);
7314 if (utf8_target && loceol - scan > max) {
7316 /* We didn't adjust <loceol> at the beginning of this routine
7317 * because is UTF-8, but it is actually ok to do so, since here, to
7318 * match, 1 char == 1 byte. */
7319 loceol = scan + max;
7321 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
7334 if (! utf8_target) {
7335 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
7341 /* The complement of something that matches only ASCII matches all
7342 * UTF-8 variant code points, plus everything in ASCII that isn't
7344 while (hardcount < max && scan < loceol
7345 && (! UTF8_IS_INVARIANT(*scan)
7346 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
7348 scan += UTF8SKIP(scan);
7359 if (! utf8_target) {
7360 while (scan < loceol && to_complement
7361 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
7368 classnum = (_char_class_number) FLAGS(p);
7369 if (classnum < _FIRST_NON_SWASH_CC) {
7371 /* Here, a swash is needed for above-Latin1 code points.
7372 * Process as many Latin1 code points using the built-in rules.
7373 * Go to another loop to finish processing upon encountering
7374 * the first Latin1 code point. We could do that in this loop
7375 * as well, but the other way saves having to test if the swash
7376 * has been loaded every time through the loop: extra space to
7378 while (hardcount < max && scan < loceol) {
7379 if (UTF8_IS_INVARIANT(*scan)) {
7380 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
7387 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
7388 if (! (to_complement
7389 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
7398 goto found_above_latin1;
7405 /* For these character classes, the knowledge of how to handle
7406 * every code point is compiled in to Perl via a macro. This
7407 * code is written for making the loops as tight as possible.
7408 * It could be refactored to save space instead */
7410 case _CC_ENUM_SPACE: /* XXX would require separate code
7411 if we revert the change of \v
7414 case _CC_ENUM_PSXSPC:
7415 while (hardcount < max
7417 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
7419 scan += UTF8SKIP(scan);
7423 case _CC_ENUM_BLANK:
7424 while (hardcount < max
7426 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
7428 scan += UTF8SKIP(scan);
7432 case _CC_ENUM_XDIGIT:
7433 while (hardcount < max
7435 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
7437 scan += UTF8SKIP(scan);
7441 case _CC_ENUM_VERTSPACE:
7442 while (hardcount < max
7444 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
7446 scan += UTF8SKIP(scan);
7450 case _CC_ENUM_CNTRL:
7451 while (hardcount < max
7453 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
7455 scan += UTF8SKIP(scan);
7460 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
7466 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
7468 /* Load the swash if not already present */
7469 if (! PL_utf8_swash_ptrs[classnum]) {
7470 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7471 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
7475 PL_XPosix_ptrs[classnum], &flags);
7478 while (hardcount < max && scan < loceol
7479 && to_complement ^ cBOOL(_generic_utf8(
7482 swash_fetch(PL_utf8_swash_ptrs[classnum],
7486 scan += UTF8SKIP(scan);
7493 while (hardcount < max && scan < loceol &&
7494 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
7499 /* LNBREAK can match one or two latin chars, which is ok, but we
7500 * have to use hardcount in this situation, and throw away the
7501 * adjustment to <loceol> done before the switch statement */
7502 loceol = reginfo->strend;
7503 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
7524 /* These are all 0 width, so match right here or not at all. */
7528 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
7529 assert(0); /* NOTREACHED */
7536 c = scan - *startposp;
7540 GET_RE_DEBUG_FLAGS_DECL;
7542 SV * const prop = sv_newmortal();
7543 regprop(prog, prop, p, reginfo);
7544 PerlIO_printf(Perl_debug_log,
7545 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
7546 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
7554 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
7556 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
7557 create a copy so that changes the caller makes won't change the shared one.
7558 If <altsvp> is non-null, will return NULL in it, for back-compat.
7561 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
7563 PERL_ARGS_ASSERT_REGCLASS_SWASH;
7569 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL));
7573 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
7574 const regnode* node,
7577 SV** only_utf8_locale_ptr)
7579 /* For internal core use only.
7580 * Returns the swash for the input 'node' in the regex 'prog'.
7581 * If <doinit> is 'true', will attempt to create the swash if not already
7583 * If <listsvp> is non-null, will return the printable contents of the
7584 * swash. This can be used to get debugging information even before the
7585 * swash exists, by calling this function with 'doinit' set to false, in
7586 * which case the components that will be used to eventually create the
7587 * swash are returned (in a printable form).
7588 * Tied intimately to how regcomp.c sets up the data structure */
7592 SV *si = NULL; /* Input swash initialization string */
7595 RXi_GET_DECL(prog,progi);
7596 const struct reg_data * const data = prog ? progi->data : NULL;
7598 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
7600 assert(ANYOF_FLAGS(node)
7601 & (ANYOF_UTF8|ANYOF_NONBITMAP_NON_UTF8|ANYOF_LOC_FOLD));
7603 if (data && data->count) {
7604 const U32 n = ARG(node);
7606 if (data->what[n] == 's') {
7607 SV * const rv = MUTABLE_SV(data->data[n]);
7608 AV * const av = MUTABLE_AV(SvRV(rv));
7609 SV **const ary = AvARRAY(av);
7610 U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7612 si = *ary; /* ary[0] = the string to initialize the swash with */
7614 /* Elements 3 and 4 are either both present or both absent. [3] is
7615 * any inversion list generated at compile time; [4] indicates if
7616 * that inversion list has any user-defined properties in it. */
7617 if (av_tindex(av) >= 2) {
7618 if (only_utf8_locale_ptr
7620 && ary[2] != &PL_sv_undef)
7622 *only_utf8_locale_ptr = ary[2];
7625 *only_utf8_locale_ptr = NULL;
7628 if (av_tindex(av) >= 3) {
7631 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
7639 /* Element [1] is reserved for the set-up swash. If already there,
7640 * return it; if not, create it and store it there */
7641 if (ary[1] && SvROK(ary[1])) {
7644 else if (doinit && ((si && si != &PL_sv_undef)
7645 || (invlist && invlist != &PL_sv_undef))) {
7647 sw = _core_swash_init("utf8", /* the utf8 package */
7651 0, /* not from tr/// */
7654 (void)av_store(av, 1, sw);
7659 /* If requested, return a printable version of what this swash matches */
7661 SV* matches_string = newSVpvn("", 0);
7663 /* The swash should be used, if possible, to get the data, as it
7664 * contains the resolved data. But this function can be called at
7665 * compile-time, before everything gets resolved, in which case we
7666 * return the currently best available information, which is the string
7667 * that will eventually be used to do that resolving, 'si' */
7668 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
7669 && (si && si != &PL_sv_undef))
7671 sv_catsv(matches_string, si);
7674 /* Add the inversion list to whatever we have. This may have come from
7675 * the swash, or from an input parameter */
7677 sv_catsv(matches_string, _invlist_contents(invlist));
7679 *listsvp = matches_string;
7684 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
7687 - reginclass - determine if a character falls into a character class
7689 n is the ANYOF regnode
7690 p is the target string
7691 p_end points to one byte beyond the end of the target string
7692 utf8_target tells whether p is in UTF-8.
7694 Returns true if matched; false otherwise.
7696 Note that this can be a synthetic start class, a combination of various
7697 nodes, so things you think might be mutually exclusive, such as locale,
7698 aren't. It can match both locale and non-locale
7703 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
7706 const char flags = ANYOF_FLAGS(n);
7710 PERL_ARGS_ASSERT_REGINCLASS;
7712 /* If c is not already the code point, get it. Note that
7713 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
7714 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
7716 c = utf8n_to_uvchr(p, p_end - p, &c_len,
7717 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
7718 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
7719 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
7720 * UTF8_ALLOW_FFFF */
7721 if (c_len == (STRLEN)-1)
7722 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
7725 /* If this character is potentially in the bitmap, check it */
7727 if (ANYOF_BITMAP_TEST(n, c))
7729 else if (flags & ANYOF_NON_UTF8_NON_ASCII_ALL
7735 else if (flags & ANYOF_LOCALE_FLAGS) {
7736 if (flags & ANYOF_LOC_FOLD) {
7737 if (ANYOF_BITMAP_TEST(n, PL_fold_locale[c])) {
7741 if (! match && ANYOF_POSIXL_TEST_ANY_SET(n)) {
7743 /* The data structure is arranged so bits 0, 2, 4, ... are set
7744 * if the class includes the Posix character class given by
7745 * bit/2; and 1, 3, 5, ... are set if the class includes the
7746 * complemented Posix class given by int(bit/2). So we loop
7747 * through the bits, each time changing whether we complement
7748 * the result or not. Suppose for the sake of illustration
7749 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
7750 * is set, it means there is a match for this ANYOF node if the
7751 * character is in the class given by the expression (0 / 2 = 0
7752 * = \w). If it is in that class, isFOO_lc() will return 1,
7753 * and since 'to_complement' is 0, the result will stay TRUE,
7754 * and we exit the loop. Suppose instead that bit 0 is 0, but
7755 * bit 1 is 1. That means there is a match if the character
7756 * matches \W. We won't bother to call isFOO_lc() on bit 0,
7757 * but will on bit 1. On the second iteration 'to_complement'
7758 * will be 1, so the exclusive or will reverse things, so we
7759 * are testing for \W. On the third iteration, 'to_complement'
7760 * will be 0, and we would be testing for \s; the fourth
7761 * iteration would test for \S, etc.
7763 * Note that this code assumes that all the classes are closed
7764 * under folding. For example, if a character matches \w, then
7765 * its fold does too; and vice versa. This should be true for
7766 * any well-behaved locale for all the currently defined Posix
7767 * classes, except for :lower: and :upper:, which are handled
7768 * by the pseudo-class :cased: which matches if either of the
7769 * other two does. To get rid of this assumption, an outer
7770 * loop could be used below to iterate over both the source
7771 * character, and its fold (if different) */
7774 int to_complement = 0;
7776 while (count < ANYOF_MAX) {
7777 if (ANYOF_POSIXL_TEST(n, count)
7778 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
7791 /* If the bitmap didn't (or couldn't) match, and something outside the
7792 * bitmap could match, try that. */
7794 if (c >= 256 && (flags & ANYOF_ABOVE_LATIN1_ALL)) {
7795 match = TRUE; /* Everything above 255 matches */
7797 else if ((flags & ANYOF_NONBITMAP_NON_UTF8)
7798 || (utf8_target && (flags & ANYOF_UTF8))
7799 || ((flags & ANYOF_LOC_FOLD)
7800 && IN_UTF8_CTYPE_LOCALE
7801 && ARG(n) != ANYOF_NONBITMAP_EMPTY))
7803 SV* only_utf8_locale = NULL;
7804 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
7810 } else { /* Convert to utf8 */
7812 utf8_p = bytes_to_utf8(p, &len);
7815 if (swash_fetch(sw, utf8_p, TRUE)) {
7819 /* If we allocated a string above, free it */
7820 if (! utf8_target) Safefree(utf8_p);
7822 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
7823 match = _invlist_contains_cp(only_utf8_locale, c);
7827 if (UNICODE_IS_SUPER(c)
7828 && (flags & ANYOF_WARN_SUPER)
7829 && ckWARN_d(WARN_NON_UNICODE))
7831 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7832 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
7836 #if ANYOF_INVERT != 1
7837 /* Depending on compiler optimization cBOOL takes time, so if don't have to
7839 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
7842 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
7843 return (flags & ANYOF_INVERT) ^ match;
7847 S_reghop3(U8 *s, SSize_t off, const U8* lim)
7849 /* return the position 'off' UTF-8 characters away from 's', forward if
7850 * 'off' >= 0, backwards if negative. But don't go outside of position
7851 * 'lim', which better be < s if off < 0 */
7855 PERL_ARGS_ASSERT_REGHOP3;
7858 while (off-- && s < lim) {
7859 /* XXX could check well-formedness here */
7864 while (off++ && s > lim) {
7866 if (UTF8_IS_CONTINUED(*s)) {
7867 while (s > lim && UTF8_IS_CONTINUATION(*s))
7870 /* XXX could check well-formedness here */
7877 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
7881 PERL_ARGS_ASSERT_REGHOP4;
7884 while (off-- && s < rlim) {
7885 /* XXX could check well-formedness here */
7890 while (off++ && s > llim) {
7892 if (UTF8_IS_CONTINUED(*s)) {
7893 while (s > llim && UTF8_IS_CONTINUATION(*s))
7896 /* XXX could check well-formedness here */
7902 /* like reghop3, but returns NULL on overrun, rather than returning last
7906 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
7910 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7913 while (off-- && s < lim) {
7914 /* XXX could check well-formedness here */
7921 while (off++ && s > lim) {
7923 if (UTF8_IS_CONTINUED(*s)) {
7924 while (s > lim && UTF8_IS_CONTINUATION(*s))
7927 /* XXX could check well-formedness here */
7936 /* when executing a regex that may have (?{}), extra stuff needs setting
7937 up that will be visible to the called code, even before the current
7938 match has finished. In particular:
7940 * $_ is localised to the SV currently being matched;
7941 * pos($_) is created if necessary, ready to be updated on each call-out
7943 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
7944 isn't set until the current pattern is successfully finished), so that
7945 $1 etc of the match-so-far can be seen;
7946 * save the old values of subbeg etc of the current regex, and set then
7947 to the current string (again, this is normally only done at the end
7952 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
7955 regexp *const rex = ReANY(reginfo->prog);
7956 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
7958 eval_state->rex = rex;
7961 /* Make $_ available to executed code. */
7962 if (reginfo->sv != DEFSV) {
7964 DEFSV_set(reginfo->sv);
7967 if (!(mg = mg_find_mglob(reginfo->sv))) {
7968 /* prepare for quick setting of pos */
7969 mg = sv_magicext_mglob(reginfo->sv);
7972 eval_state->pos_magic = mg;
7973 eval_state->pos = mg->mg_len;
7974 eval_state->pos_flags = mg->mg_flags;
7977 eval_state->pos_magic = NULL;
7979 if (!PL_reg_curpm) {
7980 /* PL_reg_curpm is a fake PMOP that we can attach the current
7981 * regex to and point PL_curpm at, so that $1 et al are visible
7982 * within a /(?{})/. It's just allocated once per interpreter the
7983 * first time its needed */
7984 Newxz(PL_reg_curpm, 1, PMOP);
7987 SV* const repointer = &PL_sv_undef;
7988 /* this regexp is also owned by the new PL_reg_curpm, which
7989 will try to free it. */
7990 av_push(PL_regex_padav, repointer);
7991 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
7992 PL_regex_pad = AvARRAY(PL_regex_padav);
7996 SET_reg_curpm(reginfo->prog);
7997 eval_state->curpm = PL_curpm;
7998 PL_curpm = PL_reg_curpm;
7999 if (RXp_MATCH_COPIED(rex)) {
8000 /* Here is a serious problem: we cannot rewrite subbeg,
8001 since it may be needed if this match fails. Thus
8002 $` inside (?{}) could fail... */
8003 eval_state->subbeg = rex->subbeg;
8004 eval_state->sublen = rex->sublen;
8005 eval_state->suboffset = rex->suboffset;
8006 eval_state->subcoffset = rex->subcoffset;
8008 eval_state->saved_copy = rex->saved_copy;
8010 RXp_MATCH_COPIED_off(rex);
8013 eval_state->subbeg = NULL;
8014 rex->subbeg = (char *)reginfo->strbeg;
8016 rex->subcoffset = 0;
8017 rex->sublen = reginfo->strend - reginfo->strbeg;
8021 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8024 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8027 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8028 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8031 Safefree(aux->poscache);
8035 /* undo the effects of S_setup_eval_state() */
8037 if (eval_state->subbeg) {
8038 regexp * const rex = eval_state->rex;
8039 rex->subbeg = eval_state->subbeg;
8040 rex->sublen = eval_state->sublen;
8041 rex->suboffset = eval_state->suboffset;
8042 rex->subcoffset = eval_state->subcoffset;
8044 rex->saved_copy = eval_state->saved_copy;
8046 RXp_MATCH_COPIED_on(rex);
8048 if (eval_state->pos_magic)
8050 eval_state->pos_magic->mg_len = eval_state->pos;
8051 eval_state->pos_magic->mg_flags =
8052 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8053 | (eval_state->pos_flags & MGf_BYTES);
8056 PL_curpm = eval_state->curpm;
8059 PL_regmatch_state = aux->old_regmatch_state;
8060 PL_regmatch_slab = aux->old_regmatch_slab;
8062 /* free all slabs above current one - this must be the last action
8063 * of this function, as aux and eval_state are allocated within
8064 * slabs and may be freed here */
8066 s = PL_regmatch_slab->next;
8068 PL_regmatch_slab->next = NULL;
8070 regmatch_slab * const osl = s;
8079 S_to_utf8_substr(pTHX_ regexp *prog)
8081 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8082 * on the converted value */
8086 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8089 if (prog->substrs->data[i].substr
8090 && !prog->substrs->data[i].utf8_substr) {
8091 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8092 prog->substrs->data[i].utf8_substr = sv;
8093 sv_utf8_upgrade(sv);
8094 if (SvVALID(prog->substrs->data[i].substr)) {
8095 if (SvTAIL(prog->substrs->data[i].substr)) {
8096 /* Trim the trailing \n that fbm_compile added last
8098 SvCUR_set(sv, SvCUR(sv) - 1);
8099 /* Whilst this makes the SV technically "invalid" (as its
8100 buffer is no longer followed by "\0") when fbm_compile()
8101 adds the "\n" back, a "\0" is restored. */
8102 fbm_compile(sv, FBMcf_TAIL);
8106 if (prog->substrs->data[i].substr == prog->check_substr)
8107 prog->check_utf8 = sv;
8113 S_to_byte_substr(pTHX_ regexp *prog)
8115 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8116 * on the converted value; returns FALSE if can't be converted. */
8121 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8124 if (prog->substrs->data[i].utf8_substr
8125 && !prog->substrs->data[i].substr) {
8126 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
8127 if (! sv_utf8_downgrade(sv, TRUE)) {
8130 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
8131 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
8132 /* Trim the trailing \n that fbm_compile added last
8134 SvCUR_set(sv, SvCUR(sv) - 1);
8135 fbm_compile(sv, FBMcf_TAIL);
8139 prog->substrs->data[i].substr = sv;
8140 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
8141 prog->check_substr = sv;
8150 * c-indentation-style: bsd
8152 * indent-tabs-mode: nil
8155 * ex: set ts=8 sts=4 sw=4 et: