5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
89 static const char utf8_locale_required[] =
90 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
93 /* At least one required character in the target string is expressible only in
95 static const char* const non_utf8_target_but_utf8_required
96 = "Can't match, because target string needs to be in UTF-8\n";
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
107 #define STATIC static
110 /* Valid only for non-utf8 strings: avoids the reginclass
111 * call if there are no complications: i.e., if everything matchable is
112 * straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
114 : ANYOF_BITMAP_TEST(p,*(c)))
120 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
121 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
123 #define HOPc(pos,off) \
124 (char *)(reginfo->is_utf8_target \
125 ? reghop3((U8*)pos, off, \
126 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
129 #define HOPBACKc(pos, off) \
130 (char*)(reginfo->is_utf8_target \
131 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
132 : (pos - off >= reginfo->strbeg) \
136 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
137 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
139 /* lim must be +ve. Returns NULL on overshoot */
140 #define HOPMAYBE3(pos,off,lim) \
141 (reginfo->is_utf8_target \
142 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
143 : ((U8*)pos + off <= lim) \
147 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
148 * off must be >=0; args should be vars rather than expressions */
149 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
150 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
151 : (U8*)((pos + off) > lim ? lim : (pos + off)))
153 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
154 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
156 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
158 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
159 #define NEXTCHR_IS_EOS (nextchr < 0)
161 #define SET_nextchr \
162 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
164 #define SET_locinput(p) \
169 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
171 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
172 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
173 1, 0, invlist, &flags); \
178 /* If in debug mode, we test that a known character properly matches */
180 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
183 utf8_char_in_property) \
184 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
185 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
187 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
190 utf8_char_in_property) \
191 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
194 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
195 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
197 PL_XPosix_ptrs[_CC_WORDCHAR], \
198 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
200 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
201 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
203 /* for use after a quantifier and before an EXACT-like node -- japhy */
204 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
206 * NOTE that *nothing* that affects backtracking should be in here, specifically
207 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
208 * node that is in between two EXACT like nodes when ascertaining what the required
209 * "follow" character is. This should probably be moved to regex compile time
210 * although it may be done at run time beause of the REF possibility - more
211 * investigation required. -- demerphq
213 #define JUMPABLE(rn) ( \
215 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
217 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
218 OP(rn) == PLUS || OP(rn) == MINMOD || \
220 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
222 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
224 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
227 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
228 we don't need this definition. XXX These are now out-of-sync*/
229 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
230 #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 )
231 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
234 /* ... so we use this as its faster. */
235 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
236 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
237 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
238 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
243 Search for mandatory following text node; for lookahead, the text must
244 follow but for lookbehind (rn->flags != 0) we skip to the next step.
246 #define FIND_NEXT_IMPT(rn) STMT_START { \
247 while (JUMPABLE(rn)) { \
248 const OPCODE type = OP(rn); \
249 if (type == SUSPEND || PL_regkind[type] == CURLY) \
250 rn = NEXTOPER(NEXTOPER(rn)); \
251 else if (type == PLUS) \
253 else if (type == IFMATCH) \
254 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
255 else rn += NEXT_OFF(rn); \
259 #define SLAB_FIRST(s) (&(s)->states[0])
260 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
262 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
263 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
264 static regmatch_state * S_push_slab(pTHX);
266 #define REGCP_PAREN_ELEMS 3
267 #define REGCP_OTHER_ELEMS 3
268 #define REGCP_FRAME_ELEMS 1
269 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
270 * are needed for the regexp context stack bookkeeping. */
273 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
275 const int retval = PL_savestack_ix;
276 const int paren_elems_to_push =
277 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
278 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
279 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
281 GET_RE_DEBUG_FLAGS_DECL;
283 PERL_ARGS_ASSERT_REGCPPUSH;
285 if (paren_elems_to_push < 0)
286 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
287 (int)paren_elems_to_push, (int)maxopenparen,
288 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
290 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
291 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
292 " out of range (%lu-%ld)",
294 (unsigned long)maxopenparen,
297 SSGROW(total_elems + REGCP_FRAME_ELEMS);
300 if ((int)maxopenparen > (int)parenfloor)
301 PerlIO_printf(Perl_debug_log,
302 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
307 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
308 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
309 SSPUSHIV(rex->offs[p].end);
310 SSPUSHIV(rex->offs[p].start);
311 SSPUSHINT(rex->offs[p].start_tmp);
312 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
313 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
315 (IV)rex->offs[p].start,
316 (IV)rex->offs[p].start_tmp,
320 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
321 SSPUSHINT(maxopenparen);
322 SSPUSHINT(rex->lastparen);
323 SSPUSHINT(rex->lastcloseparen);
324 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
329 /* These are needed since we do not localize EVAL nodes: */
330 #define REGCP_SET(cp) \
332 PerlIO_printf(Perl_debug_log, \
333 " Setting an EVAL scope, savestack=%"IVdf"\n", \
334 (IV)PL_savestack_ix)); \
337 #define REGCP_UNWIND(cp) \
339 if (cp != PL_savestack_ix) \
340 PerlIO_printf(Perl_debug_log, \
341 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
342 (IV)(cp), (IV)PL_savestack_ix)); \
345 #define UNWIND_PAREN(lp, lcp) \
346 for (n = rex->lastparen; n > lp; n--) \
347 rex->offs[n].end = -1; \
348 rex->lastparen = n; \
349 rex->lastcloseparen = lcp;
353 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
357 GET_RE_DEBUG_FLAGS_DECL;
359 PERL_ARGS_ASSERT_REGCPPOP;
361 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
363 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
364 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
365 rex->lastcloseparen = SSPOPINT;
366 rex->lastparen = SSPOPINT;
367 *maxopenparen_p = SSPOPINT;
369 i -= REGCP_OTHER_ELEMS;
370 /* Now restore the parentheses context. */
372 if (i || rex->lastparen + 1 <= rex->nparens)
373 PerlIO_printf(Perl_debug_log,
374 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
379 paren = *maxopenparen_p;
380 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
382 rex->offs[paren].start_tmp = SSPOPINT;
383 rex->offs[paren].start = SSPOPIV;
385 if (paren <= rex->lastparen)
386 rex->offs[paren].end = tmps;
387 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
388 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
390 (IV)rex->offs[paren].start,
391 (IV)rex->offs[paren].start_tmp,
392 (IV)rex->offs[paren].end,
393 (paren > rex->lastparen ? "(skipped)" : ""));
398 /* It would seem that the similar code in regtry()
399 * already takes care of this, and in fact it is in
400 * a better location to since this code can #if 0-ed out
401 * but the code in regtry() is needed or otherwise tests
402 * requiring null fields (pat.t#187 and split.t#{13,14}
403 * (as of patchlevel 7877) will fail. Then again,
404 * this code seems to be necessary or otherwise
405 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
406 * --jhi updated by dapm */
407 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
408 if (i > *maxopenparen_p)
409 rex->offs[i].start = -1;
410 rex->offs[i].end = -1;
411 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
412 " \\%"UVuf": %s ..-1 undeffing\n",
414 (i > *maxopenparen_p) ? "-1" : " "
420 /* restore the parens and associated vars at savestack position ix,
421 * but without popping the stack */
424 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
426 I32 tmpix = PL_savestack_ix;
427 PL_savestack_ix = ix;
428 regcppop(rex, maxopenparen_p);
429 PL_savestack_ix = tmpix;
432 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
435 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
437 /* Returns a boolean as to whether or not 'character' is a member of the
438 * Posix character class given by 'classnum' that should be equivalent to a
439 * value in the typedef '_char_class_number'.
441 * Ideally this could be replaced by a just an array of function pointers
442 * to the C library functions that implement the macros this calls.
443 * However, to compile, the precise function signatures are required, and
444 * these may vary from platform to to platform. To avoid having to figure
445 * out what those all are on each platform, I (khw) am using this method,
446 * which adds an extra layer of function call overhead (unless the C
447 * optimizer strips it away). But we don't particularly care about
448 * performance with locales anyway. */
450 switch ((_char_class_number) classnum) {
451 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
452 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
453 case _CC_ENUM_ASCII: return isASCII_LC(character);
454 case _CC_ENUM_BLANK: return isBLANK_LC(character);
455 case _CC_ENUM_CASED: return isLOWER_LC(character)
456 || isUPPER_LC(character);
457 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
458 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
459 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
460 case _CC_ENUM_LOWER: return isLOWER_LC(character);
461 case _CC_ENUM_PRINT: return isPRINT_LC(character);
462 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
463 case _CC_ENUM_SPACE: return isSPACE_LC(character);
464 case _CC_ENUM_UPPER: return isUPPER_LC(character);
465 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
466 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
467 default: /* VERTSPACE should never occur in locales */
468 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
471 NOT_REACHED; /* NOTREACHED */
476 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
478 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
479 * 'character' is a member of the Posix character class given by 'classnum'
480 * that should be equivalent to a value in the typedef
481 * '_char_class_number'.
483 * This just calls isFOO_lc on the code point for the character if it is in
484 * the range 0-255. Outside that range, all characters use Unicode
485 * rules, ignoring any locale. So use the Unicode function if this class
486 * requires a swash, and use the Unicode macro otherwise. */
488 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
490 if (UTF8_IS_INVARIANT(*character)) {
491 return isFOO_lc(classnum, *character);
493 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
494 return isFOO_lc(classnum,
495 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
498 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
500 if (classnum < _FIRST_NON_SWASH_CC) {
502 /* Initialize the swash unless done already */
503 if (! PL_utf8_swash_ptrs[classnum]) {
504 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
505 PL_utf8_swash_ptrs[classnum] =
506 _core_swash_init("utf8",
509 PL_XPosix_ptrs[classnum], &flags);
512 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
514 TRUE /* is UTF */ ));
517 switch ((_char_class_number) classnum) {
518 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
519 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
520 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
521 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
525 return FALSE; /* Things like CNTRL are always below 256 */
529 * pregexec and friends
532 #ifndef PERL_IN_XSUB_RE
534 - pregexec - match a regexp against a string
537 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
538 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
539 /* stringarg: the point in the string at which to begin matching */
540 /* strend: pointer to null at end of string */
541 /* strbeg: real beginning of string */
542 /* minend: end of match must be >= minend bytes after stringarg. */
543 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
544 * itself is accessed via the pointers above */
545 /* nosave: For optimizations. */
547 PERL_ARGS_ASSERT_PREGEXEC;
550 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
551 nosave ? 0 : REXEC_COPY_STR);
557 /* re_intuit_start():
559 * Based on some optimiser hints, try to find the earliest position in the
560 * string where the regex could match.
562 * rx: the regex to match against
563 * sv: the SV being matched: only used for utf8 flag; the string
564 * itself is accessed via the pointers below. Note that on
565 * something like an overloaded SV, SvPOK(sv) may be false
566 * and the string pointers may point to something unrelated to
568 * strbeg: real beginning of string
569 * strpos: the point in the string at which to begin matching
570 * strend: pointer to the byte following the last char of the string
571 * flags currently unused; set to 0
572 * data: currently unused; set to NULL
574 * The basic idea of re_intuit_start() is to use some known information
575 * about the pattern, namely:
577 * a) the longest known anchored substring (i.e. one that's at a
578 * constant offset from the beginning of the pattern; but not
579 * necessarily at a fixed offset from the beginning of the
581 * b) the longest floating substring (i.e. one that's not at a constant
582 * offset from the beginning of the pattern);
583 * c) Whether the pattern is anchored to the string; either
584 * an absolute anchor: /^../, or anchored to \n: /^.../m,
585 * or anchored to pos(): /\G/;
586 * d) A start class: a real or synthetic character class which
587 * represents which characters are legal at the start of the pattern;
589 * to either quickly reject the match, or to find the earliest position
590 * within the string at which the pattern might match, thus avoiding
591 * running the full NFA engine at those earlier locations, only to
592 * eventually fail and retry further along.
594 * Returns NULL if the pattern can't match, or returns the address within
595 * the string which is the earliest place the match could occur.
597 * The longest of the anchored and floating substrings is called 'check'
598 * and is checked first. The other is called 'other' and is checked
599 * second. The 'other' substring may not be present. For example,
601 * /(abc|xyz)ABC\d{0,3}DEFG/
605 * check substr (float) = "DEFG", offset 6..9 chars
606 * other substr (anchored) = "ABC", offset 3..3 chars
609 * Be aware that during the course of this function, sometimes 'anchored'
610 * refers to a substring being anchored relative to the start of the
611 * pattern, and sometimes to the pattern itself being anchored relative to
612 * the string. For example:
614 * /\dabc/: "abc" is anchored to the pattern;
615 * /^\dabc/: "abc" is anchored to the pattern and the string;
616 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
617 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
618 * but the pattern is anchored to the string.
622 Perl_re_intuit_start(pTHX_
625 const char * const strbeg,
629 re_scream_pos_data *data)
631 struct regexp *const prog = ReANY(rx);
632 SSize_t start_shift = prog->check_offset_min;
633 /* Should be nonnegative! */
634 SSize_t end_shift = 0;
635 /* current lowest pos in string where the regex can start matching */
636 char *rx_origin = strpos;
638 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
639 U8 other_ix = 1 - prog->substrs->check_ix;
641 char *other_last = strpos;/* latest pos 'other' substr already checked to */
642 char *check_at = NULL; /* check substr found at this pos */
643 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
644 RXi_GET_DECL(prog,progi);
645 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
646 regmatch_info *const reginfo = ®info_buf;
647 GET_RE_DEBUG_FLAGS_DECL;
649 PERL_ARGS_ASSERT_RE_INTUIT_START;
650 PERL_UNUSED_ARG(flags);
651 PERL_UNUSED_ARG(data);
653 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
654 "Intuit: trying to determine minimum start position...\n"));
656 /* for now, assume that all substr offsets are positive. If at some point
657 * in the future someone wants to do clever things with lookbehind and
658 * -ve offsets, they'll need to fix up any code in this function
659 * which uses these offsets. See the thread beginning
660 * <20140113145929.GF27210@iabyn.com>
662 assert(prog->substrs->data[0].min_offset >= 0);
663 assert(prog->substrs->data[0].max_offset >= 0);
664 assert(prog->substrs->data[1].min_offset >= 0);
665 assert(prog->substrs->data[1].max_offset >= 0);
666 assert(prog->substrs->data[2].min_offset >= 0);
667 assert(prog->substrs->data[2].max_offset >= 0);
669 /* for now, assume that if both present, that the floating substring
670 * doesn't start before the anchored substring.
671 * If you break this assumption (e.g. doing better optimisations
672 * with lookahead/behind), then you'll need to audit the code in this
673 * function carefully first
676 ! ( (prog->anchored_utf8 || prog->anchored_substr)
677 && (prog->float_utf8 || prog->float_substr))
678 || (prog->float_min_offset >= prog->anchored_offset));
680 /* byte rather than char calculation for efficiency. It fails
681 * to quickly reject some cases that can't match, but will reject
682 * them later after doing full char arithmetic */
683 if (prog->minlen > strend - strpos) {
684 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
685 " String too short...\n"));
689 RX_MATCH_UTF8_set(rx,utf8_target);
690 reginfo->is_utf8_target = cBOOL(utf8_target);
691 reginfo->info_aux = NULL;
692 reginfo->strbeg = strbeg;
693 reginfo->strend = strend;
694 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
696 /* not actually used within intuit, but zero for safety anyway */
697 reginfo->poscache_maxiter = 0;
700 if (!prog->check_utf8 && prog->check_substr)
701 to_utf8_substr(prog);
702 check = prog->check_utf8;
704 if (!prog->check_substr && prog->check_utf8) {
705 if (! to_byte_substr(prog)) {
706 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
709 check = prog->check_substr;
712 /* dump the various substring data */
713 DEBUG_OPTIMISE_MORE_r({
715 for (i=0; i<=2; i++) {
716 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
717 : prog->substrs->data[i].substr);
721 PerlIO_printf(Perl_debug_log,
722 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
723 " useful=%"IVdf" utf8=%d [%s]\n",
725 (IV)prog->substrs->data[i].min_offset,
726 (IV)prog->substrs->data[i].max_offset,
727 (IV)prog->substrs->data[i].end_shift,
734 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
736 /* ml_anch: check after \n?
738 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
739 * with /.*.../, these flags will have been added by the
741 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
742 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
744 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
745 && !(prog->intflags & PREGf_IMPLICIT);
747 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
748 /* we are only allowed to match at BOS or \G */
750 /* trivially reject if there's a BOS anchor and we're not at BOS.
752 * Note that we don't try to do a similar quick reject for
753 * \G, since generally the caller will have calculated strpos
754 * based on pos() and gofs, so the string is already correctly
755 * anchored by definition; and handling the exceptions would
756 * be too fiddly (e.g. REXEC_IGNOREPOS).
758 if ( strpos != strbeg
759 && (prog->intflags & PREGf_ANCH_SBOL))
761 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
762 " Not at start...\n"));
766 /* in the presence of an anchor, the anchored (relative to the
767 * start of the regex) substr must also be anchored relative
768 * to strpos. So quickly reject if substr isn't found there.
769 * This works for \G too, because the caller will already have
770 * subtracted gofs from pos, and gofs is the offset from the
771 * \G to the start of the regex. For example, in /.abc\Gdef/,
772 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
773 * caller will have set strpos=pos()-4; we look for the substr
774 * at position pos()-4+1, which lines up with the "a" */
776 if (prog->check_offset_min == prog->check_offset_max) {
777 /* Substring at constant offset from beg-of-str... */
778 SSize_t slen = SvCUR(check);
779 char *s = HOP3c(strpos, prog->check_offset_min, strend);
781 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
782 " Looking for check substr at fixed offset %"IVdf"...\n",
783 (IV)prog->check_offset_min));
786 /* In this case, the regex is anchored at the end too.
787 * Unless it's a multiline match, the lengths must match
788 * exactly, give or take a \n. NB: slen >= 1 since
789 * the last char of check is \n */
791 && ( strend - s > slen
792 || strend - s < slen - 1
793 || (strend - s == slen && strend[-1] != '\n')))
795 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
796 " String too long...\n"));
799 /* Now should match s[0..slen-2] */
802 if (slen && (*SvPVX_const(check) != *s
803 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
805 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
806 " String not equal...\n"));
811 goto success_at_start;
816 end_shift = prog->check_end_shift;
818 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
820 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
821 (IV)end_shift, RX_PRECOMP(prog));
826 /* This is the (re)entry point of the main loop in this function.
827 * The goal of this loop is to:
828 * 1) find the "check" substring in the region rx_origin..strend
829 * (adjusted by start_shift / end_shift). If not found, reject
831 * 2) If it exists, look for the "other" substr too if defined; for
832 * example, if the check substr maps to the anchored substr, then
833 * check the floating substr, and vice-versa. If not found, go
834 * back to (1) with rx_origin suitably incremented.
835 * 3) If we find an rx_origin position that doesn't contradict
836 * either of the substrings, then check the possible additional
837 * constraints on rx_origin of /^.../m or a known start class.
838 * If these fail, then depending on which constraints fail, jump
839 * back to here, or to various other re-entry points further along
840 * that skip some of the first steps.
841 * 4) If we pass all those tests, update the BmUSEFUL() count on the
842 * substring. If the start position was determined to be at the
843 * beginning of the string - so, not rejected, but not optimised,
844 * since we have to run regmatch from position 0 - decrement the
845 * BmUSEFUL() count. Otherwise increment it.
849 /* first, look for the 'check' substring */
855 DEBUG_OPTIMISE_MORE_r({
856 PerlIO_printf(Perl_debug_log,
857 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
858 " Start shift: %"IVdf" End shift %"IVdf
859 " Real end Shift: %"IVdf"\n",
860 (IV)(rx_origin - strbeg),
861 (IV)prog->check_offset_min,
864 (IV)prog->check_end_shift);
867 end_point = HOP3(strend, -end_shift, strbeg);
868 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
873 /* If the regex is absolutely anchored to either the start of the
874 * string (SBOL) or to pos() (ANCH_GPOS), then
875 * check_offset_max represents an upper bound on the string where
876 * the substr could start. For the ANCH_GPOS case, we assume that
877 * the caller of intuit will have already set strpos to
878 * pos()-gofs, so in this case strpos + offset_max will still be
879 * an upper bound on the substr.
882 && prog->intflags & PREGf_ANCH
883 && prog->check_offset_max != SSize_t_MAX)
885 SSize_t len = SvCUR(check) - !!SvTAIL(check);
886 const char * const anchor =
887 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
889 /* do a bytes rather than chars comparison. It's conservative;
890 * so it skips doing the HOP if the result can't possibly end
891 * up earlier than the old value of end_point.
893 if ((char*)end_point - anchor > prog->check_offset_max) {
894 end_point = HOP3lim((U8*)anchor,
895 prog->check_offset_max,
901 check_at = fbm_instr( start_point, end_point,
902 check, multiline ? FBMrf_MULTILINE : 0);
904 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
905 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
906 (IV)((char*)start_point - strbeg),
907 (IV)((char*)end_point - strbeg),
908 (IV)(check_at ? check_at - strbeg : -1)
911 /* Update the count-of-usability, remove useless subpatterns,
915 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
916 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
917 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
918 (check_at ? "Found" : "Did not find"),
919 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
920 ? "anchored" : "floating"),
923 (check_at ? " at offset " : "...\n") );
928 /* set rx_origin to the minimum position where the regex could start
929 * matching, given the constraint of the just-matched check substring.
930 * But don't set it lower than previously.
933 if (check_at - rx_origin > prog->check_offset_max)
934 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
935 /* Finish the diagnostic message */
936 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
937 "%ld (rx_origin now %"IVdf")...\n",
938 (long)(check_at - strbeg),
939 (IV)(rx_origin - strbeg)
944 /* now look for the 'other' substring if defined */
946 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
947 : prog->substrs->data[other_ix].substr)
949 /* Take into account the "other" substring. */
953 struct reg_substr_datum *other;
956 other = &prog->substrs->data[other_ix];
958 /* if "other" is anchored:
959 * we've previously found a floating substr starting at check_at.
960 * This means that the regex origin must lie somewhere
961 * between min (rx_origin): HOP3(check_at, -check_offset_max)
962 * and max: HOP3(check_at, -check_offset_min)
963 * (except that min will be >= strpos)
964 * So the fixed substr must lie somewhere between
965 * HOP3(min, anchored_offset)
966 * HOP3(max, anchored_offset) + SvCUR(substr)
969 /* if "other" is floating
970 * Calculate last1, the absolute latest point where the
971 * floating substr could start in the string, ignoring any
972 * constraints from the earlier fixed match. It is calculated
975 * strend - prog->minlen (in chars) is the absolute latest
976 * position within the string where the origin of the regex
977 * could appear. The latest start point for the floating
978 * substr is float_min_offset(*) on from the start of the
979 * regex. last1 simply combines thee two offsets.
981 * (*) You might think the latest start point should be
982 * float_max_offset from the regex origin, and technically
983 * you'd be correct. However, consider
985 * Here, float min, max are 3,5 and minlen is 7.
986 * This can match either
990 * In the first case, the regex matches minlen chars; in the
991 * second, minlen+1, in the third, minlen+2.
992 * In the first case, the floating offset is 3 (which equals
993 * float_min), in the second, 4, and in the third, 5 (which
994 * equals float_max). In all cases, the floating string bcd
995 * can never start more than 4 chars from the end of the
996 * string, which equals minlen - float_min. As the substring
997 * starts to match more than float_min from the start of the
998 * regex, it makes the regex match more than minlen chars,
999 * and the two cancel each other out. So we can always use
1000 * float_min - minlen, rather than float_max - minlen for the
1001 * latest position in the string.
1003 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1004 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1007 assert(prog->minlen >= other->min_offset);
1008 last1 = HOP3c(strend,
1009 other->min_offset - prog->minlen, strbeg);
1011 if (other_ix) {/* i.e. if (other-is-float) */
1012 /* last is the latest point where the floating substr could
1013 * start, *given* any constraints from the earlier fixed
1014 * match. This constraint is that the floating string starts
1015 * <= float_max_offset chars from the regex origin (rx_origin).
1016 * If this value is less than last1, use it instead.
1018 assert(rx_origin <= last1);
1020 /* this condition handles the offset==infinity case, and
1021 * is a short-cut otherwise. Although it's comparing a
1022 * byte offset to a char length, it does so in a safe way,
1023 * since 1 char always occupies 1 or more bytes,
1024 * so if a string range is (last1 - rx_origin) bytes,
1025 * it will be less than or equal to (last1 - rx_origin)
1026 * chars; meaning it errs towards doing the accurate HOP3
1027 * rather than just using last1 as a short-cut */
1028 (last1 - rx_origin) < other->max_offset
1030 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1033 assert(strpos + start_shift <= check_at);
1034 last = HOP4c(check_at, other->min_offset - start_shift,
1038 s = HOP3c(rx_origin, other->min_offset, strend);
1039 if (s < other_last) /* These positions already checked */
1042 must = utf8_target ? other->utf8_substr : other->substr;
1043 assert(SvPOK(must));
1046 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1050 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1051 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1052 (IV)(from - strbeg),
1058 (unsigned char*)from,
1061 multiline ? FBMrf_MULTILINE : 0
1063 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1064 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1065 (IV)(from - strbeg),
1067 (IV)(s ? s - strbeg : -1)
1073 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1074 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1075 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1076 s ? "Found" : "Contradicts",
1077 other_ix ? "floating" : "anchored",
1078 quoted, RE_SV_TAIL(must));
1083 /* last1 is latest possible substr location. If we didn't
1084 * find it before there, we never will */
1085 if (last >= last1) {
1086 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1087 "; giving up...\n"));
1091 /* try to find the check substr again at a later
1092 * position. Maybe next time we'll find the "other" substr
1094 other_last = HOP3c(last, 1, strend) /* highest failure */;
1096 other_ix /* i.e. if other-is-float */
1097 ? HOP3c(rx_origin, 1, strend)
1098 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1099 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1100 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1101 (other_ix ? "floating" : "anchored"),
1102 (long)(HOP3c(check_at, 1, strend) - strbeg),
1103 (IV)(rx_origin - strbeg)
1108 if (other_ix) { /* if (other-is-float) */
1109 /* other_last is set to s, not s+1, since its possible for
1110 * a floating substr to fail first time, then succeed
1111 * second time at the same floating position; e.g.:
1112 * "-AB--AABZ" =~ /\wAB\d*Z/
1113 * The first time round, anchored and float match at
1114 * "-(AB)--AAB(Z)" then fail on the initial \w character
1115 * class. Second time round, they match at "-AB--A(AB)(Z)".
1120 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1121 other_last = HOP3c(s, 1, strend);
1123 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1124 " at offset %ld (rx_origin now %"IVdf")...\n",
1126 (IV)(rx_origin - strbeg)
1132 DEBUG_OPTIMISE_MORE_r(
1133 PerlIO_printf(Perl_debug_log,
1134 " Check-only match: offset min:%"IVdf" max:%"IVdf
1135 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1136 " strend:%"IVdf"\n",
1137 (IV)prog->check_offset_min,
1138 (IV)prog->check_offset_max,
1139 (IV)(check_at-strbeg),
1140 (IV)(rx_origin-strbeg),
1141 (IV)(rx_origin-check_at),
1147 postprocess_substr_matches:
1149 /* handle the extra constraint of /^.../m if present */
1151 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1154 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1155 " looking for /^/m anchor"));
1157 /* we have failed the constraint of a \n before rx_origin.
1158 * Find the next \n, if any, even if it's beyond the current
1159 * anchored and/or floating substrings. Whether we should be
1160 * scanning ahead for the next \n or the next substr is debatable.
1161 * On the one hand you'd expect rare substrings to appear less
1162 * often than \n's. On the other hand, searching for \n means
1163 * we're effectively flipping between check_substr and "\n" on each
1164 * iteration as the current "rarest" string candidate, which
1165 * means for example that we'll quickly reject the whole string if
1166 * hasn't got a \n, rather than trying every substr position
1170 s = HOP3c(strend, - prog->minlen, strpos);
1171 if (s <= rx_origin ||
1172 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1174 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1175 " Did not find /%s^%s/m...\n",
1176 PL_colors[0], PL_colors[1]));
1180 /* earliest possible origin is 1 char after the \n.
1181 * (since *rx_origin == '\n', it's safe to ++ here rather than
1182 * HOP(rx_origin, 1)) */
1185 if (prog->substrs->check_ix == 0 /* check is anchored */
1186 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1188 /* Position contradicts check-string; either because
1189 * check was anchored (and thus has no wiggle room),
1190 * or check was float and rx_origin is above the float range */
1191 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1192 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1193 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1197 /* if we get here, the check substr must have been float,
1198 * is in range, and we may or may not have had an anchored
1199 * "other" substr which still contradicts */
1200 assert(prog->substrs->check_ix); /* check is float */
1202 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1203 /* whoops, the anchored "other" substr exists, so we still
1204 * contradict. On the other hand, the float "check" substr
1205 * didn't contradict, so just retry the anchored "other"
1207 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1208 " Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1209 PL_colors[0], PL_colors[1],
1210 (IV)(rx_origin - strbeg + prog->anchored_offset),
1211 (IV)(rx_origin - strbeg)
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 with rx_origin %ld...\n",
1220 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
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'. In this case, at worst,
1313 * an extra anchored search may get done, but in
1314 * practice the extra fbm_instr() is likely to
1315 * get skipped anyway. */
1316 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1317 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1318 (long)(other_last - strbeg),
1319 (IV)(rx_origin - strbeg)
1321 goto do_other_substr;
1329 /* In the presence of ml_anch, we might be able to
1330 * find another \n without breaking the current float
1333 /* strictly speaking this should be HOP3c(..., 1, ...),
1334 * but since we goto a block of code that's going to
1335 * search for the next \n if any, its safe here */
1337 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1338 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1339 PL_colors[0], PL_colors[1],
1340 (long)(rx_origin - strbeg)) );
1341 goto postprocess_substr_matches;
1344 /* strictly speaking this can never be true; but might
1345 * be if we ever allow intuit without substrings */
1346 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1349 rx_origin = rx_max_float;
1352 /* at this point, any matching substrings have been
1353 * contradicted. Start again... */
1355 rx_origin = HOP3c(rx_origin, 1, strend);
1357 /* uses bytes rather than char calculations for efficiency.
1358 * It's conservative: it errs on the side of doing 'goto restart',
1359 * where there is code that does a proper char-based test */
1360 if (rx_origin + start_shift + end_shift > strend) {
1361 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1362 " Could not match STCLASS...\n") );
1365 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1366 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1367 (prog->substrs->check_ix ? "floating" : "anchored"),
1368 (long)(rx_origin + start_shift - strbeg),
1369 (IV)(rx_origin - strbeg)
1376 if (rx_origin != s) {
1377 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1378 " By STCLASS: moving %ld --> %ld\n",
1379 (long)(rx_origin - strbeg), (long)(s - strbeg))
1383 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1384 " Does not contradict STCLASS...\n");
1389 /* Decide whether using the substrings helped */
1391 if (rx_origin != strpos) {
1392 /* Fixed substring is found far enough so that the match
1393 cannot start at strpos. */
1395 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1396 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1399 /* The found rx_origin position does not prohibit matching at
1400 * strpos, so calling intuit didn't gain us anything. Decrement
1401 * the BmUSEFUL() count on the check substring, and if we reach
1403 if (!(prog->intflags & PREGf_NAUGHTY)
1405 prog->check_utf8 /* Could be deleted already */
1406 && --BmUSEFUL(prog->check_utf8) < 0
1407 && (prog->check_utf8 == prog->float_utf8)
1409 prog->check_substr /* Could be deleted already */
1410 && --BmUSEFUL(prog->check_substr) < 0
1411 && (prog->check_substr == prog->float_substr)
1414 /* If flags & SOMETHING - do not do it many times on the same match */
1415 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1416 /* XXX Does the destruction order has to change with utf8_target? */
1417 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1418 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1419 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1420 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1421 check = NULL; /* abort */
1422 /* XXXX This is a remnant of the old implementation. It
1423 looks wasteful, since now INTUIT can use many
1424 other heuristics. */
1425 prog->extflags &= ~RXf_USE_INTUIT;
1429 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1430 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1431 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1435 fail_finish: /* Substring not found */
1436 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1437 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1439 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1440 PL_colors[4], PL_colors[5]));
1445 #define DECL_TRIE_TYPE(scan) \
1446 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1447 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1448 trie_utf8l, trie_flu8 } \
1449 trie_type = ((scan->flags == EXACT) \
1450 ? (utf8_target ? trie_utf8 : trie_plain) \
1451 : (scan->flags == EXACTL) \
1452 ? (utf8_target ? trie_utf8l : trie_plain) \
1453 : (scan->flags == EXACTFA) \
1455 ? trie_utf8_exactfa_fold \
1456 : trie_latin_utf8_exactfa_fold) \
1457 : (scan->flags == EXACTFLU8 \
1461 : trie_latin_utf8_fold)))
1463 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1466 U8 flags = FOLD_FLAGS_FULL; \
1467 switch (trie_type) { \
1469 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1470 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1471 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1473 goto do_trie_utf8_fold; \
1474 case trie_utf8_exactfa_fold: \
1475 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1477 case trie_utf8_fold: \
1478 do_trie_utf8_fold: \
1479 if ( foldlen>0 ) { \
1480 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1485 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1486 len = UTF8SKIP(uc); \
1487 skiplen = UVCHR_SKIP( uvc ); \
1488 foldlen -= skiplen; \
1489 uscan = foldbuf + skiplen; \
1492 case trie_latin_utf8_exactfa_fold: \
1493 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1495 case trie_latin_utf8_fold: \
1496 if ( foldlen>0 ) { \
1497 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1503 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1504 skiplen = UVCHR_SKIP( uvc ); \
1505 foldlen -= skiplen; \
1506 uscan = foldbuf + skiplen; \
1510 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1511 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1512 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1516 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1523 charid = trie->charmap[ uvc ]; \
1527 if (widecharmap) { \
1528 SV** const svpp = hv_fetch(widecharmap, \
1529 (char*)&uvc, sizeof(UV), 0); \
1531 charid = (U16)SvIV(*svpp); \
1536 #define DUMP_EXEC_POS(li,s,doutf8) \
1537 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1540 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1544 && (ln == 1 || folder(s, pat_string, ln)) \
1545 && (reginfo->intuit || regtry(reginfo, &s)) )\
1551 #define REXEC_FBC_UTF8_SCAN(CODE) \
1553 while (s < strend) { \
1559 #define REXEC_FBC_SCAN(CODE) \
1561 while (s < strend) { \
1567 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1568 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1570 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1579 #define REXEC_FBC_CLASS_SCAN(COND) \
1580 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1582 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1591 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1592 if (utf8_target) { \
1593 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1596 REXEC_FBC_CLASS_SCAN(COND); \
1599 /* The three macros below are slightly different versions of the same logic.
1601 * The first is for /a and /aa when the target string is UTF-8. This can only
1602 * match ascii, but it must advance based on UTF-8. The other two handle the
1603 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1604 * for the boundary (or non-boundary) between a word and non-word character.
1605 * The utf8 and non-utf8 cases have the same logic, but the details must be
1606 * different. Find the "wordness" of the character just prior to this one, and
1607 * compare it with the wordness of this one. If they differ, we have a
1608 * boundary. At the beginning of the string, pretend that the previous
1609 * character was a new-line.
1611 * All these macros uncleanly have side-effects with each other and outside
1612 * variables. So far it's been too much trouble to clean-up
1614 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1615 * a word character or not.
1616 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1618 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1620 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1621 * are looking for a boundary or for a non-boundary. If we are looking for a
1622 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1623 * see if this tentative match actually works, and if so, to quit the loop
1624 * here. And vice-versa if we are looking for a non-boundary.
1626 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1627 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1628 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1629 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1630 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1631 * complement. But in that branch we complement tmp, meaning that at the
1632 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1633 * which means at the top of the loop in the next iteration, it is
1634 * TEST_NON_UTF8(s-1) */
1635 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1636 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1637 tmp = TEST_NON_UTF8(tmp); \
1638 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1639 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1641 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1648 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1649 * TEST_UTF8 is a macro that for the same input code points returns identically
1650 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1651 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1652 if (s == reginfo->strbeg) { \
1655 else { /* Back-up to the start of the previous character */ \
1656 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1657 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1658 0, UTF8_ALLOW_DEFAULT); \
1660 tmp = TEST_UV(tmp); \
1661 LOAD_UTF8_CHARCLASS_ALNUM(); \
1662 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1663 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1672 /* Like the above two macros. UTF8_CODE is the complete code for handling
1673 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1675 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1676 if (utf8_target) { \
1679 else { /* Not utf8 */ \
1680 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1681 tmp = TEST_NON_UTF8(tmp); \
1682 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1683 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1692 /* Here, things have been set up by the previous code so that tmp is the \
1693 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1694 * utf8ness of the target). We also have to check if this matches against \
1695 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1696 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1698 if (tmp == ! TEST_NON_UTF8('\n')) { \
1705 /* This is the macro to use when we want to see if something that looks like it
1706 * could match, actually does, and if so exits the loop */
1707 #define REXEC_FBC_TRYIT \
1708 if ((reginfo->intuit || regtry(reginfo, &s))) \
1711 /* The only difference between the BOUND and NBOUND cases is that
1712 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1713 * NBOUND. This is accomplished by passing it as either the if or else clause,
1714 * with the other one being empty (PLACEHOLDER is defined as empty).
1716 * The TEST_FOO parameters are for operating on different forms of input, but
1717 * all should be ones that return identically for the same underlying code
1719 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1721 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1722 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1724 #define FBC_BOUND_A(TEST_NON_UTF8) \
1726 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1727 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1729 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1731 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1732 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1734 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1736 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1737 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1739 /* Takes a pointer to an inversion list, a pointer to its corresponding
1740 * inversion map, and a code point, and returns the code point's value
1741 * according to the two arrays. It assumes that all code points have a value.
1742 * This is used as the base macro for macros for particular properties */
1743 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1744 invmap[_invlist_search(invlist, cp)]
1746 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1747 * of a code point, returning the value for the first code point in the string.
1748 * And it takes the particular macro name that finds the desired value given a
1749 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1750 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1751 (__ASSERT_(pos < strend) \
1752 /* Note assumes is valid UTF-8 */ \
1753 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1755 /* Returns the GCB value for the input code point */
1756 #define getGCB_VAL_CP(cp) \
1757 _generic_GET_BREAK_VAL_CP( \
1762 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1763 * bounded by pos and strend */
1764 #define getGCB_VAL_UTF8(pos, strend) \
1765 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1768 /* Returns the SB value for the input code point */
1769 #define getSB_VAL_CP(cp) \
1770 _generic_GET_BREAK_VAL_CP( \
1775 /* Returns the SB value for the first code point in the UTF-8 encoded string
1776 * bounded by pos and strend */
1777 #define getSB_VAL_UTF8(pos, strend) \
1778 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1780 /* Returns the WB value for the input code point */
1781 #define getWB_VAL_CP(cp) \
1782 _generic_GET_BREAK_VAL_CP( \
1787 /* Returns the WB value for the first code point in the UTF-8 encoded string
1788 * bounded by pos and strend */
1789 #define getWB_VAL_UTF8(pos, strend) \
1790 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1792 /* We know what class REx starts with. Try to find this position... */
1793 /* if reginfo->intuit, its a dryrun */
1794 /* annoyingly all the vars in this routine have different names from their counterparts
1795 in regmatch. /grrr */
1797 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1798 const char *strend, regmatch_info *reginfo)
1801 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1802 char *pat_string; /* The pattern's exactish string */
1803 char *pat_end; /* ptr to end char of pat_string */
1804 re_fold_t folder; /* Function for computing non-utf8 folds */
1805 const U8 *fold_array; /* array for folding ords < 256 */
1811 I32 tmp = 1; /* Scratch variable? */
1812 const bool utf8_target = reginfo->is_utf8_target;
1813 UV utf8_fold_flags = 0;
1814 const bool is_utf8_pat = reginfo->is_utf8_pat;
1815 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1816 with a result inverts that result, as 0^1 =
1818 _char_class_number classnum;
1820 RXi_GET_DECL(prog,progi);
1822 PERL_ARGS_ASSERT_FIND_BYCLASS;
1824 /* We know what class it must start with. */
1827 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1829 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1830 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1837 REXEC_FBC_UTF8_CLASS_SCAN(
1838 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1841 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1845 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1846 assert(! is_utf8_pat);
1849 if (is_utf8_pat || utf8_target) {
1850 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1851 goto do_exactf_utf8;
1853 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1854 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1855 goto do_exactf_non_utf8; /* isn't dealt with by these */
1857 case EXACTF: /* This node only generated for non-utf8 patterns */
1858 assert(! is_utf8_pat);
1860 utf8_fold_flags = 0;
1861 goto do_exactf_utf8;
1863 fold_array = PL_fold;
1865 goto do_exactf_non_utf8;
1868 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1869 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1870 utf8_fold_flags = FOLDEQ_LOCALE;
1871 goto do_exactf_utf8;
1873 fold_array = PL_fold_locale;
1874 folder = foldEQ_locale;
1875 goto do_exactf_non_utf8;
1879 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1881 goto do_exactf_utf8;
1884 if (! utf8_target) { /* All code points in this node require
1885 UTF-8 to express. */
1888 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1889 | FOLDEQ_S2_FOLDS_SANE;
1890 goto do_exactf_utf8;
1893 if (is_utf8_pat || utf8_target) {
1894 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1895 goto do_exactf_utf8;
1898 /* Any 'ss' in the pattern should have been replaced by regcomp,
1899 * so we don't have to worry here about this single special case
1900 * in the Latin1 range */
1901 fold_array = PL_fold_latin1;
1902 folder = foldEQ_latin1;
1906 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1907 are no glitches with fold-length differences
1908 between the target string and pattern */
1910 /* The idea in the non-utf8 EXACTF* cases is to first find the
1911 * first character of the EXACTF* node and then, if necessary,
1912 * case-insensitively compare the full text of the node. c1 is the
1913 * first character. c2 is its fold. This logic will not work for
1914 * Unicode semantics and the german sharp ss, which hence should
1915 * not be compiled into a node that gets here. */
1916 pat_string = STRING(c);
1917 ln = STR_LEN(c); /* length to match in octets/bytes */
1919 /* We know that we have to match at least 'ln' bytes (which is the
1920 * same as characters, since not utf8). If we have to match 3
1921 * characters, and there are only 2 availabe, we know without
1922 * trying that it will fail; so don't start a match past the
1923 * required minimum number from the far end */
1924 e = HOP3c(strend, -((SSize_t)ln), s);
1926 if (reginfo->intuit && e < s) {
1927 e = s; /* Due to minlen logic of intuit() */
1931 c2 = fold_array[c1];
1932 if (c1 == c2) { /* If char and fold are the same */
1933 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1936 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1944 /* If one of the operands is in utf8, we can't use the simpler folding
1945 * above, due to the fact that many different characters can have the
1946 * same fold, or portion of a fold, or different- length fold */
1947 pat_string = STRING(c);
1948 ln = STR_LEN(c); /* length to match in octets/bytes */
1949 pat_end = pat_string + ln;
1950 lnc = is_utf8_pat /* length to match in characters */
1951 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1954 /* We have 'lnc' characters to match in the pattern, but because of
1955 * multi-character folding, each character in the target can match
1956 * up to 3 characters (Unicode guarantees it will never exceed
1957 * this) if it is utf8-encoded; and up to 2 if not (based on the
1958 * fact that the Latin 1 folds are already determined, and the
1959 * only multi-char fold in that range is the sharp-s folding to
1960 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1961 * string character. Adjust lnc accordingly, rounding up, so that
1962 * if we need to match at least 4+1/3 chars, that really is 5. */
1963 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1964 lnc = (lnc + expansion - 1) / expansion;
1966 /* As in the non-UTF8 case, if we have to match 3 characters, and
1967 * only 2 are left, it's guaranteed to fail, so don't start a
1968 * match that would require us to go beyond the end of the string
1970 e = HOP3c(strend, -((SSize_t)lnc), s);
1972 if (reginfo->intuit && e < s) {
1973 e = s; /* Due to minlen logic of intuit() */
1976 /* XXX Note that we could recalculate e to stop the loop earlier,
1977 * as the worst case expansion above will rarely be met, and as we
1978 * go along we would usually find that e moves further to the left.
1979 * This would happen only after we reached the point in the loop
1980 * where if there were no expansion we should fail. Unclear if
1981 * worth the expense */
1984 char *my_strend= (char *)strend;
1985 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1986 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1987 && (reginfo->intuit || regtry(reginfo, &s)) )
1991 s += (utf8_target) ? UTF8SKIP(s) : 1;
1997 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1998 if (FLAGS(c) != TRADITIONAL_BOUND) {
1999 if (! IN_UTF8_CTYPE_LOCALE) {
2000 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2001 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2006 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2010 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2011 if (FLAGS(c) != TRADITIONAL_BOUND) {
2012 if (! IN_UTF8_CTYPE_LOCALE) {
2013 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2014 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2019 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2022 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2024 assert(FLAGS(c) == TRADITIONAL_BOUND);
2026 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2029 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2031 assert(FLAGS(c) == TRADITIONAL_BOUND);
2033 FBC_BOUND_A(isWORDCHAR_A);
2036 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2038 assert(FLAGS(c) == TRADITIONAL_BOUND);
2040 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2043 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2045 assert(FLAGS(c) == TRADITIONAL_BOUND);
2047 FBC_NBOUND_A(isWORDCHAR_A);
2051 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2052 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2063 switch((bound_type) FLAGS(c)) {
2064 case TRADITIONAL_BOUND:
2065 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2068 if (s == reginfo->strbeg) {
2069 if (reginfo->intuit || regtry(reginfo, &s))
2074 /* Didn't match. Try at the next position (if there is one) */
2075 s += (utf8_target) ? UTF8SKIP(s) : 1;
2076 if (UNLIKELY(s >= reginfo->strend)) {
2082 GCB_enum before = getGCB_VAL_UTF8(
2084 (U8*)(reginfo->strbeg)),
2085 (U8*) reginfo->strend);
2086 while (s < strend) {
2087 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2088 (U8*) reginfo->strend);
2089 if ( (to_complement ^ isGCB(before, after))
2090 && (reginfo->intuit || regtry(reginfo, &s)))
2098 else { /* Not utf8. Everything is a GCB except between CR and
2100 while (s < strend) {
2101 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2102 || UCHARAT(s) != '\n'))
2103 && (reginfo->intuit || regtry(reginfo, &s)))
2111 /* And, since this is a bound, it can match after the final
2112 * character in the string */
2113 if ((reginfo->intuit || regtry(reginfo, &s))) {
2119 if (s == reginfo->strbeg) {
2120 if (reginfo->intuit || regtry(reginfo, &s)) {
2123 s += (utf8_target) ? UTF8SKIP(s) : 1;
2124 if (UNLIKELY(s >= reginfo->strend)) {
2130 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2132 (U8*)(reginfo->strbeg)),
2133 (U8*) reginfo->strend);
2134 while (s < strend) {
2135 SB_enum after = getSB_VAL_UTF8((U8*) s,
2136 (U8*) reginfo->strend);
2137 if ((to_complement ^ isSB(before,
2139 (U8*) reginfo->strbeg,
2141 (U8*) reginfo->strend,
2143 && (reginfo->intuit || regtry(reginfo, &s)))
2151 else { /* Not utf8. */
2152 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2153 while (s < strend) {
2154 SB_enum after = getSB_VAL_CP((U8) *s);
2155 if ((to_complement ^ isSB(before,
2157 (U8*) reginfo->strbeg,
2159 (U8*) reginfo->strend,
2161 && (reginfo->intuit || regtry(reginfo, &s)))
2170 /* Here are at the final position in the target string. The SB
2171 * value is always true here, so matches, depending on other
2173 if (reginfo->intuit || regtry(reginfo, &s)) {
2180 if (s == reginfo->strbeg) {
2181 if (reginfo->intuit || regtry(reginfo, &s)) {
2184 s += (utf8_target) ? UTF8SKIP(s) : 1;
2185 if (UNLIKELY(s >= reginfo->strend)) {
2191 /* We are at a boundary between char_sub_0 and char_sub_1.
2192 * We also keep track of the value for char_sub_-1 as we
2193 * loop through the line. Context may be needed to make a
2194 * determination, and if so, this can save having to
2196 WB_enum previous = WB_UNKNOWN;
2197 WB_enum before = getWB_VAL_UTF8(
2200 (U8*)(reginfo->strbeg)),
2201 (U8*) reginfo->strend);
2202 while (s < strend) {
2203 WB_enum after = getWB_VAL_UTF8((U8*) s,
2204 (U8*) reginfo->strend);
2205 if ((to_complement ^ isWB(previous,
2208 (U8*) reginfo->strbeg,
2210 (U8*) reginfo->strend,
2212 && (reginfo->intuit || regtry(reginfo, &s)))
2221 else { /* Not utf8. */
2222 WB_enum previous = WB_UNKNOWN;
2223 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2224 while (s < strend) {
2225 WB_enum after = getWB_VAL_CP((U8) *s);
2226 if ((to_complement ^ isWB(previous,
2229 (U8*) reginfo->strbeg,
2231 (U8*) reginfo->strend,
2233 && (reginfo->intuit || regtry(reginfo, &s)))
2243 if (reginfo->intuit || regtry(reginfo, &s)) {
2250 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2251 is_LNBREAK_latin1_safe(s, strend)
2255 /* The argument to all the POSIX node types is the class number to pass to
2256 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2263 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2264 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2265 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2280 /* The complement of something that matches only ASCII matches all
2281 * non-ASCII, plus everything in ASCII that isn't in the class. */
2282 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2283 || ! _generic_isCC_A(*s, FLAGS(c)));
2292 /* Don't need to worry about utf8, as it can match only a single
2293 * byte invariant character. */
2294 REXEC_FBC_CLASS_SCAN(
2295 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2303 if (! utf8_target) {
2304 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2310 classnum = (_char_class_number) FLAGS(c);
2311 if (classnum < _FIRST_NON_SWASH_CC) {
2312 while (s < strend) {
2314 /* We avoid loading in the swash as long as possible, but
2315 * should we have to, we jump to a separate loop. This
2316 * extra 'if' statement is what keeps this code from being
2317 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2318 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2319 goto found_above_latin1;
2321 if ((UTF8_IS_INVARIANT(*s)
2322 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2324 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2325 && to_complement ^ cBOOL(
2326 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2330 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2342 else switch (classnum) { /* These classes are implemented as
2344 case _CC_ENUM_SPACE:
2345 REXEC_FBC_UTF8_CLASS_SCAN(
2346 to_complement ^ cBOOL(isSPACE_utf8(s)));
2349 case _CC_ENUM_BLANK:
2350 REXEC_FBC_UTF8_CLASS_SCAN(
2351 to_complement ^ cBOOL(isBLANK_utf8(s)));
2354 case _CC_ENUM_XDIGIT:
2355 REXEC_FBC_UTF8_CLASS_SCAN(
2356 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2359 case _CC_ENUM_VERTSPACE:
2360 REXEC_FBC_UTF8_CLASS_SCAN(
2361 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2364 case _CC_ENUM_CNTRL:
2365 REXEC_FBC_UTF8_CLASS_SCAN(
2366 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2370 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2371 NOT_REACHED; /* NOTREACHED */
2376 found_above_latin1: /* Here we have to load a swash to get the result
2377 for the current code point */
2378 if (! PL_utf8_swash_ptrs[classnum]) {
2379 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2380 PL_utf8_swash_ptrs[classnum] =
2381 _core_swash_init("utf8",
2384 PL_XPosix_ptrs[classnum], &flags);
2387 /* This is a copy of the loop above for swash classes, though using the
2388 * FBC macro instead of being expanded out. Since we've loaded the
2389 * swash, we don't have to check for that each time through the loop */
2390 REXEC_FBC_UTF8_CLASS_SCAN(
2391 to_complement ^ cBOOL(_generic_utf8(
2394 swash_fetch(PL_utf8_swash_ptrs[classnum],
2402 /* what trie are we using right now */
2403 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2404 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2405 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2407 const char *last_start = strend - trie->minlen;
2409 const char *real_start = s;
2411 STRLEN maxlen = trie->maxlen;
2413 U8 **points; /* map of where we were in the input string
2414 when reading a given char. For ASCII this
2415 is unnecessary overhead as the relationship
2416 is always 1:1, but for Unicode, especially
2417 case folded Unicode this is not true. */
2418 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2422 GET_RE_DEBUG_FLAGS_DECL;
2424 /* We can't just allocate points here. We need to wrap it in
2425 * an SV so it gets freed properly if there is a croak while
2426 * running the match */
2429 sv_points=newSV(maxlen * sizeof(U8 *));
2430 SvCUR_set(sv_points,
2431 maxlen * sizeof(U8 *));
2432 SvPOK_on(sv_points);
2433 sv_2mortal(sv_points);
2434 points=(U8**)SvPV_nolen(sv_points );
2435 if ( trie_type != trie_utf8_fold
2436 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2439 bitmap=(U8*)trie->bitmap;
2441 bitmap=(U8*)ANYOF_BITMAP(c);
2443 /* this is the Aho-Corasick algorithm modified a touch
2444 to include special handling for long "unknown char" sequences.
2445 The basic idea being that we use AC as long as we are dealing
2446 with a possible matching char, when we encounter an unknown char
2447 (and we have not encountered an accepting state) we scan forward
2448 until we find a legal starting char.
2449 AC matching is basically that of trie matching, except that when
2450 we encounter a failing transition, we fall back to the current
2451 states "fail state", and try the current char again, a process
2452 we repeat until we reach the root state, state 1, or a legal
2453 transition. If we fail on the root state then we can either
2454 terminate if we have reached an accepting state previously, or
2455 restart the entire process from the beginning if we have not.
2458 while (s <= last_start) {
2459 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2467 U8 *uscan = (U8*)NULL;
2468 U8 *leftmost = NULL;
2470 U32 accepted_word= 0;
2474 while ( state && uc <= (U8*)strend ) {
2476 U32 word = aho->states[ state ].wordnum;
2480 DEBUG_TRIE_EXECUTE_r(
2481 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2482 dump_exec_pos( (char *)uc, c, strend, real_start,
2483 (char *)uc, utf8_target );
2484 PerlIO_printf( Perl_debug_log,
2485 " Scanning for legal start char...\n");
2489 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2493 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2499 if (uc >(U8*)last_start) break;
2503 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2504 if (!leftmost || lpos < leftmost) {
2505 DEBUG_r(accepted_word=word);
2511 points[pointpos++ % maxlen]= uc;
2512 if (foldlen || uc < (U8*)strend) {
2513 REXEC_TRIE_READ_CHAR(trie_type, trie,
2515 uscan, len, uvc, charid, foldlen,
2517 DEBUG_TRIE_EXECUTE_r({
2518 dump_exec_pos( (char *)uc, c, strend,
2519 real_start, s, utf8_target);
2520 PerlIO_printf(Perl_debug_log,
2521 " Charid:%3u CP:%4"UVxf" ",
2533 word = aho->states[ state ].wordnum;
2535 base = aho->states[ state ].trans.base;
2537 DEBUG_TRIE_EXECUTE_r({
2539 dump_exec_pos( (char *)uc, c, strend, real_start,
2541 PerlIO_printf( Perl_debug_log,
2542 "%sState: %4"UVxf", word=%"UVxf,
2543 failed ? " Fail transition to " : "",
2544 (UV)state, (UV)word);
2550 ( ((offset = base + charid
2551 - 1 - trie->uniquecharcount)) >= 0)
2552 && ((U32)offset < trie->lasttrans)
2553 && trie->trans[offset].check == state
2554 && (tmp=trie->trans[offset].next))
2556 DEBUG_TRIE_EXECUTE_r(
2557 PerlIO_printf( Perl_debug_log," - legal\n"));
2562 DEBUG_TRIE_EXECUTE_r(
2563 PerlIO_printf( Perl_debug_log," - fail\n"));
2565 state = aho->fail[state];
2569 /* we must be accepting here */
2570 DEBUG_TRIE_EXECUTE_r(
2571 PerlIO_printf( Perl_debug_log," - accepting\n"));
2580 if (!state) state = 1;
2583 if ( aho->states[ state ].wordnum ) {
2584 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2585 if (!leftmost || lpos < leftmost) {
2586 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2591 s = (char*)leftmost;
2592 DEBUG_TRIE_EXECUTE_r({
2594 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2595 (UV)accepted_word, (IV)(s - real_start)
2598 if (reginfo->intuit || regtry(reginfo, &s)) {
2604 DEBUG_TRIE_EXECUTE_r({
2605 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2608 DEBUG_TRIE_EXECUTE_r(
2609 PerlIO_printf( Perl_debug_log,"No match.\n"));
2618 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2625 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2626 * flags have same meanings as with regexec_flags() */
2629 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2636 struct regexp *const prog = ReANY(rx);
2638 if (flags & REXEC_COPY_STR) {
2642 PerlIO_printf(Perl_debug_log,
2643 "Copy on write: regexp capture, type %d\n",
2646 /* Create a new COW SV to share the match string and store
2647 * in saved_copy, unless the current COW SV in saved_copy
2648 * is valid and suitable for our purpose */
2649 if (( prog->saved_copy
2650 && SvIsCOW(prog->saved_copy)
2651 && SvPOKp(prog->saved_copy)
2654 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2656 /* just reuse saved_copy SV */
2657 if (RXp_MATCH_COPIED(prog)) {
2658 Safefree(prog->subbeg);
2659 RXp_MATCH_COPIED_off(prog);
2663 /* create new COW SV to share string */
2664 RX_MATCH_COPY_FREE(rx);
2665 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2667 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2668 assert (SvPOKp(prog->saved_copy));
2669 prog->sublen = strend - strbeg;
2670 prog->suboffset = 0;
2671 prog->subcoffset = 0;
2676 SSize_t max = strend - strbeg;
2679 if ( (flags & REXEC_COPY_SKIP_POST)
2680 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2681 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2682 ) { /* don't copy $' part of string */
2685 /* calculate the right-most part of the string covered
2686 * by a capture. Due to lookahead, this may be to
2687 * the right of $&, so we have to scan all captures */
2688 while (n <= prog->lastparen) {
2689 if (prog->offs[n].end > max)
2690 max = prog->offs[n].end;
2694 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2695 ? prog->offs[0].start
2697 assert(max >= 0 && max <= strend - strbeg);
2700 if ( (flags & REXEC_COPY_SKIP_PRE)
2701 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2702 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2703 ) { /* don't copy $` part of string */
2706 /* calculate the left-most part of the string covered
2707 * by a capture. Due to lookbehind, this may be to
2708 * the left of $&, so we have to scan all captures */
2709 while (min && n <= prog->lastparen) {
2710 if ( prog->offs[n].start != -1
2711 && prog->offs[n].start < min)
2713 min = prog->offs[n].start;
2717 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2718 && min > prog->offs[0].end
2720 min = prog->offs[0].end;
2724 assert(min >= 0 && min <= max && min <= strend - strbeg);
2727 if (RX_MATCH_COPIED(rx)) {
2728 if (sublen > prog->sublen)
2730 (char*)saferealloc(prog->subbeg, sublen+1);
2733 prog->subbeg = (char*)safemalloc(sublen+1);
2734 Copy(strbeg + min, prog->subbeg, sublen, char);
2735 prog->subbeg[sublen] = '\0';
2736 prog->suboffset = min;
2737 prog->sublen = sublen;
2738 RX_MATCH_COPIED_on(rx);
2740 prog->subcoffset = prog->suboffset;
2741 if (prog->suboffset && utf8_target) {
2742 /* Convert byte offset to chars.
2743 * XXX ideally should only compute this if @-/@+
2744 * has been seen, a la PL_sawampersand ??? */
2746 /* If there's a direct correspondence between the
2747 * string which we're matching and the original SV,
2748 * then we can use the utf8 len cache associated with
2749 * the SV. In particular, it means that under //g,
2750 * sv_pos_b2u() will use the previously cached
2751 * position to speed up working out the new length of
2752 * subcoffset, rather than counting from the start of
2753 * the string each time. This stops
2754 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2755 * from going quadratic */
2756 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2757 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2758 SV_GMAGIC|SV_CONST_RETURN);
2760 prog->subcoffset = utf8_length((U8*)strbeg,
2761 (U8*)(strbeg+prog->suboffset));
2765 RX_MATCH_COPY_FREE(rx);
2766 prog->subbeg = strbeg;
2767 prog->suboffset = 0;
2768 prog->subcoffset = 0;
2769 prog->sublen = strend - strbeg;
2777 - regexec_flags - match a regexp against a string
2780 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2781 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2782 /* stringarg: the point in the string at which to begin matching */
2783 /* strend: pointer to null at end of string */
2784 /* strbeg: real beginning of string */
2785 /* minend: end of match must be >= minend bytes after stringarg. */
2786 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2787 * itself is accessed via the pointers above */
2788 /* data: May be used for some additional optimizations.
2789 Currently unused. */
2790 /* flags: For optimizations. See REXEC_* in regexp.h */
2793 struct regexp *const prog = ReANY(rx);
2797 SSize_t minlen; /* must match at least this many chars */
2798 SSize_t dontbother = 0; /* how many characters not to try at end */
2799 const bool utf8_target = cBOOL(DO_UTF8(sv));
2801 RXi_GET_DECL(prog,progi);
2802 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2803 regmatch_info *const reginfo = ®info_buf;
2804 regexp_paren_pair *swap = NULL;
2806 GET_RE_DEBUG_FLAGS_DECL;
2808 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2809 PERL_UNUSED_ARG(data);
2811 /* Be paranoid... */
2813 Perl_croak(aTHX_ "NULL regexp parameter");
2817 debug_start_match(rx, utf8_target, stringarg, strend,
2821 startpos = stringarg;
2823 /* set these early as they may be used by the HOP macros below */
2824 reginfo->strbeg = strbeg;
2825 reginfo->strend = strend;
2826 reginfo->is_utf8_target = cBOOL(utf8_target);
2828 if (prog->intflags & PREGf_GPOS_SEEN) {
2831 /* set reginfo->ganch, the position where \G can match */
2834 (flags & REXEC_IGNOREPOS)
2835 ? stringarg /* use start pos rather than pos() */
2836 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2837 /* Defined pos(): */
2838 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2839 : strbeg; /* pos() not defined; use start of string */
2841 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2842 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2844 /* in the presence of \G, we may need to start looking earlier in
2845 * the string than the suggested start point of stringarg:
2846 * if prog->gofs is set, then that's a known, fixed minimum
2849 * /ab|c\G/: gofs = 1
2850 * or if the minimum offset isn't known, then we have to go back
2851 * to the start of the string, e.g. /w+\G/
2854 if (prog->intflags & PREGf_ANCH_GPOS) {
2856 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2858 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2860 DEBUG_r(PerlIO_printf(Perl_debug_log,
2861 "fail: ganch-gofs before earliest possible start\n"));
2866 startpos = reginfo->ganch;
2868 else if (prog->gofs) {
2869 startpos = HOPBACKc(startpos, prog->gofs);
2873 else if (prog->intflags & PREGf_GPOS_FLOAT)
2877 minlen = prog->minlen;
2878 if ((startpos + minlen) > strend || startpos < strbeg) {
2879 DEBUG_r(PerlIO_printf(Perl_debug_log,
2880 "Regex match can't succeed, so not even tried\n"));
2884 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2885 * which will call destuctors to reset PL_regmatch_state, free higher
2886 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2887 * regmatch_info_aux_eval */
2889 oldsave = PL_savestack_ix;
2893 if ((prog->extflags & RXf_USE_INTUIT)
2894 && !(flags & REXEC_CHECKED))
2896 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2901 if (prog->extflags & RXf_CHECK_ALL) {
2902 /* we can match based purely on the result of INTUIT.
2903 * Set up captures etc just for $& and $-[0]
2904 * (an intuit-only match wont have $1,$2,..) */
2905 assert(!prog->nparens);
2907 /* s/// doesn't like it if $& is earlier than where we asked it to
2908 * start searching (which can happen on something like /.\G/) */
2909 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2912 /* this should only be possible under \G */
2913 assert(prog->intflags & PREGf_GPOS_SEEN);
2914 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2915 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2919 /* match via INTUIT shouldn't have any captures.
2920 * Let @-, @+, $^N know */
2921 prog->lastparen = prog->lastcloseparen = 0;
2922 RX_MATCH_UTF8_set(rx, utf8_target);
2923 prog->offs[0].start = s - strbeg;
2924 prog->offs[0].end = utf8_target
2925 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2926 : s - strbeg + prog->minlenret;
2927 if ( !(flags & REXEC_NOT_FIRST) )
2928 S_reg_set_capture_string(aTHX_ rx,
2930 sv, flags, utf8_target);
2936 multiline = prog->extflags & RXf_PMf_MULTILINE;
2938 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2939 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2940 "String too short [regexec_flags]...\n"));
2944 /* Check validity of program. */
2945 if (UCHARAT(progi->program) != REG_MAGIC) {
2946 Perl_croak(aTHX_ "corrupted regexp program");
2949 RX_MATCH_TAINTED_off(rx);
2950 RX_MATCH_UTF8_set(rx, utf8_target);
2952 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2953 reginfo->intuit = 0;
2954 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2955 reginfo->warned = FALSE;
2957 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2958 /* see how far we have to get to not match where we matched before */
2959 reginfo->till = stringarg + minend;
2961 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2962 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2963 S_cleanup_regmatch_info_aux has executed (registered by
2964 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2965 magic belonging to this SV.
2966 Not newSVsv, either, as it does not COW.
2968 reginfo->sv = newSV(0);
2969 SvSetSV_nosteal(reginfo->sv, sv);
2970 SAVEFREESV(reginfo->sv);
2973 /* reserve next 2 or 3 slots in PL_regmatch_state:
2974 * slot N+0: may currently be in use: skip it
2975 * slot N+1: use for regmatch_info_aux struct
2976 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2977 * slot N+3: ready for use by regmatch()
2981 regmatch_state *old_regmatch_state;
2982 regmatch_slab *old_regmatch_slab;
2983 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2985 /* on first ever match, allocate first slab */
2986 if (!PL_regmatch_slab) {
2987 Newx(PL_regmatch_slab, 1, regmatch_slab);
2988 PL_regmatch_slab->prev = NULL;
2989 PL_regmatch_slab->next = NULL;
2990 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2993 old_regmatch_state = PL_regmatch_state;
2994 old_regmatch_slab = PL_regmatch_slab;
2996 for (i=0; i <= max; i++) {
2998 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3000 reginfo->info_aux_eval =
3001 reginfo->info_aux->info_aux_eval =
3002 &(PL_regmatch_state->u.info_aux_eval);
3004 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3005 PL_regmatch_state = S_push_slab(aTHX);
3008 /* note initial PL_regmatch_state position; at end of match we'll
3009 * pop back to there and free any higher slabs */
3011 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3012 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3013 reginfo->info_aux->poscache = NULL;
3015 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3017 if ((prog->extflags & RXf_EVAL_SEEN))
3018 S_setup_eval_state(aTHX_ reginfo);
3020 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3023 /* If there is a "must appear" string, look for it. */
3025 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3026 /* We have to be careful. If the previous successful match
3027 was from this regex we don't want a subsequent partially
3028 successful match to clobber the old results.
3029 So when we detect this possibility we add a swap buffer
3030 to the re, and switch the buffer each match. If we fail,
3031 we switch it back; otherwise we leave it swapped.
3034 /* do we need a save destructor here for eval dies? */
3035 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3036 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3037 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3044 /* Simplest case: anchored match need be tried only once, or with
3045 * MBOL, only at the beginning of each line.
3047 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3048 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3049 * match at the start of the string then it won't match anywhere else
3050 * either; while with /.*.../, if it doesn't match at the beginning,
3051 * the earliest it could match is at the start of the next line */
3053 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3056 if (regtry(reginfo, &s))
3059 if (!(prog->intflags & PREGf_ANCH_MBOL))
3062 /* didn't match at start, try at other newline positions */
3065 dontbother = minlen - 1;
3066 end = HOP3c(strend, -dontbother, strbeg) - 1;
3068 /* skip to next newline */
3070 while (s <= end) { /* note it could be possible to match at the end of the string */
3071 /* NB: newlines are the same in unicode as they are in latin */
3074 if (prog->check_substr || prog->check_utf8) {
3075 /* note that with PREGf_IMPLICIT, intuit can only fail
3076 * or return the start position, so it's of limited utility.
3077 * Nevertheless, I made the decision that the potential for
3078 * quick fail was still worth it - DAPM */
3079 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3083 if (regtry(reginfo, &s))
3087 } /* end anchored search */
3089 if (prog->intflags & PREGf_ANCH_GPOS)
3091 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3092 assert(prog->intflags & PREGf_GPOS_SEEN);
3093 /* For anchored \G, the only position it can match from is
3094 * (ganch-gofs); we already set startpos to this above; if intuit
3095 * moved us on from there, we can't possibly succeed */
3096 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3097 if (s == startpos && regtry(reginfo, &s))
3102 /* Messy cases: unanchored match. */
3103 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3104 /* we have /x+whatever/ */
3105 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3111 if (! prog->anchored_utf8) {
3112 to_utf8_substr(prog);
3114 ch = SvPVX_const(prog->anchored_utf8)[0];
3117 DEBUG_EXECUTE_r( did_match = 1 );
3118 if (regtry(reginfo, &s)) goto got_it;
3120 while (s < strend && *s == ch)
3127 if (! prog->anchored_substr) {
3128 if (! to_byte_substr(prog)) {
3129 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3132 ch = SvPVX_const(prog->anchored_substr)[0];
3135 DEBUG_EXECUTE_r( did_match = 1 );
3136 if (regtry(reginfo, &s)) goto got_it;
3138 while (s < strend && *s == ch)
3143 DEBUG_EXECUTE_r(if (!did_match)
3144 PerlIO_printf(Perl_debug_log,
3145 "Did not find anchored character...\n")
3148 else if (prog->anchored_substr != NULL
3149 || prog->anchored_utf8 != NULL
3150 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3151 && prog->float_max_offset < strend - s)) {
3156 char *last1; /* Last position checked before */
3160 if (prog->anchored_substr || prog->anchored_utf8) {
3162 if (! prog->anchored_utf8) {
3163 to_utf8_substr(prog);
3165 must = prog->anchored_utf8;
3168 if (! prog->anchored_substr) {
3169 if (! to_byte_substr(prog)) {
3170 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3173 must = prog->anchored_substr;
3175 back_max = back_min = prog->anchored_offset;
3178 if (! prog->float_utf8) {
3179 to_utf8_substr(prog);
3181 must = prog->float_utf8;
3184 if (! prog->float_substr) {
3185 if (! to_byte_substr(prog)) {
3186 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3189 must = prog->float_substr;
3191 back_max = prog->float_max_offset;
3192 back_min = prog->float_min_offset;
3198 last = HOP3c(strend, /* Cannot start after this */
3199 -(SSize_t)(CHR_SVLEN(must)
3200 - (SvTAIL(must) != 0) + back_min), strbeg);
3202 if (s > reginfo->strbeg)
3203 last1 = HOPc(s, -1);
3205 last1 = s - 1; /* bogus */
3207 /* XXXX check_substr already used to find "s", can optimize if
3208 check_substr==must. */
3210 strend = HOPc(strend, -dontbother);
3211 while ( (s <= last) &&
3212 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3213 (unsigned char*)strend, must,
3214 multiline ? FBMrf_MULTILINE : 0)) ) {
3215 DEBUG_EXECUTE_r( did_match = 1 );
3216 if (HOPc(s, -back_max) > last1) {
3217 last1 = HOPc(s, -back_min);
3218 s = HOPc(s, -back_max);
3221 char * const t = (last1 >= reginfo->strbeg)
3222 ? HOPc(last1, 1) : last1 + 1;
3224 last1 = HOPc(s, -back_min);
3228 while (s <= last1) {
3229 if (regtry(reginfo, &s))
3232 s++; /* to break out of outer loop */
3239 while (s <= last1) {
3240 if (regtry(reginfo, &s))
3246 DEBUG_EXECUTE_r(if (!did_match) {
3247 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3248 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3249 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3250 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3251 ? "anchored" : "floating"),
3252 quoted, RE_SV_TAIL(must));
3256 else if ( (c = progi->regstclass) ) {
3258 const OPCODE op = OP(progi->regstclass);
3259 /* don't bother with what can't match */
3260 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3261 strend = HOPc(strend, -(minlen - 1));
3264 SV * const prop = sv_newmortal();
3265 regprop(prog, prop, c, reginfo, NULL);
3267 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3269 PerlIO_printf(Perl_debug_log,
3270 "Matching stclass %.*s against %s (%d bytes)\n",
3271 (int)SvCUR(prop), SvPVX_const(prop),
3272 quoted, (int)(strend - s));
3275 if (find_byclass(prog, c, s, strend, reginfo))
3277 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3281 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3289 if (! prog->float_utf8) {
3290 to_utf8_substr(prog);
3292 float_real = prog->float_utf8;
3295 if (! prog->float_substr) {
3296 if (! to_byte_substr(prog)) {
3297 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3300 float_real = prog->float_substr;
3303 little = SvPV_const(float_real, len);
3304 if (SvTAIL(float_real)) {
3305 /* This means that float_real contains an artificial \n on
3306 * the end due to the presence of something like this:
3307 * /foo$/ where we can match both "foo" and "foo\n" at the
3308 * end of the string. So we have to compare the end of the
3309 * string first against the float_real without the \n and
3310 * then against the full float_real with the string. We
3311 * have to watch out for cases where the string might be
3312 * smaller than the float_real or the float_real without
3314 char *checkpos= strend - len;
3316 PerlIO_printf(Perl_debug_log,
3317 "%sChecking for float_real.%s\n",
3318 PL_colors[4], PL_colors[5]));
3319 if (checkpos + 1 < strbeg) {
3320 /* can't match, even if we remove the trailing \n
3321 * string is too short to match */
3323 PerlIO_printf(Perl_debug_log,
3324 "%sString shorter than required trailing substring, cannot match.%s\n",
3325 PL_colors[4], PL_colors[5]));
3327 } else if (memEQ(checkpos + 1, little, len - 1)) {
3328 /* can match, the end of the string matches without the
3330 last = checkpos + 1;
3331 } else if (checkpos < strbeg) {
3332 /* cant match, string is too short when the "\n" is
3335 PerlIO_printf(Perl_debug_log,
3336 "%sString does not contain required trailing substring, cannot match.%s\n",
3337 PL_colors[4], PL_colors[5]));
3339 } else if (!multiline) {
3340 /* non multiline match, so compare with the "\n" at the
3341 * end of the string */
3342 if (memEQ(checkpos, little, len)) {
3346 PerlIO_printf(Perl_debug_log,
3347 "%sString does not contain required trailing substring, cannot match.%s\n",
3348 PL_colors[4], PL_colors[5]));
3352 /* multiline match, so we have to search for a place
3353 * where the full string is located */
3359 last = rninstr(s, strend, little, little + len);
3361 last = strend; /* matching "$" */
3364 /* at one point this block contained a comment which was
3365 * probably incorrect, which said that this was a "should not
3366 * happen" case. Even if it was true when it was written I am
3367 * pretty sure it is not anymore, so I have removed the comment
3368 * and replaced it with this one. Yves */
3370 PerlIO_printf(Perl_debug_log,
3371 "%sString does not contain required substring, cannot match.%s\n",
3372 PL_colors[4], PL_colors[5]
3376 dontbother = strend - last + prog->float_min_offset;
3378 if (minlen && (dontbother < minlen))
3379 dontbother = minlen - 1;
3380 strend -= dontbother; /* this one's always in bytes! */
3381 /* We don't know much -- general case. */
3384 if (regtry(reginfo, &s))
3393 if (regtry(reginfo, &s))
3395 } while (s++ < strend);
3403 /* s/// doesn't like it if $& is earlier than where we asked it to
3404 * start searching (which can happen on something like /.\G/) */
3405 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3406 && (prog->offs[0].start < stringarg - strbeg))
3408 /* this should only be possible under \G */
3409 assert(prog->intflags & PREGf_GPOS_SEEN);
3410 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3411 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3417 PerlIO_printf(Perl_debug_log,
3418 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3425 /* clean up; this will trigger destructors that will free all slabs
3426 * above the current one, and cleanup the regmatch_info_aux
3427 * and regmatch_info_aux_eval sructs */
3429 LEAVE_SCOPE(oldsave);
3431 if (RXp_PAREN_NAMES(prog))
3432 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3434 /* make sure $`, $&, $', and $digit will work later */
3435 if ( !(flags & REXEC_NOT_FIRST) )
3436 S_reg_set_capture_string(aTHX_ rx,
3437 strbeg, reginfo->strend,
3438 sv, flags, utf8_target);
3443 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3444 PL_colors[4], PL_colors[5]));
3446 /* clean up; this will trigger destructors that will free all slabs
3447 * above the current one, and cleanup the regmatch_info_aux
3448 * and regmatch_info_aux_eval sructs */
3450 LEAVE_SCOPE(oldsave);
3453 /* we failed :-( roll it back */
3454 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3455 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3460 Safefree(prog->offs);
3467 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3468 * Do inc before dec, in case old and new rex are the same */
3469 #define SET_reg_curpm(Re2) \
3470 if (reginfo->info_aux_eval) { \
3471 (void)ReREFCNT_inc(Re2); \
3472 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3473 PM_SETRE((PL_reg_curpm), (Re2)); \
3478 - regtry - try match at specific point
3480 STATIC bool /* 0 failure, 1 success */
3481 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3484 REGEXP *const rx = reginfo->prog;
3485 regexp *const prog = ReANY(rx);
3487 RXi_GET_DECL(prog,progi);
3488 GET_RE_DEBUG_FLAGS_DECL;
3490 PERL_ARGS_ASSERT_REGTRY;
3492 reginfo->cutpoint=NULL;
3494 prog->offs[0].start = *startposp - reginfo->strbeg;
3495 prog->lastparen = 0;
3496 prog->lastcloseparen = 0;
3498 /* XXXX What this code is doing here?!!! There should be no need
3499 to do this again and again, prog->lastparen should take care of
3502 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3503 * Actually, the code in regcppop() (which Ilya may be meaning by
3504 * prog->lastparen), is not needed at all by the test suite
3505 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3506 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3507 * Meanwhile, this code *is* needed for the
3508 * above-mentioned test suite tests to succeed. The common theme
3509 * on those tests seems to be returning null fields from matches.
3510 * --jhi updated by dapm */
3512 if (prog->nparens) {
3513 regexp_paren_pair *pp = prog->offs;
3515 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3523 result = regmatch(reginfo, *startposp, progi->program + 1);
3525 prog->offs[0].end = result;
3528 if (reginfo->cutpoint)
3529 *startposp= reginfo->cutpoint;
3530 REGCP_UNWIND(lastcp);
3535 #define sayYES goto yes
3536 #define sayNO goto no
3537 #define sayNO_SILENT goto no_silent
3539 /* we dont use STMT_START/END here because it leads to
3540 "unreachable code" warnings, which are bogus, but distracting. */
3541 #define CACHEsayNO \
3542 if (ST.cache_mask) \
3543 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3546 /* this is used to determine how far from the left messages like
3547 'failed...' are printed. It should be set such that messages
3548 are inline with the regop output that created them.
3550 #define REPORT_CODE_OFF 32
3553 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3554 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3555 #define CHRTEST_NOT_A_CP_1 -999
3556 #define CHRTEST_NOT_A_CP_2 -998
3558 /* grab a new slab and return the first slot in it */
3560 STATIC regmatch_state *
3563 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3566 regmatch_slab *s = PL_regmatch_slab->next;
3568 Newx(s, 1, regmatch_slab);
3569 s->prev = PL_regmatch_slab;
3571 PL_regmatch_slab->next = s;
3573 PL_regmatch_slab = s;
3574 return SLAB_FIRST(s);
3578 /* push a new state then goto it */
3580 #define PUSH_STATE_GOTO(state, node, input) \
3581 pushinput = input; \
3583 st->resume_state = state; \
3586 /* push a new state with success backtracking, then goto it */
3588 #define PUSH_YES_STATE_GOTO(state, node, input) \
3589 pushinput = input; \
3591 st->resume_state = state; \
3592 goto push_yes_state;
3599 regmatch() - main matching routine
3601 This is basically one big switch statement in a loop. We execute an op,
3602 set 'next' to point the next op, and continue. If we come to a point which
3603 we may need to backtrack to on failure such as (A|B|C), we push a
3604 backtrack state onto the backtrack stack. On failure, we pop the top
3605 state, and re-enter the loop at the state indicated. If there are no more
3606 states to pop, we return failure.
3608 Sometimes we also need to backtrack on success; for example /A+/, where
3609 after successfully matching one A, we need to go back and try to
3610 match another one; similarly for lookahead assertions: if the assertion
3611 completes successfully, we backtrack to the state just before the assertion
3612 and then carry on. In these cases, the pushed state is marked as
3613 'backtrack on success too'. This marking is in fact done by a chain of
3614 pointers, each pointing to the previous 'yes' state. On success, we pop to
3615 the nearest yes state, discarding any intermediate failure-only states.
3616 Sometimes a yes state is pushed just to force some cleanup code to be
3617 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3618 it to free the inner regex.
3620 Note that failure backtracking rewinds the cursor position, while
3621 success backtracking leaves it alone.
3623 A pattern is complete when the END op is executed, while a subpattern
3624 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3625 ops trigger the "pop to last yes state if any, otherwise return true"
3628 A common convention in this function is to use A and B to refer to the two
3629 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3630 the subpattern to be matched possibly multiple times, while B is the entire
3631 rest of the pattern. Variable and state names reflect this convention.
3633 The states in the main switch are the union of ops and failure/success of
3634 substates associated with with that op. For example, IFMATCH is the op
3635 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3636 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3637 successfully matched A and IFMATCH_A_fail is a state saying that we have
3638 just failed to match A. Resume states always come in pairs. The backtrack
3639 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3640 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3641 on success or failure.
3643 The struct that holds a backtracking state is actually a big union, with
3644 one variant for each major type of op. The variable st points to the
3645 top-most backtrack struct. To make the code clearer, within each
3646 block of code we #define ST to alias the relevant union.
3648 Here's a concrete example of a (vastly oversimplified) IFMATCH
3654 #define ST st->u.ifmatch
3656 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3657 ST.foo = ...; // some state we wish to save
3659 // push a yes backtrack state with a resume value of
3660 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3662 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3665 case IFMATCH_A: // we have successfully executed A; now continue with B
3667 bar = ST.foo; // do something with the preserved value
3670 case IFMATCH_A_fail: // A failed, so the assertion failed
3671 ...; // do some housekeeping, then ...
3672 sayNO; // propagate the failure
3679 For any old-timers reading this who are familiar with the old recursive
3680 approach, the code above is equivalent to:
3682 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3691 ...; // do some housekeeping, then ...
3692 sayNO; // propagate the failure
3695 The topmost backtrack state, pointed to by st, is usually free. If you
3696 want to claim it, populate any ST.foo fields in it with values you wish to
3697 save, then do one of
3699 PUSH_STATE_GOTO(resume_state, node, newinput);
3700 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3702 which sets that backtrack state's resume value to 'resume_state', pushes a
3703 new free entry to the top of the backtrack stack, then goes to 'node'.
3704 On backtracking, the free slot is popped, and the saved state becomes the
3705 new free state. An ST.foo field in this new top state can be temporarily
3706 accessed to retrieve values, but once the main loop is re-entered, it
3707 becomes available for reuse.
3709 Note that the depth of the backtrack stack constantly increases during the
3710 left-to-right execution of the pattern, rather than going up and down with
3711 the pattern nesting. For example the stack is at its maximum at Z at the
3712 end of the pattern, rather than at X in the following:
3714 /(((X)+)+)+....(Y)+....Z/
3716 The only exceptions to this are lookahead/behind assertions and the cut,
3717 (?>A), which pop all the backtrack states associated with A before
3720 Backtrack state structs are allocated in slabs of about 4K in size.
3721 PL_regmatch_state and st always point to the currently active state,
3722 and PL_regmatch_slab points to the slab currently containing
3723 PL_regmatch_state. The first time regmatch() is called, the first slab is
3724 allocated, and is never freed until interpreter destruction. When the slab
3725 is full, a new one is allocated and chained to the end. At exit from
3726 regmatch(), slabs allocated since entry are freed.
3731 #define DEBUG_STATE_pp(pp) \
3733 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3734 PerlIO_printf(Perl_debug_log, \
3735 " %*s"pp" %s%s%s%s%s\n", \
3737 PL_reg_name[st->resume_state], \
3738 ((st==yes_state||st==mark_state) ? "[" : ""), \
3739 ((st==yes_state) ? "Y" : ""), \
3740 ((st==mark_state) ? "M" : ""), \
3741 ((st==yes_state||st==mark_state) ? "]" : "") \
3746 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3751 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3752 const char *start, const char *end, const char *blurb)
3754 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3756 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3761 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3762 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3764 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3765 start, end - start, 60);
3767 PerlIO_printf(Perl_debug_log,
3768 "%s%s REx%s %s against %s\n",
3769 PL_colors[4], blurb, PL_colors[5], s0, s1);
3771 if (utf8_target||utf8_pat)
3772 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3773 utf8_pat ? "pattern" : "",
3774 utf8_pat && utf8_target ? " and " : "",
3775 utf8_target ? "string" : ""
3781 S_dump_exec_pos(pTHX_ const char *locinput,
3782 const regnode *scan,
3783 const char *loc_regeol,
3784 const char *loc_bostr,
3785 const char *loc_reg_starttry,
3786 const bool utf8_target)
3788 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3789 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3790 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3791 /* The part of the string before starttry has one color
3792 (pref0_len chars), between starttry and current
3793 position another one (pref_len - pref0_len chars),
3794 after the current position the third one.
3795 We assume that pref0_len <= pref_len, otherwise we
3796 decrease pref0_len. */
3797 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3798 ? (5 + taill) - l : locinput - loc_bostr;
3801 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3803 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3805 pref0_len = pref_len - (locinput - loc_reg_starttry);
3806 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3807 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3808 ? (5 + taill) - pref_len : loc_regeol - locinput);
3809 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3813 if (pref0_len > pref_len)
3814 pref0_len = pref_len;
3816 const int is_uni = utf8_target ? 1 : 0;
3818 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3819 (locinput - pref_len),pref0_len, 60, 4, 5);
3821 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3822 (locinput - pref_len + pref0_len),
3823 pref_len - pref0_len, 60, 2, 3);
3825 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3826 locinput, loc_regeol - locinput, 10, 0, 1);
3828 const STRLEN tlen=len0+len1+len2;
3829 PerlIO_printf(Perl_debug_log,
3830 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3831 (IV)(locinput - loc_bostr),
3834 (docolor ? "" : "> <"),
3836 (int)(tlen > 19 ? 0 : 19 - tlen),
3843 /* reg_check_named_buff_matched()
3844 * Checks to see if a named buffer has matched. The data array of
3845 * buffer numbers corresponding to the buffer is expected to reside
3846 * in the regexp->data->data array in the slot stored in the ARG() of
3847 * node involved. Note that this routine doesn't actually care about the
3848 * name, that information is not preserved from compilation to execution.
3849 * Returns the index of the leftmost defined buffer with the given name
3850 * or 0 if non of the buffers matched.
3853 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3856 RXi_GET_DECL(rex,rexi);
3857 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3858 I32 *nums=(I32*)SvPVX(sv_dat);
3860 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3862 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3863 if ((I32)rex->lastparen >= nums[n] &&
3864 rex->offs[nums[n]].end != -1)
3874 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3875 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3877 /* This function determines if there are one or two characters that match
3878 * the first character of the passed-in EXACTish node <text_node>, and if
3879 * so, returns them in the passed-in pointers.
3881 * If it determines that no possible character in the target string can
3882 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3883 * the first character in <text_node> requires UTF-8 to represent, and the
3884 * target string isn't in UTF-8.)
3886 * If there are more than two characters that could match the beginning of
3887 * <text_node>, or if more context is required to determine a match or not,
3888 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3890 * The motiviation behind this function is to allow the caller to set up
3891 * tight loops for matching. If <text_node> is of type EXACT, there is
3892 * only one possible character that can match its first character, and so
3893 * the situation is quite simple. But things get much more complicated if
3894 * folding is involved. It may be that the first character of an EXACTFish
3895 * node doesn't participate in any possible fold, e.g., punctuation, so it
3896 * can be matched only by itself. The vast majority of characters that are
3897 * in folds match just two things, their lower and upper-case equivalents.
3898 * But not all are like that; some have multiple possible matches, or match
3899 * sequences of more than one character. This function sorts all that out.
3901 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3902 * loop of trying to match A*, we know we can't exit where the thing
3903 * following it isn't a B. And something can't be a B unless it is the
3904 * beginning of B. By putting a quick test for that beginning in a tight
3905 * loop, we can rule out things that can't possibly be B without having to
3906 * break out of the loop, thus avoiding work. Similarly, if A is a single
3907 * character, we can make a tight loop matching A*, using the outputs of
3910 * If the target string to match isn't in UTF-8, and there aren't
3911 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3912 * the one or two possible octets (which are characters in this situation)
3913 * that can match. In all cases, if there is only one character that can
3914 * match, *<c1p> and *<c2p> will be identical.
3916 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3917 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3918 * can match the beginning of <text_node>. They should be declared with at
3919 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3920 * undefined what these contain.) If one or both of the buffers are
3921 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3922 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3923 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3924 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3925 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3927 const bool utf8_target = reginfo->is_utf8_target;
3929 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
3930 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
3931 bool use_chrtest_void = FALSE;
3932 const bool is_utf8_pat = reginfo->is_utf8_pat;
3934 /* Used when we have both utf8 input and utf8 output, to avoid converting
3935 * to/from code points */
3936 bool utf8_has_been_setup = FALSE;
3940 U8 *pat = (U8*)STRING(text_node);
3941 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3943 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
3945 /* In an exact node, only one thing can be matched, that first
3946 * character. If both the pat and the target are UTF-8, we can just
3947 * copy the input to the output, avoiding finding the code point of
3952 else if (utf8_target) {
3953 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3954 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3955 utf8_has_been_setup = TRUE;
3958 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3961 else { /* an EXACTFish node */
3962 U8 *pat_end = pat + STR_LEN(text_node);
3964 /* An EXACTFL node has at least some characters unfolded, because what
3965 * they match is not known until now. So, now is the time to fold
3966 * the first few of them, as many as are needed to determine 'c1' and
3967 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3968 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3969 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3970 * need to fold as many characters as a single character can fold to,
3971 * so that later we can check if the first ones are such a multi-char
3972 * fold. But, in such a pattern only locale-problematic characters
3973 * aren't folded, so we can skip this completely if the first character
3974 * in the node isn't one of the tricky ones */
3975 if (OP(text_node) == EXACTFL) {
3977 if (! is_utf8_pat) {
3978 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3980 folded[0] = folded[1] = 's';
3982 pat_end = folded + 2;
3985 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3990 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3992 *(d++) = (U8) toFOLD_LC(*s);
3997 _to_utf8_fold_flags(s,
4000 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4011 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4012 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4014 /* Multi-character folds require more context to sort out. Also
4015 * PL_utf8_foldclosures used below doesn't handle them, so have to
4016 * be handled outside this routine */
4017 use_chrtest_void = TRUE;
4019 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4020 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4022 /* Load the folds hash, if not already done */
4024 if (! PL_utf8_foldclosures) {
4025 _load_PL_utf8_foldclosures();
4028 /* The fold closures data structure is a hash with the keys
4029 * being the UTF-8 of every character that is folded to, like
4030 * 'k', and the values each an array of all code points that
4031 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4032 * Multi-character folds are not included */
4033 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4038 /* Not found in the hash, therefore there are no folds
4039 * containing it, so there is only a single character that
4043 else { /* Does participate in folds */
4044 AV* list = (AV*) *listp;
4045 if (av_tindex(list) != 1) {
4047 /* If there aren't exactly two folds to this, it is
4048 * outside the scope of this function */
4049 use_chrtest_void = TRUE;
4051 else { /* There are two. Get them */
4052 SV** c_p = av_fetch(list, 0, FALSE);
4054 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4058 c_p = av_fetch(list, 1, FALSE);
4060 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4064 /* Folds that cross the 255/256 boundary are forbidden
4065 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4066 * one is ASCIII. Since the pattern character is above
4067 * 255, and its only other match is below 256, the only
4068 * legal match will be to itself. We have thrown away
4069 * the original, so have to compute which is the one
4071 if ((c1 < 256) != (c2 < 256)) {
4072 if ((OP(text_node) == EXACTFL
4073 && ! IN_UTF8_CTYPE_LOCALE)
4074 || ((OP(text_node) == EXACTFA
4075 || OP(text_node) == EXACTFA_NO_TRIE)
4076 && (isASCII(c1) || isASCII(c2))))
4089 else /* Here, c1 is <= 255 */
4091 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4092 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4093 && ((OP(text_node) != EXACTFA
4094 && OP(text_node) != EXACTFA_NO_TRIE)
4097 /* Here, there could be something above Latin1 in the target
4098 * which folds to this character in the pattern. All such
4099 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4100 * than two characters involved in their folds, so are outside
4101 * the scope of this function */
4102 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4103 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4106 use_chrtest_void = TRUE;
4109 else { /* Here nothing above Latin1 can fold to the pattern
4111 switch (OP(text_node)) {
4113 case EXACTFL: /* /l rules */
4114 c2 = PL_fold_locale[c1];
4117 case EXACTF: /* This node only generated for non-utf8
4119 assert(! is_utf8_pat);
4120 if (! utf8_target) { /* /d rules */
4125 /* /u rules for all these. This happens to work for
4126 * EXACTFA as nothing in Latin1 folds to ASCII */
4127 case EXACTFA_NO_TRIE: /* This node only generated for
4128 non-utf8 patterns */
4129 assert(! is_utf8_pat);
4134 c2 = PL_fold_latin1[c1];
4138 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4139 NOT_REACHED; /* NOTREACHED */
4145 /* Here have figured things out. Set up the returns */
4146 if (use_chrtest_void) {
4147 *c2p = *c1p = CHRTEST_VOID;
4149 else if (utf8_target) {
4150 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4151 uvchr_to_utf8(c1_utf8, c1);
4152 uvchr_to_utf8(c2_utf8, c2);
4155 /* Invariants are stored in both the utf8 and byte outputs; Use
4156 * negative numbers otherwise for the byte ones. Make sure that the
4157 * byte ones are the same iff the utf8 ones are the same */
4158 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4159 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4162 ? CHRTEST_NOT_A_CP_1
4163 : CHRTEST_NOT_A_CP_2;
4165 else if (c1 > 255) {
4166 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4171 *c1p = *c2p = c2; /* c2 is the only representable value */
4173 else { /* c1 is representable; see about c2 */
4175 *c2p = (c2 < 256) ? c2 : c1;
4181 /* This creates a single number by combining two, with 'before' being like the
4182 * 10's digit, but this isn't necessarily base 10; it is base however many
4183 * elements of the enum there are */
4184 #define GCBcase(before, after) ((GCB_ENUM_COUNT * before) + after)
4187 S_isGCB(const GCB_enum before, const GCB_enum after)
4189 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4190 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4192 switch (GCBcase(before, after)) {
4194 /* Break at the start and end of text.
4198 Break before and after controls except between CR and LF
4199 GB4. ( Control | CR | LF ) ÷
4200 GB5. ÷ ( Control | CR | LF )
4202 Otherwise, break everywhere.
4207 /* Do not break between a CR and LF.
4209 case GCBcase(GCB_CR, GCB_LF):
4212 /* Do not break Hangul syllable sequences.
4213 GB6. L × ( L | V | LV | LVT ) */
4214 case GCBcase(GCB_L, GCB_L):
4215 case GCBcase(GCB_L, GCB_V):
4216 case GCBcase(GCB_L, GCB_LV):
4217 case GCBcase(GCB_L, GCB_LVT):
4220 /* GB7. ( LV | V ) × ( V | T ) */
4221 case GCBcase(GCB_LV, GCB_V):
4222 case GCBcase(GCB_LV, GCB_T):
4223 case GCBcase(GCB_V, GCB_V):
4224 case GCBcase(GCB_V, GCB_T):
4227 /* GB8. ( LVT | T) × T */
4228 case GCBcase(GCB_LVT, GCB_T):
4229 case GCBcase(GCB_T, GCB_T):
4232 /* Do not break between regional indicator symbols.
4233 GB8a. Regional_Indicator × Regional_Indicator */
4234 case GCBcase(GCB_Regional_Indicator, GCB_Regional_Indicator):
4237 /* Do not break before extending characters.
4239 case GCBcase(GCB_Other, GCB_Extend):
4240 case GCBcase(GCB_Extend, GCB_Extend):
4241 case GCBcase(GCB_L, GCB_Extend):
4242 case GCBcase(GCB_LV, GCB_Extend):
4243 case GCBcase(GCB_LVT, GCB_Extend):
4244 case GCBcase(GCB_Prepend, GCB_Extend):
4245 case GCBcase(GCB_Regional_Indicator, GCB_Extend):
4246 case GCBcase(GCB_SpacingMark, GCB_Extend):
4247 case GCBcase(GCB_T, GCB_Extend):
4248 case GCBcase(GCB_V, GCB_Extend):
4251 /* Do not break before SpacingMarks, or after Prepend characters.
4252 GB9a. × SpacingMark */
4253 case GCBcase(GCB_Other, GCB_SpacingMark):
4254 case GCBcase(GCB_Extend, GCB_SpacingMark):
4255 case GCBcase(GCB_L, GCB_SpacingMark):
4256 case GCBcase(GCB_LV, GCB_SpacingMark):
4257 case GCBcase(GCB_LVT, GCB_SpacingMark):
4258 case GCBcase(GCB_Prepend, GCB_SpacingMark):
4259 case GCBcase(GCB_Regional_Indicator, GCB_SpacingMark):
4260 case GCBcase(GCB_SpacingMark, GCB_SpacingMark):
4261 case GCBcase(GCB_T, GCB_SpacingMark):
4262 case GCBcase(GCB_V, GCB_SpacingMark):
4265 /* GB9b. Prepend × */
4266 case GCBcase(GCB_Prepend, GCB_Other):
4267 case GCBcase(GCB_Prepend, GCB_L):
4268 case GCBcase(GCB_Prepend, GCB_LV):
4269 case GCBcase(GCB_Prepend, GCB_LVT):
4270 case GCBcase(GCB_Prepend, GCB_Prepend):
4271 case GCBcase(GCB_Prepend, GCB_Regional_Indicator):
4272 case GCBcase(GCB_Prepend, GCB_T):
4273 case GCBcase(GCB_Prepend, GCB_V):
4277 NOT_REACHED; /* NOTREACHED */
4280 #define SBcase(before, after) ((SB_ENUM_COUNT * before) + after)
4283 S_isSB(pTHX_ SB_enum before,
4285 const U8 * const strbeg,
4286 const U8 * const curpos,
4287 const U8 * const strend,
4288 const bool utf8_target)
4290 /* returns a boolean indicating if there is a Sentence Boundary Break
4291 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4293 U8 * lpos = (U8 *) curpos;
4297 PERL_ARGS_ASSERT_ISSB;
4299 /* Break at the start and end of text.
4302 if (before == SB_EDGE || after == SB_EDGE) {
4306 /* SB 3: Do not break within CRLF. */
4307 if (before == SB_CR && after == SB_LF) {
4311 /* Break after paragraph separators. (though why CR and LF are considered
4312 * so is beyond me (khw)
4313 SB4. Sep | CR | LF ÷ */
4314 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4318 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4319 * (See Section 6.2, Replacing Ignore Rules.)
4320 SB5. X (Extend | Format)* → X */
4321 if (after == SB_Extend || after == SB_Format) {
4325 if (before == SB_Extend || before == SB_Format) {
4326 before = backup_one_SB(strbeg, &lpos, utf8_target);
4329 /* Do not break after ambiguous terminators like period, if they are
4330 * immediately followed by a number or lowercase letter, if they are
4331 * between uppercase letters, if the first following letter (optionally
4332 * after certain punctuation) is lowercase, or if they are followed by
4333 * "continuation" punctuation such as comma, colon, or semicolon. For
4334 * example, a period may be an abbreviation or numeric period, and thus may
4335 * not mark the end of a sentence.
4337 * SB6. ATerm × Numeric */
4338 if (before == SB_ATerm && after == SB_Numeric) {
4342 /* SB7. (Upper | Lower) ATerm × Upper */
4343 if (before == SB_ATerm && after == SB_Upper) {
4345 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4346 if (backup == SB_Upper || backup == SB_Lower) {
4351 /* SB8a. (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4352 * SB10. (STerm | ATerm) Close* Sp* × ( Sp | Sep | CR | LF ) */
4355 while (backup == SB_Sp) {
4356 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4358 while (backup == SB_Close) {
4359 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4361 if ((backup == SB_STerm || backup == SB_ATerm)
4362 && ( after == SB_SContinue
4363 || after == SB_STerm
4364 || after == SB_ATerm
4373 /* SB8. ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR | LF |
4374 * STerm | ATerm) )* Lower */
4375 if (backup == SB_ATerm) {
4376 U8 * rpos = (U8 *) curpos;
4377 SB_enum later = after;
4379 while ( later != SB_OLetter
4380 && later != SB_Upper
4381 && later != SB_Lower
4385 && later != SB_STerm
4386 && later != SB_ATerm
4387 && later != SB_EDGE)
4389 later = advance_one_SB(&rpos, strend, utf8_target);
4391 if (later == SB_Lower) {
4396 /* Break after sentence terminators, but include closing punctuation,
4397 * trailing spaces, and a paragraph separator (if present). [See note
4399 * SB9. ( STerm | ATerm ) Close* × ( Close | Sp | Sep | CR | LF ) */
4402 while (backup == SB_Close) {
4403 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4405 if ((backup == SB_STerm || backup == SB_ATerm)
4406 && ( after == SB_Close
4416 /* SB11. ( STerm | ATerm ) Close* Sp* ( Sep | CR | LF )? ÷ */
4418 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4419 if ( backup == SB_Sep
4428 while (backup == SB_Sp) {
4429 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4431 while (backup == SB_Close) {
4432 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4434 if (backup == SB_STerm || backup == SB_ATerm) {
4438 /* Otherwise, do not break.
4445 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4449 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4451 if (*curpos >= strend) {
4457 *curpos += UTF8SKIP(*curpos);
4458 if (*curpos >= strend) {
4461 sb = getSB_VAL_UTF8(*curpos, strend);
4462 } while (sb == SB_Extend || sb == SB_Format);
4467 if (*curpos >= strend) {
4470 sb = getSB_VAL_CP(**curpos);
4471 } while (sb == SB_Extend || sb == SB_Format);
4478 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4482 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4484 if (*curpos < strbeg) {
4489 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4490 if (! prev_char_pos) {
4494 /* Back up over Extend and Format. curpos is always just to the right
4495 * of the characater whose value we are getting */
4497 U8 * prev_prev_char_pos;
4498 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4501 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4502 *curpos = prev_char_pos;
4503 prev_char_pos = prev_prev_char_pos;
4506 *curpos = (U8 *) strbeg;
4509 } while (sb == SB_Extend || sb == SB_Format);
4513 if (*curpos - 2 < strbeg) {
4514 *curpos = (U8 *) strbeg;
4518 sb = getSB_VAL_CP(*(*curpos - 1));
4519 } while (sb == SB_Extend || sb == SB_Format);
4525 #define WBcase(before, after) ((WB_ENUM_COUNT * before) + after)
4528 S_isWB(pTHX_ WB_enum previous,
4531 const U8 * const strbeg,
4532 const U8 * const curpos,
4533 const U8 * const strend,
4534 const bool utf8_target)
4536 /* Return a boolean as to if the boundary between 'before' and 'after' is
4537 * a Unicode word break, using their published algorithm, but tailored for
4538 * Perl by treating spans of white space as one unit. Context may be
4539 * needed to make this determination. If the value for the character
4540 * before 'before' is known, it is passed as 'previous'; otherwise that
4541 * should be set to WB_UNKNOWN. The other input parameters give the
4542 * boundaries and current position in the matching of the string. That
4543 * is, 'curpos' marks the position where the character whose wb value is
4544 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
4546 U8 * before_pos = (U8 *) curpos;
4547 U8 * after_pos = (U8 *) curpos;
4549 PERL_ARGS_ASSERT_ISWB;
4551 /* WB1 and WB2: Break at the start and end of text. */
4552 if (before == WB_EDGE || after == WB_EDGE) {
4556 /* WB 3 is: "Do not break within CRLF." Perl extends this so that all
4557 * white space sequences ending in a vertical space are treated as one
4560 if (after == WB_CR || after == WB_LF || after == WB_Newline) {
4561 if (before == WB_CR || before == WB_LF || before == WB_Newline
4562 || before == WB_Perl_Tailored_HSpace)
4567 /* WB 3a: Otherwise break before Newlines (including CR and LF) */
4571 /* Here, we know that 'after' is not a vertical space character, but
4572 * 'before' could be. WB 3b is: "Otherwise break after Newlines (including
4573 * CR and LF)." Perl changes that to not break-up spans of white space,
4574 * except when horizontal space is followed by an Extend or Format
4575 * character. These apply just to the final white space character in the
4576 * span, so it is broken away from the rest. (If the Extend or Format
4577 * character follows a vertical space character, it is treated as beginning
4578 * a line, and doesn't modify the preceeding character.) */
4579 if ( before == WB_CR || before == WB_LF || before == WB_Newline
4580 || before == WB_Perl_Tailored_HSpace)
4582 if (after == WB_Perl_Tailored_HSpace) {
4583 U8 * temp_pos = (U8 *) curpos;
4585 = advance_one_WB(&temp_pos, strend, utf8_target,
4586 FALSE /* Don't skip Extend nor Format */ );
4587 return next == WB_Extend || next == WB_Format;
4589 else if (before != WB_Perl_Tailored_HSpace) {
4591 /* Here, 'before' must be one of the vertical space characters, and
4592 * after is not any type of white-space. Follow WB 3b. */
4596 /* Here, 'before' is horizontal space, and 'after' is not any kind of
4597 * space. Normal rules apply */
4600 /* Ignore Format and Extend characters, except when they appear at the
4601 * beginning of a region of text.
4602 * WB4. X (Extend | Format)* → X. */
4604 if (after == WB_Extend || after == WB_Format) {
4608 if (before == WB_Extend || before == WB_Format) {
4609 before = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4612 switch (WBcase(before, after)) {
4613 /* Otherwise, break everywhere (including around ideographs).
4618 /* Do not break between most letters.
4619 WB5. (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) */
4620 case WBcase(WB_ALetter, WB_ALetter):
4621 case WBcase(WB_ALetter, WB_Hebrew_Letter):
4622 case WBcase(WB_Hebrew_Letter, WB_ALetter):
4623 case WBcase(WB_Hebrew_Letter, WB_Hebrew_Letter):
4626 /* Do not break letters across certain punctuation.
4627 WB6. (ALetter | Hebrew_Letter)
4628 × (MidLetter | MidNumLet | Single_Quote) (ALetter
4630 case WBcase(WB_ALetter, WB_MidLetter):
4631 case WBcase(WB_ALetter, WB_MidNumLet):
4632 case WBcase(WB_ALetter, WB_Single_Quote):
4633 case WBcase(WB_Hebrew_Letter, WB_MidLetter):
4634 case WBcase(WB_Hebrew_Letter, WB_MidNumLet):
4635 /*case WBcase(WB_Hebrew_Letter, WB_Single_Quote):*/
4636 after = advance_one_WB(&after_pos, strend, utf8_target,
4637 TRUE /* Do skip Extend and Format */ );
4638 return after != WB_ALetter && after != WB_Hebrew_Letter;
4640 /* WB7. (ALetter | Hebrew_Letter) (MidLetter | MidNumLet |
4641 * Single_Quote) × (ALetter | Hebrew_Letter) */
4642 case WBcase(WB_MidLetter, WB_ALetter):
4643 case WBcase(WB_MidLetter, WB_Hebrew_Letter):
4644 case WBcase(WB_MidNumLet, WB_ALetter):
4645 case WBcase(WB_MidNumLet, WB_Hebrew_Letter):
4646 case WBcase(WB_Single_Quote, WB_ALetter):
4647 case WBcase(WB_Single_Quote, WB_Hebrew_Letter):
4649 = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4650 return before != WB_ALetter && before != WB_Hebrew_Letter;
4652 /* WB7a. Hebrew_Letter × Single_Quote */
4653 case WBcase(WB_Hebrew_Letter, WB_Single_Quote):
4656 /* WB7b. Hebrew_Letter × Double_Quote Hebrew_Letter */
4657 case WBcase(WB_Hebrew_Letter, WB_Double_Quote):
4658 return advance_one_WB(&after_pos, strend, utf8_target,
4659 TRUE /* Do skip Extend and Format */ )
4660 != WB_Hebrew_Letter;
4662 /* WB7c. Hebrew_Letter Double_Quote × Hebrew_Letter */
4663 case WBcase(WB_Double_Quote, WB_Hebrew_Letter):
4664 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4665 != WB_Hebrew_Letter;
4667 /* Do not break within sequences of digits, or digits adjacent to
4668 * letters (“3a”, or “A3”).
4669 WB8. Numeric × Numeric */
4670 case WBcase(WB_Numeric, WB_Numeric):
4673 /* WB9. (ALetter | Hebrew_Letter) × Numeric */
4674 case WBcase(WB_ALetter, WB_Numeric):
4675 case WBcase(WB_Hebrew_Letter, WB_Numeric):
4678 /* WB10. Numeric × (ALetter | Hebrew_Letter) */
4679 case WBcase(WB_Numeric, WB_ALetter):
4680 case WBcase(WB_Numeric, WB_Hebrew_Letter):
4683 /* Do not break within sequences, such as “3.2” or “3,456.789”.
4684 WB11. Numeric (MidNum | MidNumLet | Single_Quote) × Numeric
4686 case WBcase(WB_MidNum, WB_Numeric):
4687 case WBcase(WB_MidNumLet, WB_Numeric):
4688 case WBcase(WB_Single_Quote, WB_Numeric):
4689 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4692 /* WB12. Numeric × (MidNum | MidNumLet | Single_Quote) Numeric
4694 case WBcase(WB_Numeric, WB_MidNum):
4695 case WBcase(WB_Numeric, WB_MidNumLet):
4696 case WBcase(WB_Numeric, WB_Single_Quote):
4697 return advance_one_WB(&after_pos, strend, utf8_target,
4698 TRUE /* Do skip Extend and Format */ )
4701 /* Do not break between Katakana.
4702 WB13. Katakana × Katakana */
4703 case WBcase(WB_Katakana, WB_Katakana):
4706 /* Do not break from extenders.
4707 WB13a. (ALetter | Hebrew_Letter | Numeric | Katakana |
4708 ExtendNumLet) × ExtendNumLet */
4709 case WBcase(WB_ALetter, WB_ExtendNumLet):
4710 case WBcase(WB_Hebrew_Letter, WB_ExtendNumLet):
4711 case WBcase(WB_Numeric, WB_ExtendNumLet):
4712 case WBcase(WB_Katakana, WB_ExtendNumLet):
4713 case WBcase(WB_ExtendNumLet, WB_ExtendNumLet):
4716 /* WB13b. ExtendNumLet × (ALetter | Hebrew_Letter | Numeric
4718 case WBcase(WB_ExtendNumLet, WB_ALetter):
4719 case WBcase(WB_ExtendNumLet, WB_Hebrew_Letter):
4720 case WBcase(WB_ExtendNumLet, WB_Numeric):
4721 case WBcase(WB_ExtendNumLet, WB_Katakana):
4724 /* Do not break between regional indicator symbols.
4725 WB13c. Regional_Indicator × Regional_Indicator */
4726 case WBcase(WB_Regional_Indicator, WB_Regional_Indicator):
4731 NOT_REACHED; /* NOTREACHED */
4735 S_advance_one_WB(pTHX_ U8 ** curpos,
4736 const U8 * const strend,
4737 const bool utf8_target,
4738 const bool skip_Extend_Format)
4742 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
4744 if (*curpos >= strend) {
4750 /* Advance over Extend and Format */
4752 *curpos += UTF8SKIP(*curpos);
4753 if (*curpos >= strend) {
4756 wb = getWB_VAL_UTF8(*curpos, strend);
4757 } while ( skip_Extend_Format
4758 && (wb == WB_Extend || wb == WB_Format));
4763 if (*curpos >= strend) {
4766 wb = getWB_VAL_CP(**curpos);
4767 } while ( skip_Extend_Format
4768 && (wb == WB_Extend || wb == WB_Format));
4775 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4779 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
4781 /* If we know what the previous character's break value is, don't have
4783 if (*previous != WB_UNKNOWN) {
4786 /* But we need to move backwards by one */
4788 *curpos = reghopmaybe3(*curpos, -1, strbeg);
4790 *previous = WB_EDGE;
4791 *curpos = (U8 *) strbeg;
4794 *previous = WB_UNKNOWN;
4799 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
4802 /* And we always back up over these two types */
4803 if (wb != WB_Extend && wb != WB_Format) {
4808 if (*curpos < strbeg) {
4813 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4814 if (! prev_char_pos) {
4818 /* Back up over Extend and Format. curpos is always just to the right
4819 * of the characater whose value we are getting */
4821 U8 * prev_prev_char_pos;
4822 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
4826 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4827 *curpos = prev_char_pos;
4828 prev_char_pos = prev_prev_char_pos;
4831 *curpos = (U8 *) strbeg;
4834 } while (wb == WB_Extend || wb == WB_Format);
4838 if (*curpos - 2 < strbeg) {
4839 *curpos = (U8 *) strbeg;
4843 wb = getWB_VAL_CP(*(*curpos - 1));
4844 } while (wb == WB_Extend || wb == WB_Format);
4850 /* returns -1 on failure, $+[0] on success */
4852 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
4854 #if PERL_VERSION < 9 && !defined(PERL_CORE)
4858 const bool utf8_target = reginfo->is_utf8_target;
4859 const U32 uniflags = UTF8_ALLOW_DEFAULT;
4860 REGEXP *rex_sv = reginfo->prog;
4861 regexp *rex = ReANY(rex_sv);
4862 RXi_GET_DECL(rex,rexi);
4863 /* the current state. This is a cached copy of PL_regmatch_state */
4865 /* cache heavy used fields of st in registers */
4868 U32 n = 0; /* general value; init to avoid compiler warning */
4869 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
4870 char *locinput = startpos;
4871 char *pushinput; /* where to continue after a PUSH */
4872 I32 nextchr; /* is always set to UCHARAT(locinput) */
4874 bool result = 0; /* return value of S_regmatch */
4875 int depth = 0; /* depth of backtrack stack */
4876 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
4877 const U32 max_nochange_depth =
4878 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
4879 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
4880 regmatch_state *yes_state = NULL; /* state to pop to on success of
4882 /* mark_state piggy backs on the yes_state logic so that when we unwind
4883 the stack on success we can update the mark_state as we go */
4884 regmatch_state *mark_state = NULL; /* last mark state we have seen */
4885 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
4886 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
4888 bool no_final = 0; /* prevent failure from backtracking? */
4889 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
4890 char *startpoint = locinput;
4891 SV *popmark = NULL; /* are we looking for a mark? */
4892 SV *sv_commit = NULL; /* last mark name seen in failure */
4893 SV *sv_yes_mark = NULL; /* last mark name we have seen
4894 during a successful match */
4895 U32 lastopen = 0; /* last open we saw */
4896 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
4897 SV* const oreplsv = GvSVn(PL_replgv);
4898 /* these three flags are set by various ops to signal information to
4899 * the very next op. They have a useful lifetime of exactly one loop
4900 * iteration, and are not preserved or restored by state pushes/pops
4902 bool sw = 0; /* the condition value in (?(cond)a|b) */
4903 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
4904 int logical = 0; /* the following EVAL is:
4908 or the following IFMATCH/UNLESSM is:
4909 false: plain (?=foo)
4910 true: used as a condition: (?(?=foo))
4912 PAD* last_pad = NULL;
4914 I32 gimme = G_SCALAR;
4915 CV *caller_cv = NULL; /* who called us */
4916 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
4917 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
4918 U32 maxopenparen = 0; /* max '(' index seen so far */
4919 int to_complement; /* Invert the result? */
4920 _char_class_number classnum;
4921 bool is_utf8_pat = reginfo->is_utf8_pat;
4926 GET_RE_DEBUG_FLAGS_DECL;
4929 /* protect against undef(*^R) */
4930 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
4932 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
4933 multicall_oldcatch = 0;
4934 multicall_cv = NULL;
4936 PERL_UNUSED_VAR(multicall_cop);
4937 PERL_UNUSED_VAR(newsp);
4940 PERL_ARGS_ASSERT_REGMATCH;
4942 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
4943 PerlIO_printf(Perl_debug_log,"regmatch start\n");
4946 st = PL_regmatch_state;
4948 /* Note that nextchr is a byte even in UTF */
4951 while (scan != NULL) {
4954 SV * const prop = sv_newmortal();
4955 regnode *rnext=regnext(scan);
4956 DUMP_EXEC_POS( locinput, scan, utf8_target );
4957 regprop(rex, prop, scan, reginfo, NULL);
4959 PerlIO_printf(Perl_debug_log,
4960 "%3"IVdf":%*s%s(%"IVdf")\n",
4961 (IV)(scan - rexi->program), depth*2, "",
4963 (PL_regkind[OP(scan)] == END || !rnext) ?
4964 0 : (IV)(rnext - rexi->program));
4967 next = scan + NEXT_OFF(scan);
4970 state_num = OP(scan);
4976 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
4978 switch (state_num) {
4979 case SBOL: /* /^../ and /\A../ */
4980 if (locinput == reginfo->strbeg)
4984 case MBOL: /* /^../m */
4985 if (locinput == reginfo->strbeg ||
4986 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4993 if (locinput == reginfo->ganch)
4997 case KEEPS: /* \K */
4998 /* update the startpoint */
4999 st->u.keeper.val = rex->offs[0].start;
5000 rex->offs[0].start = locinput - reginfo->strbeg;
5001 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5003 NOT_REACHED; /* NOTREACHED */
5005 case KEEPS_next_fail:
5006 /* rollback the start point change */
5007 rex->offs[0].start = st->u.keeper.val;
5010 NOT_REACHED; /* NOTREACHED */
5012 case MEOL: /* /..$/m */
5013 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5017 case SEOL: /* /..$/ */
5018 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5020 if (reginfo->strend - locinput > 1)
5025 if (!NEXTCHR_IS_EOS)
5029 case SANY: /* /./s */
5032 goto increment_locinput;
5034 case REG_ANY: /* /./ */
5035 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5037 goto increment_locinput;
5041 #define ST st->u.trie
5042 case TRIEC: /* (ab|cd) with known charclass */
5043 /* In this case the charclass data is available inline so
5044 we can fail fast without a lot of extra overhead.
5046 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5048 PerlIO_printf(Perl_debug_log,
5049 "%*s %sfailed to match trie start class...%s\n",
5050 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5054 NOT_REACHED; /* NOTREACHED */
5057 case TRIE: /* (ab|cd) */
5058 /* the basic plan of execution of the trie is:
5059 * At the beginning, run though all the states, and
5060 * find the longest-matching word. Also remember the position
5061 * of the shortest matching word. For example, this pattern:
5064 * when matched against the string "abcde", will generate
5065 * accept states for all words except 3, with the longest
5066 * matching word being 4, and the shortest being 2 (with
5067 * the position being after char 1 of the string).
5069 * Then for each matching word, in word order (i.e. 1,2,4,5),
5070 * we run the remainder of the pattern; on each try setting
5071 * the current position to the character following the word,
5072 * returning to try the next word on failure.
5074 * We avoid having to build a list of words at runtime by
5075 * using a compile-time structure, wordinfo[].prev, which
5076 * gives, for each word, the previous accepting word (if any).
5077 * In the case above it would contain the mappings 1->2, 2->0,
5078 * 3->0, 4->5, 5->1. We can use this table to generate, from
5079 * the longest word (4 above), a list of all words, by
5080 * following the list of prev pointers; this gives us the
5081 * unordered list 4,5,1,2. Then given the current word we have
5082 * just tried, we can go through the list and find the
5083 * next-biggest word to try (so if we just failed on word 2,
5084 * the next in the list is 4).
5086 * Since at runtime we don't record the matching position in
5087 * the string for each word, we have to work that out for
5088 * each word we're about to process. The wordinfo table holds
5089 * the character length of each word; given that we recorded
5090 * at the start: the position of the shortest word and its
5091 * length in chars, we just need to move the pointer the
5092 * difference between the two char lengths. Depending on
5093 * Unicode status and folding, that's cheap or expensive.
5095 * This algorithm is optimised for the case where are only a
5096 * small number of accept states, i.e. 0,1, or maybe 2.
5097 * With lots of accepts states, and having to try all of them,
5098 * it becomes quadratic on number of accept states to find all
5103 /* what type of TRIE am I? (utf8 makes this contextual) */
5104 DECL_TRIE_TYPE(scan);
5106 /* what trie are we using right now */
5107 reg_trie_data * const trie
5108 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5109 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5110 U32 state = trie->startstate;
5112 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5113 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5115 && UTF8_IS_ABOVE_LATIN1(nextchr)
5116 && scan->flags == EXACTL)
5118 /* We only output for EXACTL, as we let the folder
5119 * output this message for EXACTFLU8 to avoid
5121 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5126 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5128 if (trie->states[ state ].wordnum) {
5130 PerlIO_printf(Perl_debug_log,
5131 "%*s %smatched empty string...%s\n",
5132 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5138 PerlIO_printf(Perl_debug_log,
5139 "%*s %sfailed to match trie start class...%s\n",
5140 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5147 U8 *uc = ( U8* )locinput;
5151 U8 *uscan = (U8*)NULL;
5152 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5153 U32 charcount = 0; /* how many input chars we have matched */
5154 U32 accepted = 0; /* have we seen any accepting states? */
5156 ST.jump = trie->jump;
5159 ST.longfold = FALSE; /* char longer if folded => it's harder */
5162 /* fully traverse the TRIE; note the position of the
5163 shortest accept state and the wordnum of the longest
5166 while ( state && uc <= (U8*)(reginfo->strend) ) {
5167 U32 base = trie->states[ state ].trans.base;
5171 wordnum = trie->states[ state ].wordnum;
5173 if (wordnum) { /* it's an accept state */
5176 /* record first match position */
5178 ST.firstpos = (U8*)locinput;
5183 ST.firstchars = charcount;
5186 if (!ST.nextword || wordnum < ST.nextword)
5187 ST.nextword = wordnum;
5188 ST.topword = wordnum;
5191 DEBUG_TRIE_EXECUTE_r({
5192 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5193 PerlIO_printf( Perl_debug_log,
5194 "%*s %sState: %4"UVxf" Accepted: %c ",
5195 2+depth * 2, "", PL_colors[4],
5196 (UV)state, (accepted ? 'Y' : 'N'));
5199 /* read a char and goto next state */
5200 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5202 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5203 uscan, len, uvc, charid, foldlen,
5210 base + charid - 1 - trie->uniquecharcount)) >= 0)
5212 && ((U32)offset < trie->lasttrans)
5213 && trie->trans[offset].check == state)
5215 state = trie->trans[offset].next;
5226 DEBUG_TRIE_EXECUTE_r(
5227 PerlIO_printf( Perl_debug_log,
5228 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5229 charid, uvc, (UV)state, PL_colors[5] );
5235 /* calculate total number of accept states */
5240 w = trie->wordinfo[w].prev;
5243 ST.accepted = accepted;
5247 PerlIO_printf( Perl_debug_log,
5248 "%*s %sgot %"IVdf" possible matches%s\n",
5249 REPORT_CODE_OFF + depth * 2, "",
5250 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5252 goto trie_first_try; /* jump into the fail handler */
5255 NOT_REACHED; /* NOTREACHED */
5257 case TRIE_next_fail: /* we failed - try next alternative */
5261 REGCP_UNWIND(ST.cp);
5262 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5264 if (!--ST.accepted) {
5266 PerlIO_printf( Perl_debug_log,
5267 "%*s %sTRIE failed...%s\n",
5268 REPORT_CODE_OFF+depth*2, "",
5275 /* Find next-highest word to process. Note that this code
5276 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5279 U16 const nextword = ST.nextword;
5280 reg_trie_wordinfo * const wordinfo
5281 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5282 for (word=ST.topword; word; word=wordinfo[word].prev) {
5283 if (word > nextword && (!min || word < min))
5296 ST.lastparen = rex->lastparen;
5297 ST.lastcloseparen = rex->lastcloseparen;
5301 /* find start char of end of current word */
5303 U32 chars; /* how many chars to skip */
5304 reg_trie_data * const trie
5305 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5307 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5309 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5314 /* the hard option - fold each char in turn and find
5315 * its folded length (which may be different */
5316 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5324 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5332 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5337 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5353 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5354 ? ST.jump[ST.nextword]
5358 PerlIO_printf( Perl_debug_log,
5359 "%*s %sTRIE matched word #%d, continuing%s\n",
5360 REPORT_CODE_OFF+depth*2, "",
5367 if (ST.accepted > 1 || has_cutgroup) {
5368 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5370 NOT_REACHED; /* NOTREACHED */
5372 /* only one choice left - just continue */
5374 AV *const trie_words
5375 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5376 SV ** const tmp = trie_words
5377 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5378 SV *sv= tmp ? sv_newmortal() : NULL;
5380 PerlIO_printf( Perl_debug_log,
5381 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
5382 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5384 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5385 PL_colors[0], PL_colors[1],
5386 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5388 : "not compiled under -Dr",
5392 locinput = (char*)uc;
5393 continue; /* execute rest of RE */
5398 case EXACTL: /* /abc/l */
5399 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5401 /* Complete checking would involve going through every character
5402 * matched by the string to see if any is above latin1. But the
5403 * comparision otherwise might very well be a fast assembly
5404 * language routine, and I (khw) don't think slowing things down
5405 * just to check for this warning is worth it. So this just checks
5406 * the first character */
5407 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5408 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5411 case EXACT: { /* /abc/ */
5412 char *s = STRING(scan);
5414 if (utf8_target != is_utf8_pat) {
5415 /* The target and the pattern have differing utf8ness. */
5417 const char * const e = s + ln;
5420 /* The target is utf8, the pattern is not utf8.
5421 * Above-Latin1 code points can't match the pattern;
5422 * invariants match exactly, and the other Latin1 ones need
5423 * to be downgraded to a single byte in order to do the
5424 * comparison. (If we could be confident that the target
5425 * is not malformed, this could be refactored to have fewer
5426 * tests by just assuming that if the first bytes match, it
5427 * is an invariant, but there are tests in the test suite
5428 * dealing with (??{...}) which violate this) */
5430 if (l >= reginfo->strend
5431 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5435 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5442 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5452 /* The target is not utf8, the pattern is utf8. */
5454 if (l >= reginfo->strend
5455 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5459 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5466 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5478 /* The target and the pattern have the same utf8ness. */
5479 /* Inline the first character, for speed. */
5480 if (reginfo->strend - locinput < ln
5481 || UCHARAT(s) != nextchr
5482 || (ln > 1 && memNE(s, locinput, ln)))
5491 case EXACTFL: { /* /abc/il */
5493 const U8 * fold_array;
5495 U32 fold_utf8_flags;
5497 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5498 folder = foldEQ_locale;
5499 fold_array = PL_fold_locale;
5500 fold_utf8_flags = FOLDEQ_LOCALE;
5503 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5504 is effectively /u; hence to match, target
5506 if (! utf8_target) {
5509 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5510 | FOLDEQ_S1_FOLDS_SANE;
5511 folder = foldEQ_latin1;
5512 fold_array = PL_fold_latin1;
5515 case EXACTFU_SS: /* /\x{df}/iu */
5516 case EXACTFU: /* /abc/iu */
5517 folder = foldEQ_latin1;
5518 fold_array = PL_fold_latin1;
5519 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5522 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5524 assert(! is_utf8_pat);
5526 case EXACTFA: /* /abc/iaa */
5527 folder = foldEQ_latin1;
5528 fold_array = PL_fold_latin1;
5529 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5532 case EXACTF: /* /abc/i This node only generated for
5533 non-utf8 patterns */
5534 assert(! is_utf8_pat);
5536 fold_array = PL_fold;
5537 fold_utf8_flags = 0;
5545 || state_num == EXACTFU_SS
5546 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5548 /* Either target or the pattern are utf8, or has the issue where
5549 * the fold lengths may differ. */
5550 const char * const l = locinput;
5551 char *e = reginfo->strend;
5553 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
5554 l, &e, 0, utf8_target, fold_utf8_flags))
5562 /* Neither the target nor the pattern are utf8 */
5563 if (UCHARAT(s) != nextchr
5565 && UCHARAT(s) != fold_array[nextchr])
5569 if (reginfo->strend - locinput < ln)
5571 if (ln > 1 && ! folder(s, locinput, ln))
5577 case NBOUNDL: /* /\B/l */
5581 case BOUNDL: /* /\b/l */
5584 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5586 if (FLAGS(scan) != TRADITIONAL_BOUND) {
5587 if (! IN_UTF8_CTYPE_LOCALE) {
5588 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5589 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5595 if (locinput == reginfo->strbeg)
5596 b1 = isWORDCHAR_LC('\n');
5598 b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5599 (U8*)(reginfo->strbeg)));
5601 b2 = (NEXTCHR_IS_EOS)
5602 ? isWORDCHAR_LC('\n')
5603 : isWORDCHAR_LC_utf8((U8*)locinput);
5605 else { /* Here the string isn't utf8 */
5606 b1 = (locinput == reginfo->strbeg)
5607 ? isWORDCHAR_LC('\n')
5608 : isWORDCHAR_LC(UCHARAT(locinput - 1));
5609 b2 = (NEXTCHR_IS_EOS)
5610 ? isWORDCHAR_LC('\n')
5611 : isWORDCHAR_LC(nextchr);
5613 if (to_complement ^ (b1 == b2)) {
5619 case NBOUND: /* /\B/ */
5623 case BOUND: /* /\b/ */
5627 goto bound_ascii_match_only;
5629 case NBOUNDA: /* /\B/a */
5633 case BOUNDA: /* /\b/a */
5637 bound_ascii_match_only:
5638 /* Here the string isn't utf8, or is utf8 and only ascii characters
5639 * are to match \w. In the latter case looking at the byte just
5640 * prior to the current one may be just the final byte of a
5641 * multi-byte character. This is ok. There are two cases:
5642 * 1) it is a single byte character, and then the test is doing
5643 * just what it's supposed to.
5644 * 2) it is a multi-byte character, in which case the final byte is
5645 * never mistakable for ASCII, and so the test will say it is
5646 * not a word character, which is the correct answer. */
5647 b1 = (locinput == reginfo->strbeg)
5648 ? isWORDCHAR_A('\n')
5649 : isWORDCHAR_A(UCHARAT(locinput - 1));
5650 b2 = (NEXTCHR_IS_EOS)
5651 ? isWORDCHAR_A('\n')
5652 : isWORDCHAR_A(nextchr);
5653 if (to_complement ^ (b1 == b2)) {
5659 case NBOUNDU: /* /\B/u */
5663 case BOUNDU: /* /\b/u */
5666 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
5669 else if (utf8_target) {
5671 switch((bound_type) FLAGS(scan)) {
5672 case TRADITIONAL_BOUND:
5675 b1 = (locinput == reginfo->strbeg)
5676 ? 0 /* isWORDCHAR_L1('\n') */
5677 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5678 (U8*)(reginfo->strbeg)));
5679 b2 = (NEXTCHR_IS_EOS)
5680 ? 0 /* isWORDCHAR_L1('\n') */
5681 : isWORDCHAR_utf8((U8*)locinput);
5682 match = cBOOL(b1 != b2);
5686 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5687 match = TRUE; /* GCB always matches at begin and
5691 /* Find the gcb values of previous and current
5692 * chars, then see if is a break point */
5693 match = isGCB(getGCB_VAL_UTF8(
5694 reghop3((U8*)locinput,
5696 (U8*)(reginfo->strbeg)),
5697 (U8*) reginfo->strend),
5698 getGCB_VAL_UTF8((U8*) locinput,
5699 (U8*) reginfo->strend));
5703 case SB_BOUND: /* Always matches at begin and end */
5704 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5708 match = isSB(getSB_VAL_UTF8(
5709 reghop3((U8*)locinput,
5711 (U8*)(reginfo->strbeg)),
5712 (U8*) reginfo->strend),
5713 getSB_VAL_UTF8((U8*) locinput,
5714 (U8*) reginfo->strend),
5715 (U8*) reginfo->strbeg,
5717 (U8*) reginfo->strend,
5723 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5727 match = isWB(WB_UNKNOWN,
5729 reghop3((U8*)locinput,
5731 (U8*)(reginfo->strbeg)),
5732 (U8*) reginfo->strend),
5733 getWB_VAL_UTF8((U8*) locinput,
5734 (U8*) reginfo->strend),
5735 (U8*) reginfo->strbeg,
5737 (U8*) reginfo->strend,
5743 else { /* Not utf8 target */
5744 switch((bound_type) FLAGS(scan)) {
5745 case TRADITIONAL_BOUND:
5748 b1 = (locinput == reginfo->strbeg)
5749 ? 0 /* isWORDCHAR_L1('\n') */
5750 : isWORDCHAR_L1(UCHARAT(locinput - 1));
5751 b2 = (NEXTCHR_IS_EOS)
5752 ? 0 /* isWORDCHAR_L1('\n') */
5753 : isWORDCHAR_L1(nextchr);
5754 match = cBOOL(b1 != b2);
5759 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5760 match = TRUE; /* GCB always matches at begin and
5763 else { /* Only CR-LF combo isn't a GCB in 0-255
5765 match = UCHARAT(locinput - 1) != '\r'
5766 || UCHARAT(locinput) != '\n';
5770 case SB_BOUND: /* Always matches at begin and end */
5771 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5775 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
5776 getSB_VAL_CP(UCHARAT(locinput)),
5777 (U8*) reginfo->strbeg,
5779 (U8*) reginfo->strend,
5785 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5789 match = isWB(WB_UNKNOWN,
5790 getWB_VAL_CP(UCHARAT(locinput -1)),
5791 getWB_VAL_CP(UCHARAT(locinput)),
5792 (U8*) reginfo->strbeg,
5794 (U8*) reginfo->strend,
5801 if (to_complement ^ ! match) {
5806 case ANYOFL: /* /[abc]/l */
5807 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5809 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
5811 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
5814 case ANYOFD: /* /[abc]/d */
5815 case ANYOF: /* /[abc]/ */
5818 if (utf8_target && ! UTF8_IS_INVARIANT(locinput)) {
5819 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
5822 locinput += UTF8SKIP(locinput);
5825 if (!REGINCLASS(rex, scan, (U8*)locinput))
5831 /* The argument (FLAGS) to all the POSIX node types is the class number
5834 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
5838 case POSIXL: /* \w or [:punct:] etc. under /l */
5839 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5843 /* Use isFOO_lc() for characters within Latin1. (Note that
5844 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5845 * wouldn't be invariant) */
5846 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5847 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
5851 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5852 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
5853 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
5854 *(locinput + 1))))))
5859 else { /* Here, must be an above Latin-1 code point */
5860 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5861 goto utf8_posix_above_latin1;
5864 /* Here, must be utf8 */
5865 locinput += UTF8SKIP(locinput);
5868 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
5872 case POSIXD: /* \w or [:punct:] etc. under /d */
5878 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
5880 if (NEXTCHR_IS_EOS) {
5884 /* All UTF-8 variants match */
5885 if (! UTF8_IS_INVARIANT(nextchr)) {
5886 goto increment_locinput;
5892 case POSIXA: /* \w or [:punct:] etc. under /a */
5895 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
5896 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
5897 * character is a single byte */
5900 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
5906 /* Here we are either not in utf8, or we matched a utf8-invariant,
5907 * so the next char is the next byte */
5911 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
5915 case POSIXU: /* \w or [:punct:] etc. under /u */
5917 if (NEXTCHR_IS_EOS) {
5921 /* Use _generic_isCC() for characters within Latin1. (Note that
5922 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5923 * wouldn't be invariant) */
5924 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5925 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
5932 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5933 if (! (to_complement
5934 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
5942 else { /* Handle above Latin-1 code points */
5943 utf8_posix_above_latin1:
5944 classnum = (_char_class_number) FLAGS(scan);
5945 if (classnum < _FIRST_NON_SWASH_CC) {
5947 /* Here, uses a swash to find such code points. Load if if
5948 * not done already */
5949 if (! PL_utf8_swash_ptrs[classnum]) {
5950 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
5951 PL_utf8_swash_ptrs[classnum]
5952 = _core_swash_init("utf8",
5955 PL_XPosix_ptrs[classnum], &flags);
5957 if (! (to_complement
5958 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
5959 (U8 *) locinput, TRUE))))
5964 else { /* Here, uses macros to find above Latin-1 code points */
5966 case _CC_ENUM_SPACE:
5967 if (! (to_complement
5968 ^ cBOOL(is_XPERLSPACE_high(locinput))))
5973 case _CC_ENUM_BLANK:
5974 if (! (to_complement
5975 ^ cBOOL(is_HORIZWS_high(locinput))))
5980 case _CC_ENUM_XDIGIT:
5981 if (! (to_complement
5982 ^ cBOOL(is_XDIGIT_high(locinput))))
5987 case _CC_ENUM_VERTSPACE:
5988 if (! (to_complement
5989 ^ cBOOL(is_VERTWS_high(locinput))))
5994 default: /* The rest, e.g. [:cntrl:], can't match
5996 if (! to_complement) {
6002 locinput += UTF8SKIP(locinput);
6006 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6007 a Unicode extended Grapheme Cluster */
6010 if (! utf8_target) {
6012 /* Match either CR LF or '.', as all the other possibilities
6014 locinput++; /* Match the . or CR */
6015 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6017 && locinput < reginfo->strend
6018 && UCHARAT(locinput) == '\n')
6025 /* Get the gcb type for the current character */
6026 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6027 (U8*) reginfo->strend);
6029 /* Then scan through the input until we get to the first
6030 * character whose type is supposed to be a gcb with the
6031 * current character. (There is always a break at the
6033 locinput += UTF8SKIP(locinput);
6034 while (locinput < reginfo->strend) {
6035 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6036 (U8*) reginfo->strend);
6037 if (isGCB(prev_gcb, cur_gcb)) {
6042 locinput += UTF8SKIP(locinput);
6049 case NREFFL: /* /\g{name}/il */
6050 { /* The capture buffer cases. The ones beginning with N for the
6051 named buffers just convert to the equivalent numbered and
6052 pretend they were called as the corresponding numbered buffer
6054 /* don't initialize these in the declaration, it makes C++
6059 const U8 *fold_array;
6062 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6063 folder = foldEQ_locale;
6064 fold_array = PL_fold_locale;
6066 utf8_fold_flags = FOLDEQ_LOCALE;
6069 case NREFFA: /* /\g{name}/iaa */
6070 folder = foldEQ_latin1;
6071 fold_array = PL_fold_latin1;
6073 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6076 case NREFFU: /* /\g{name}/iu */
6077 folder = foldEQ_latin1;
6078 fold_array = PL_fold_latin1;
6080 utf8_fold_flags = 0;
6083 case NREFF: /* /\g{name}/i */
6085 fold_array = PL_fold;
6087 utf8_fold_flags = 0;
6090 case NREF: /* /\g{name}/ */
6094 utf8_fold_flags = 0;
6097 /* For the named back references, find the corresponding buffer
6099 n = reg_check_named_buff_matched(rex,scan);
6104 goto do_nref_ref_common;
6106 case REFFL: /* /\1/il */
6107 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6108 folder = foldEQ_locale;
6109 fold_array = PL_fold_locale;
6110 utf8_fold_flags = FOLDEQ_LOCALE;
6113 case REFFA: /* /\1/iaa */
6114 folder = foldEQ_latin1;
6115 fold_array = PL_fold_latin1;
6116 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6119 case REFFU: /* /\1/iu */
6120 folder = foldEQ_latin1;
6121 fold_array = PL_fold_latin1;
6122 utf8_fold_flags = 0;
6125 case REFF: /* /\1/i */
6127 fold_array = PL_fold;
6128 utf8_fold_flags = 0;
6131 case REF: /* /\1/ */
6134 utf8_fold_flags = 0;
6138 n = ARG(scan); /* which paren pair */
6141 ln = rex->offs[n].start;
6142 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6143 if (rex->lastparen < n || ln == -1)
6144 sayNO; /* Do not match unless seen CLOSEn. */
6145 if (ln == rex->offs[n].end)
6148 s = reginfo->strbeg + ln;
6149 if (type != REF /* REF can do byte comparison */
6150 && (utf8_target || type == REFFU || type == REFFL))
6152 char * limit = reginfo->strend;
6154 /* This call case insensitively compares the entire buffer
6155 * at s, with the current input starting at locinput, but
6156 * not going off the end given by reginfo->strend, and
6157 * returns in <limit> upon success, how much of the
6158 * current input was matched */
6159 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6160 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6168 /* Not utf8: Inline the first character, for speed. */
6169 if (!NEXTCHR_IS_EOS &&
6170 UCHARAT(s) != nextchr &&
6172 UCHARAT(s) != fold_array[nextchr]))
6174 ln = rex->offs[n].end - ln;
6175 if (locinput + ln > reginfo->strend)
6177 if (ln > 1 && (type == REF
6178 ? memNE(s, locinput, ln)
6179 : ! folder(s, locinput, ln)))
6185 case NOTHING: /* null op; e.g. the 'nothing' following
6186 * the '*' in m{(a+|b)*}' */
6188 case TAIL: /* placeholder while compiling (A|B|C) */
6192 #define ST st->u.eval
6197 regexp_internal *rei;
6198 regnode *startpoint;
6200 case GOSTART: /* (?R) */
6201 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6202 if (cur_eval && cur_eval->locinput==locinput) {
6203 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
6204 Perl_croak(aTHX_ "Infinite recursion in regex");
6205 if ( ++nochange_depth > max_nochange_depth )
6207 "Pattern subroutine nesting without pos change"
6208 " exceeded limit in regex");
6215 if (OP(scan)==GOSUB) {
6216 startpoint = scan + ARG2L(scan);
6217 ST.close_paren = ARG(scan);
6219 startpoint = rei->program+1;
6223 /* Save all the positions seen so far. */
6224 ST.cp = regcppush(rex, 0, maxopenparen);
6225 REGCP_SET(ST.lastcp);
6227 /* and then jump to the code we share with EVAL */
6228 goto eval_recurse_doit;
6231 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6232 if (cur_eval && cur_eval->locinput==locinput) {
6233 if ( ++nochange_depth > max_nochange_depth )
6234 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6239 /* execute the code in the {...} */
6243 OP * const oop = PL_op;
6244 COP * const ocurcop = PL_curcop;
6248 /* save *all* paren positions */
6249 regcppush(rex, 0, maxopenparen);
6250 REGCP_SET(runops_cp);
6253 caller_cv = find_runcv(NULL);
6257 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6259 (REGEXP*)(rexi->data->data[n])
6262 nop = (OP*)rexi->data->data[n+1];
6264 else if (rexi->data->what[n] == 'l') { /* literal code */
6266 nop = (OP*)rexi->data->data[n];
6267 assert(CvDEPTH(newcv));
6270 /* literal with own CV */
6271 assert(rexi->data->what[n] == 'L');
6272 newcv = rex->qr_anoncv;
6273 nop = (OP*)rexi->data->data[n];
6276 /* normally if we're about to execute code from the same
6277 * CV that we used previously, we just use the existing
6278 * CX stack entry. However, its possible that in the
6279 * meantime we may have backtracked, popped from the save
6280 * stack, and undone the SAVECOMPPAD(s) associated with
6281 * PUSH_MULTICALL; in which case PL_comppad no longer
6282 * points to newcv's pad. */
6283 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6285 U8 flags = (CXp_SUB_RE |
6286 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6287 if (last_pushed_cv) {
6288 CHANGE_MULTICALL_FLAGS(newcv, flags);
6291 PUSH_MULTICALL_FLAGS(newcv, flags);
6293 last_pushed_cv = newcv;
6296 /* these assignments are just to silence compiler
6298 multicall_cop = NULL;
6301 last_pad = PL_comppad;
6303 /* the initial nextstate you would normally execute
6304 * at the start of an eval (which would cause error
6305 * messages to come from the eval), may be optimised
6306 * away from the execution path in the regex code blocks;
6307 * so manually set PL_curcop to it initially */
6309 OP *o = cUNOPx(nop)->op_first;
6310 assert(o->op_type == OP_NULL);
6311 if (o->op_targ == OP_SCOPE) {
6312 o = cUNOPo->op_first;
6315 assert(o->op_targ == OP_LEAVE);
6316 o = cUNOPo->op_first;
6317 assert(o->op_type == OP_ENTER);
6321 if (o->op_type != OP_STUB) {
6322 assert( o->op_type == OP_NEXTSTATE
6323 || o->op_type == OP_DBSTATE
6324 || (o->op_type == OP_NULL
6325 && ( o->op_targ == OP_NEXTSTATE
6326 || o->op_targ == OP_DBSTATE
6330 PL_curcop = (COP*)o;
6335 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
6336 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6338 rex->offs[0].end = locinput - reginfo->strbeg;
6339 if (reginfo->info_aux_eval->pos_magic)
6340 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6341 reginfo->sv, reginfo->strbeg,
6342 locinput - reginfo->strbeg);
6345 SV *sv_mrk = get_sv("REGMARK", 1);
6346 sv_setsv(sv_mrk, sv_yes_mark);
6349 /* we don't use MULTICALL here as we want to call the
6350 * first op of the block of interest, rather than the
6351 * first op of the sub */
6352 before = (IV)(SP-PL_stack_base);
6354 CALLRUNOPS(aTHX); /* Scalar context. */
6356 if ((IV)(SP-PL_stack_base) == before)
6357 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6363 /* before restoring everything, evaluate the returned
6364 * value, so that 'uninit' warnings don't use the wrong
6365 * PL_op or pad. Also need to process any magic vars
6366 * (e.g. $1) *before* parentheses are restored */
6371 if (logical == 0) /* (?{})/ */
6372 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6373 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6374 sw = cBOOL(SvTRUE(ret));
6377 else { /* /(??{}) */
6378 /* if its overloaded, let the regex compiler handle
6379 * it; otherwise extract regex, or stringify */
6380 if (SvGMAGICAL(ret))
6381 ret = sv_mortalcopy(ret);
6382 if (!SvAMAGIC(ret)) {
6386 if (SvTYPE(sv) == SVt_REGEXP)
6387 re_sv = (REGEXP*) sv;
6388 else if (SvSMAGICAL(ret)) {
6389 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6391 re_sv = (REGEXP *) mg->mg_obj;
6394 /* force any undef warnings here */
6395 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6396 ret = sv_mortalcopy(ret);
6397 (void) SvPV_force_nolen(ret);
6403 /* *** Note that at this point we don't restore
6404 * PL_comppad, (or pop the CxSUB) on the assumption it may
6405 * be used again soon. This is safe as long as nothing
6406 * in the regexp code uses the pad ! */
6408 PL_curcop = ocurcop;
6409 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6410 PL_curpm = PL_reg_curpm;
6416 /* only /(??{})/ from now on */
6419 /* extract RE object from returned value; compiling if
6423 re_sv = reg_temp_copy(NULL, re_sv);
6428 if (SvUTF8(ret) && IN_BYTES) {
6429 /* In use 'bytes': make a copy of the octet
6430 * sequence, but without the flag on */
6432 const char *const p = SvPV(ret, len);
6433 ret = newSVpvn_flags(p, len, SVs_TEMP);
6435 if (rex->intflags & PREGf_USE_RE_EVAL)
6436 pm_flags |= PMf_USE_RE_EVAL;
6438 /* if we got here, it should be an engine which
6439 * supports compiling code blocks and stuff */
6440 assert(rex->engine && rex->engine->op_comp);
6441 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6442 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6443 rex->engine, NULL, NULL,
6444 /* copy /msixn etc to inner pattern */
6449 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6450 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6451 /* This isn't a first class regexp. Instead, it's
6452 caching a regexp onto an existing, Perl visible
6454 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6460 RXp_MATCH_COPIED_off(re);
6461 re->subbeg = rex->subbeg;
6462 re->sublen = rex->sublen;
6463 re->suboffset = rex->suboffset;
6464 re->subcoffset = rex->subcoffset;
6466 re->lastcloseparen = 0;
6469 debug_start_match(re_sv, utf8_target, locinput,
6470 reginfo->strend, "Matching embedded");
6472 startpoint = rei->program + 1;
6473 ST.close_paren = 0; /* only used for GOSUB */
6474 /* Save all the seen positions so far. */
6475 ST.cp = regcppush(rex, 0, maxopenparen);
6476 REGCP_SET(ST.lastcp);
6477 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6479 /* run the pattern returned from (??{...}) */
6481 eval_recurse_doit: /* Share code with GOSUB below this line
6482 * At this point we expect the stack context to be
6483 * set up correctly */
6485 /* invalidate the S-L poscache. We're now executing a
6486 * different set of WHILEM ops (and their associated
6487 * indexes) against the same string, so the bits in the
6488 * cache are meaningless. Setting maxiter to zero forces
6489 * the cache to be invalidated and zeroed before reuse.
6490 * XXX This is too dramatic a measure. Ideally we should
6491 * save the old cache and restore when running the outer
6493 reginfo->poscache_maxiter = 0;
6495 /* the new regexp might have a different is_utf8_pat than we do */
6496 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6498 ST.prev_rex = rex_sv;
6499 ST.prev_curlyx = cur_curlyx;
6501 SET_reg_curpm(rex_sv);
6506 ST.prev_eval = cur_eval;
6508 /* now continue from first node in postoned RE */
6509 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
6511 NOT_REACHED; /* NOTREACHED */
6514 case EVAL_AB: /* cleanup after a successful (??{A})B */
6515 /* note: this is called twice; first after popping B, then A */
6516 rex_sv = ST.prev_rex;
6517 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6518 SET_reg_curpm(rex_sv);
6519 rex = ReANY(rex_sv);
6520 rexi = RXi_GET(rex);
6522 /* preserve $^R across LEAVE's. See Bug 121070. */
6523 SV *save_sv= GvSV(PL_replgv);
6524 SvREFCNT_inc(save_sv);
6525 regcpblow(ST.cp); /* LEAVE in disguise */
6526 sv_setsv(GvSV(PL_replgv), save_sv);
6527 SvREFCNT_dec(save_sv);
6529 cur_eval = ST.prev_eval;
6530 cur_curlyx = ST.prev_curlyx;
6532 /* Invalidate cache. See "invalidate" comment above. */
6533 reginfo->poscache_maxiter = 0;
6534 if ( nochange_depth )
6539 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
6540 /* note: this is called twice; first after popping B, then A */
6541 rex_sv = ST.prev_rex;
6542 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6543 SET_reg_curpm(rex_sv);
6544 rex = ReANY(rex_sv);
6545 rexi = RXi_GET(rex);
6547 REGCP_UNWIND(ST.lastcp);
6548 regcppop(rex, &maxopenparen);
6549 cur_eval = ST.prev_eval;
6550 cur_curlyx = ST.prev_curlyx;
6551 /* Invalidate cache. See "invalidate" comment above. */
6552 reginfo->poscache_maxiter = 0;
6553 if ( nochange_depth )
6559 n = ARG(scan); /* which paren pair */
6560 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
6561 if (n > maxopenparen)
6563 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
6564 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
6568 (IV)rex->offs[n].start_tmp,
6574 /* XXX really need to log other places start/end are set too */
6575 #define CLOSE_CAPTURE \
6576 rex->offs[n].start = rex->offs[n].start_tmp; \
6577 rex->offs[n].end = locinput - reginfo->strbeg; \
6578 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
6579 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
6581 PTR2UV(rex->offs), \
6583 (IV)rex->offs[n].start, \
6584 (IV)rex->offs[n].end \
6588 n = ARG(scan); /* which paren pair */
6590 if (n > rex->lastparen)
6592 rex->lastcloseparen = n;
6593 if (cur_eval && cur_eval->u.eval.close_paren == n) {
6598 case ACCEPT: /* (*ACCEPT) */
6600 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6604 cursor && OP(cursor)!=END;
6605 cursor=regnext(cursor))
6607 if ( OP(cursor)==CLOSE ){
6609 if ( n <= lastopen ) {
6611 if (n > rex->lastparen)
6613 rex->lastcloseparen = n;
6614 if ( n == ARG(scan) || (cur_eval &&
6615 cur_eval->u.eval.close_paren == n))
6624 case GROUPP: /* (?(1)) */
6625 n = ARG(scan); /* which paren pair */
6626 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
6629 case NGROUPP: /* (?(<name>)) */
6630 /* reg_check_named_buff_matched returns 0 for no match */
6631 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
6634 case INSUBP: /* (?(R)) */
6636 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
6639 case DEFINEP: /* (?(DEFINE)) */
6643 case IFTHEN: /* (?(cond)A|B) */
6644 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6646 next = NEXTOPER(NEXTOPER(scan));
6648 next = scan + ARG(scan);
6649 if (OP(next) == IFTHEN) /* Fake one. */
6650 next = NEXTOPER(NEXTOPER(next));
6654 case LOGICAL: /* modifier for EVAL and IFMATCH */
6655 logical = scan->flags;
6658 /*******************************************************************
6660 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
6661 pattern, where A and B are subpatterns. (For simple A, CURLYM or
6662 STAR/PLUS/CURLY/CURLYN are used instead.)
6664 A*B is compiled as <CURLYX><A><WHILEM><B>
6666 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
6667 state, which contains the current count, initialised to -1. It also sets
6668 cur_curlyx to point to this state, with any previous value saved in the
6671 CURLYX then jumps straight to the WHILEM op, rather than executing A,
6672 since the pattern may possibly match zero times (i.e. it's a while {} loop
6673 rather than a do {} while loop).
6675 Each entry to WHILEM represents a successful match of A. The count in the
6676 CURLYX block is incremented, another WHILEM state is pushed, and execution
6677 passes to A or B depending on greediness and the current count.
6679 For example, if matching against the string a1a2a3b (where the aN are
6680 substrings that match /A/), then the match progresses as follows: (the
6681 pushed states are interspersed with the bits of strings matched so far):
6684 <CURLYX cnt=0><WHILEM>
6685 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
6686 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
6687 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
6688 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
6690 (Contrast this with something like CURLYM, which maintains only a single
6694 a1 <CURLYM cnt=1> a2
6695 a1 a2 <CURLYM cnt=2> a3
6696 a1 a2 a3 <CURLYM cnt=3> b
6699 Each WHILEM state block marks a point to backtrack to upon partial failure
6700 of A or B, and also contains some minor state data related to that
6701 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
6702 overall state, such as the count, and pointers to the A and B ops.
6704 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
6705 must always point to the *current* CURLYX block, the rules are:
6707 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
6708 and set cur_curlyx to point the new block.
6710 When popping the CURLYX block after a successful or unsuccessful match,
6711 restore the previous cur_curlyx.
6713 When WHILEM is about to execute B, save the current cur_curlyx, and set it
6714 to the outer one saved in the CURLYX block.
6716 When popping the WHILEM block after a successful or unsuccessful B match,
6717 restore the previous cur_curlyx.
6719 Here's an example for the pattern (AI* BI)*BO
6720 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
6723 curlyx backtrack stack
6724 ------ ---------------
6726 CO <CO prev=NULL> <WO>
6727 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6728 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6729 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
6731 At this point the pattern succeeds, and we work back down the stack to
6732 clean up, restoring as we go:
6734 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6735 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6736 CO <CO prev=NULL> <WO>
6739 *******************************************************************/
6741 #define ST st->u.curlyx
6743 case CURLYX: /* start of /A*B/ (for complex A) */
6745 /* No need to save/restore up to this paren */
6746 I32 parenfloor = scan->flags;
6748 assert(next); /* keep Coverity happy */
6749 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
6752 /* XXXX Probably it is better to teach regpush to support
6753 parenfloor > maxopenparen ... */
6754 if (parenfloor > (I32)rex->lastparen)
6755 parenfloor = rex->lastparen; /* Pessimization... */
6757 ST.prev_curlyx= cur_curlyx;
6759 ST.cp = PL_savestack_ix;
6761 /* these fields contain the state of the current curly.
6762 * they are accessed by subsequent WHILEMs */
6763 ST.parenfloor = parenfloor;
6768 ST.count = -1; /* this will be updated by WHILEM */
6769 ST.lastloc = NULL; /* this will be updated by WHILEM */
6771 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
6773 NOT_REACHED; /* NOTREACHED */
6776 case CURLYX_end: /* just finished matching all of A*B */
6777 cur_curlyx = ST.prev_curlyx;
6780 NOT_REACHED; /* NOTREACHED */
6782 case CURLYX_end_fail: /* just failed to match all of A*B */
6784 cur_curlyx = ST.prev_curlyx;
6787 NOT_REACHED; /* NOTREACHED */
6791 #define ST st->u.whilem
6793 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
6795 /* see the discussion above about CURLYX/WHILEM */
6800 assert(cur_curlyx); /* keep Coverity happy */
6802 min = ARG1(cur_curlyx->u.curlyx.me);
6803 max = ARG2(cur_curlyx->u.curlyx.me);
6804 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
6805 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
6806 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
6807 ST.cache_offset = 0;
6811 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6812 "%*s whilem: matched %ld out of %d..%d\n",
6813 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
6816 /* First just match a string of min A's. */
6819 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6821 cur_curlyx->u.curlyx.lastloc = locinput;
6822 REGCP_SET(ST.lastcp);
6824 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
6826 NOT_REACHED; /* NOTREACHED */
6829 /* If degenerate A matches "", assume A done. */
6831 if (locinput == cur_curlyx->u.curlyx.lastloc) {
6832 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6833 "%*s whilem: empty match detected, trying continuation...\n",
6834 REPORT_CODE_OFF+depth*2, "")
6836 goto do_whilem_B_max;
6839 /* super-linear cache processing.
6841 * The idea here is that for certain types of CURLYX/WHILEM -
6842 * principally those whose upper bound is infinity (and
6843 * excluding regexes that have things like \1 and other very
6844 * non-regular expresssiony things), then if a pattern like
6845 * /....A*.../ fails and we backtrack to the WHILEM, then we
6846 * make a note that this particular WHILEM op was at string
6847 * position 47 (say) when the rest of pattern failed. Then, if
6848 * we ever find ourselves back at that WHILEM, and at string
6849 * position 47 again, we can just fail immediately rather than
6850 * running the rest of the pattern again.
6852 * This is very handy when patterns start to go
6853 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
6854 * with a combinatorial explosion of backtracking.
6856 * The cache is implemented as a bit array, with one bit per
6857 * string byte position per WHILEM op (up to 16) - so its
6858 * between 0.25 and 2x the string size.
6860 * To avoid allocating a poscache buffer every time, we do an
6861 * initially countdown; only after we have executed a WHILEM
6862 * op (string-length x #WHILEMs) times do we allocate the
6865 * The top 4 bits of scan->flags byte say how many different
6866 * relevant CURLLYX/WHILEM op pairs there are, while the
6867 * bottom 4-bits is the identifying index number of this
6873 if (!reginfo->poscache_maxiter) {
6874 /* start the countdown: Postpone detection until we
6875 * know the match is not *that* much linear. */
6876 reginfo->poscache_maxiter
6877 = (reginfo->strend - reginfo->strbeg + 1)
6879 /* possible overflow for long strings and many CURLYX's */
6880 if (reginfo->poscache_maxiter < 0)
6881 reginfo->poscache_maxiter = I32_MAX;
6882 reginfo->poscache_iter = reginfo->poscache_maxiter;
6885 if (reginfo->poscache_iter-- == 0) {
6886 /* initialise cache */
6887 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
6888 regmatch_info_aux *const aux = reginfo->info_aux;
6889 if (aux->poscache) {
6890 if ((SSize_t)reginfo->poscache_size < size) {
6891 Renew(aux->poscache, size, char);
6892 reginfo->poscache_size = size;
6894 Zero(aux->poscache, size, char);
6897 reginfo->poscache_size = size;
6898 Newxz(aux->poscache, size, char);
6900 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6901 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
6902 PL_colors[4], PL_colors[5])
6906 if (reginfo->poscache_iter < 0) {
6907 /* have we already failed at this position? */
6908 SSize_t offset, mask;
6910 reginfo->poscache_iter = -1; /* stop eventual underflow */
6911 offset = (scan->flags & 0xf) - 1
6912 + (locinput - reginfo->strbeg)
6914 mask = 1 << (offset % 8);
6916 if (reginfo->info_aux->poscache[offset] & mask) {
6917 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6918 "%*s whilem: (cache) already tried at this position...\n",
6919 REPORT_CODE_OFF+depth*2, "")
6921 sayNO; /* cache records failure */
6923 ST.cache_offset = offset;
6924 ST.cache_mask = mask;
6928 /* Prefer B over A for minimal matching. */
6930 if (cur_curlyx->u.curlyx.minmod) {
6931 ST.save_curlyx = cur_curlyx;
6932 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6933 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
6935 REGCP_SET(ST.lastcp);
6936 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
6939 NOT_REACHED; /* NOTREACHED */
6942 /* Prefer A over B for maximal matching. */
6944 if (n < max) { /* More greed allowed? */
6945 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6947 cur_curlyx->u.curlyx.lastloc = locinput;
6948 REGCP_SET(ST.lastcp);
6949 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
6951 NOT_REACHED; /* NOTREACHED */
6953 goto do_whilem_B_max;
6956 NOT_REACHED; /* NOTREACHED */
6958 case WHILEM_B_min: /* just matched B in a minimal match */
6959 case WHILEM_B_max: /* just matched B in a maximal match */
6960 cur_curlyx = ST.save_curlyx;
6963 NOT_REACHED; /* NOTREACHED */
6965 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
6966 cur_curlyx = ST.save_curlyx;
6967 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6968 cur_curlyx->u.curlyx.count--;
6971 NOT_REACHED; /* NOTREACHED */
6973 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
6975 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
6976 REGCP_UNWIND(ST.lastcp);
6977 regcppop(rex, &maxopenparen);
6978 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6979 cur_curlyx->u.curlyx.count--;
6982 NOT_REACHED; /* NOTREACHED */
6984 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
6985 REGCP_UNWIND(ST.lastcp);
6986 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
6987 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6988 "%*s whilem: failed, trying continuation...\n",
6989 REPORT_CODE_OFF+depth*2, "")
6992 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6993 && ckWARN(WARN_REGEXP)
6994 && !reginfo->warned)
6996 reginfo->warned = TRUE;
6997 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6998 "Complex regular subexpression recursion limit (%d) "
7004 ST.save_curlyx = cur_curlyx;
7005 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7006 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7009 NOT_REACHED; /* NOTREACHED */
7011 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7012 cur_curlyx = ST.save_curlyx;
7013 REGCP_UNWIND(ST.lastcp);
7014 regcppop(rex, &maxopenparen);
7016 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7017 /* Maximum greed exceeded */
7018 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7019 && ckWARN(WARN_REGEXP)
7020 && !reginfo->warned)
7022 reginfo->warned = TRUE;
7023 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7024 "Complex regular subexpression recursion "
7025 "limit (%d) exceeded",
7028 cur_curlyx->u.curlyx.count--;
7032 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7033 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
7035 /* Try grabbing another A and see if it helps. */
7036 cur_curlyx->u.curlyx.lastloc = locinput;
7037 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7039 REGCP_SET(ST.lastcp);
7040 PUSH_STATE_GOTO(WHILEM_A_min,
7041 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7044 NOT_REACHED; /* NOTREACHED */
7047 #define ST st->u.branch
7049 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7050 next = scan + ARG(scan);
7053 scan = NEXTOPER(scan);
7056 case BRANCH: /* /(...|A|...)/ */
7057 scan = NEXTOPER(scan); /* scan now points to inner node */
7058 ST.lastparen = rex->lastparen;
7059 ST.lastcloseparen = rex->lastcloseparen;
7060 ST.next_branch = next;
7063 /* Now go into the branch */
7065 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7067 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7070 NOT_REACHED; /* NOTREACHED */
7072 case CUTGROUP: /* /(*THEN)/ */
7073 sv_yes_mark = st->u.mark.mark_name = scan->flags
7074 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7076 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7078 NOT_REACHED; /* NOTREACHED */
7080 case CUTGROUP_next_fail:
7083 if (st->u.mark.mark_name)
7084 sv_commit = st->u.mark.mark_name;
7087 NOT_REACHED; /* NOTREACHED */
7092 NOT_REACHED; /* NOTREACHED */
7094 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7099 REGCP_UNWIND(ST.cp);
7100 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7101 scan = ST.next_branch;
7102 /* no more branches? */
7103 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7105 PerlIO_printf( Perl_debug_log,
7106 "%*s %sBRANCH failed...%s\n",
7107 REPORT_CODE_OFF+depth*2, "",
7113 continue; /* execute next BRANCH[J] op */
7116 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7121 #define ST st->u.curlym
7123 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7125 /* This is an optimisation of CURLYX that enables us to push
7126 * only a single backtracking state, no matter how many matches
7127 * there are in {m,n}. It relies on the pattern being constant
7128 * length, with no parens to influence future backrefs
7132 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7134 ST.lastparen = rex->lastparen;
7135 ST.lastcloseparen = rex->lastcloseparen;
7137 /* if paren positive, emulate an OPEN/CLOSE around A */
7139 U32 paren = ST.me->flags;
7140 if (paren > maxopenparen)
7141 maxopenparen = paren;
7142 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7150 ST.c1 = CHRTEST_UNINIT;
7153 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7156 curlym_do_A: /* execute the A in /A{m,n}B/ */
7157 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7159 NOT_REACHED; /* NOTREACHED */
7161 case CURLYM_A: /* we've just matched an A */
7163 /* after first match, determine A's length: u.curlym.alen */
7164 if (ST.count == 1) {
7165 if (reginfo->is_utf8_target) {
7166 char *s = st->locinput;
7167 while (s < locinput) {
7173 ST.alen = locinput - st->locinput;
7176 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7179 PerlIO_printf(Perl_debug_log,
7180 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7181 (int)(REPORT_CODE_OFF+(depth*2)), "",
7182 (IV) ST.count, (IV)ST.alen)
7185 if (cur_eval && cur_eval->u.eval.close_paren &&
7186 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7190 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7191 if ( max == REG_INFTY || ST.count < max )
7192 goto curlym_do_A; /* try to match another A */
7194 goto curlym_do_B; /* try to match B */
7196 case CURLYM_A_fail: /* just failed to match an A */
7197 REGCP_UNWIND(ST.cp);
7199 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7200 || (cur_eval && cur_eval->u.eval.close_paren &&
7201 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7204 curlym_do_B: /* execute the B in /A{m,n}B/ */
7205 if (ST.c1 == CHRTEST_UNINIT) {
7206 /* calculate c1 and c2 for possible match of 1st char
7207 * following curly */
7208 ST.c1 = ST.c2 = CHRTEST_VOID;
7210 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7211 regnode *text_node = ST.B;
7212 if (! HAS_TEXT(text_node))
7213 FIND_NEXT_IMPT(text_node);
7216 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7218 But the former is redundant in light of the latter.
7220 if this changes back then the macro for
7221 IS_TEXT and friends need to change.
7223 if (PL_regkind[OP(text_node)] == EXACT) {
7224 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7225 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7235 PerlIO_printf(Perl_debug_log,
7236 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
7237 (int)(REPORT_CODE_OFF+(depth*2)),
7240 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7241 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7242 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7243 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7245 /* simulate B failing */
7247 PerlIO_printf(Perl_debug_log,
7248 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7249 (int)(REPORT_CODE_OFF+(depth*2)),"",
7250 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7251 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7252 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7254 state_num = CURLYM_B_fail;
7255 goto reenter_switch;
7258 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7259 /* simulate B failing */
7261 PerlIO_printf(Perl_debug_log,
7262 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7263 (int)(REPORT_CODE_OFF+(depth*2)),"",
7264 (int) nextchr, ST.c1, ST.c2)
7266 state_num = CURLYM_B_fail;
7267 goto reenter_switch;
7272 /* emulate CLOSE: mark current A as captured */
7273 I32 paren = ST.me->flags;
7275 rex->offs[paren].start
7276 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7277 rex->offs[paren].end = locinput - reginfo->strbeg;
7278 if ((U32)paren > rex->lastparen)
7279 rex->lastparen = paren;
7280 rex->lastcloseparen = paren;
7283 rex->offs[paren].end = -1;
7284 if (cur_eval && cur_eval->u.eval.close_paren &&
7285 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7294 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7296 NOT_REACHED; /* NOTREACHED */
7298 case CURLYM_B_fail: /* just failed to match a B */
7299 REGCP_UNWIND(ST.cp);
7300 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7302 I32 max = ARG2(ST.me);
7303 if (max != REG_INFTY && ST.count == max)
7305 goto curlym_do_A; /* try to match a further A */
7307 /* backtrack one A */
7308 if (ST.count == ARG1(ST.me) /* min */)
7311 SET_locinput(HOPc(locinput, -ST.alen));
7312 goto curlym_do_B; /* try to match B */
7315 #define ST st->u.curly
7317 #define CURLY_SETPAREN(paren, success) \
7320 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7321 rex->offs[paren].end = locinput - reginfo->strbeg; \
7322 if (paren > rex->lastparen) \
7323 rex->lastparen = paren; \
7324 rex->lastcloseparen = paren; \
7327 rex->offs[paren].end = -1; \
7328 rex->lastparen = ST.lastparen; \
7329 rex->lastcloseparen = ST.lastcloseparen; \
7333 case STAR: /* /A*B/ where A is width 1 char */
7337 scan = NEXTOPER(scan);
7340 case PLUS: /* /A+B/ where A is width 1 char */
7344 scan = NEXTOPER(scan);
7347 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7348 ST.paren = scan->flags; /* Which paren to set */
7349 ST.lastparen = rex->lastparen;
7350 ST.lastcloseparen = rex->lastcloseparen;
7351 if (ST.paren > maxopenparen)
7352 maxopenparen = ST.paren;
7353 ST.min = ARG1(scan); /* min to match */
7354 ST.max = ARG2(scan); /* max to match */
7355 if (cur_eval && cur_eval->u.eval.close_paren &&
7356 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7360 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7363 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7365 ST.min = ARG1(scan); /* min to match */
7366 ST.max = ARG2(scan); /* max to match */
7367 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7370 * Lookahead to avoid useless match attempts
7371 * when we know what character comes next.
7373 * Used to only do .*x and .*?x, but now it allows
7374 * for )'s, ('s and (?{ ... })'s to be in the way
7375 * of the quantifier and the EXACT-like node. -- japhy
7378 assert(ST.min <= ST.max);
7379 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7380 ST.c1 = ST.c2 = CHRTEST_VOID;
7383 regnode *text_node = next;
7385 if (! HAS_TEXT(text_node))
7386 FIND_NEXT_IMPT(text_node);
7388 if (! HAS_TEXT(text_node))
7389 ST.c1 = ST.c2 = CHRTEST_VOID;
7391 if ( PL_regkind[OP(text_node)] != EXACT ) {
7392 ST.c1 = ST.c2 = CHRTEST_VOID;
7396 /* Currently we only get here when
7398 PL_rekind[OP(text_node)] == EXACT
7400 if this changes back then the macro for IS_TEXT and
7401 friends need to change. */
7402 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7403 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7415 char *li = locinput;
7418 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7424 if (ST.c1 == CHRTEST_VOID)
7425 goto curly_try_B_min;
7427 ST.oldloc = locinput;
7429 /* set ST.maxpos to the furthest point along the
7430 * string that could possibly match */
7431 if (ST.max == REG_INFTY) {
7432 ST.maxpos = reginfo->strend - 1;
7434 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7437 else if (utf8_target) {
7438 int m = ST.max - ST.min;
7439 for (ST.maxpos = locinput;
7440 m >0 && ST.maxpos < reginfo->strend; m--)
7441 ST.maxpos += UTF8SKIP(ST.maxpos);
7444 ST.maxpos = locinput + ST.max - ST.min;
7445 if (ST.maxpos >= reginfo->strend)
7446 ST.maxpos = reginfo->strend - 1;
7448 goto curly_try_B_min_known;
7452 /* avoid taking address of locinput, so it can remain
7454 char *li = locinput;
7455 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7456 if (ST.count < ST.min)
7459 if ((ST.count > ST.min)
7460 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7462 /* A{m,n} must come at the end of the string, there's
7463 * no point in backing off ... */
7465 /* ...except that $ and \Z can match before *and* after
7466 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7467 We may back off by one in this case. */
7468 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7472 goto curly_try_B_max;
7475 NOT_REACHED; /* NOTREACHED */
7477 case CURLY_B_min_known_fail:
7478 /* failed to find B in a non-greedy match where c1,c2 valid */
7480 REGCP_UNWIND(ST.cp);
7482 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7484 /* Couldn't or didn't -- move forward. */
7485 ST.oldloc = locinput;
7487 locinput += UTF8SKIP(locinput);
7491 curly_try_B_min_known:
7492 /* find the next place where 'B' could work, then call B */
7496 n = (ST.oldloc == locinput) ? 0 : 1;
7497 if (ST.c1 == ST.c2) {
7498 /* set n to utf8_distance(oldloc, locinput) */
7499 while (locinput <= ST.maxpos
7500 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7502 locinput += UTF8SKIP(locinput);
7507 /* set n to utf8_distance(oldloc, locinput) */
7508 while (locinput <= ST.maxpos
7509 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7510 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7512 locinput += UTF8SKIP(locinput);
7517 else { /* Not utf8_target */
7518 if (ST.c1 == ST.c2) {
7519 while (locinput <= ST.maxpos &&
7520 UCHARAT(locinput) != ST.c1)
7524 while (locinput <= ST.maxpos
7525 && UCHARAT(locinput) != ST.c1
7526 && UCHARAT(locinput) != ST.c2)
7529 n = locinput - ST.oldloc;
7531 if (locinput > ST.maxpos)
7534 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7535 * at b; check that everything between oldloc and
7536 * locinput matches */
7537 char *li = ST.oldloc;
7539 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7541 assert(n == REG_INFTY || locinput == li);
7543 CURLY_SETPAREN(ST.paren, ST.count);
7544 if (cur_eval && cur_eval->u.eval.close_paren &&
7545 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7548 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7551 NOT_REACHED; /* NOTREACHED */
7553 case CURLY_B_min_fail:
7554 /* failed to find B in a non-greedy match where c1,c2 invalid */
7556 REGCP_UNWIND(ST.cp);
7558 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7560 /* failed -- move forward one */
7562 char *li = locinput;
7563 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7570 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7571 ST.count > 0)) /* count overflow ? */
7574 CURLY_SETPAREN(ST.paren, ST.count);
7575 if (cur_eval && cur_eval->u.eval.close_paren &&
7576 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7579 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7584 NOT_REACHED; /* NOTREACHED */
7587 /* a successful greedy match: now try to match B */
7588 if (cur_eval && cur_eval->u.eval.close_paren &&
7589 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7593 bool could_match = locinput < reginfo->strend;
7595 /* If it could work, try it. */
7596 if (ST.c1 != CHRTEST_VOID && could_match) {
7597 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7599 could_match = memEQ(locinput,
7604 UTF8SKIP(locinput));
7607 could_match = UCHARAT(locinput) == ST.c1
7608 || UCHARAT(locinput) == ST.c2;
7611 if (ST.c1 == CHRTEST_VOID || could_match) {
7612 CURLY_SETPAREN(ST.paren, ST.count);
7613 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7615 NOT_REACHED; /* NOTREACHED */
7620 case CURLY_B_max_fail:
7621 /* failed to find B in a greedy match */
7623 REGCP_UNWIND(ST.cp);
7625 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7628 if (--ST.count < ST.min)
7630 locinput = HOPc(locinput, -1);
7631 goto curly_try_B_max;
7635 case END: /* last op of main pattern */
7638 /* we've just finished A in /(??{A})B/; now continue with B */
7640 st->u.eval.prev_rex = rex_sv; /* inner */
7642 /* Save *all* the positions. */
7643 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7644 rex_sv = cur_eval->u.eval.prev_rex;
7645 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7646 SET_reg_curpm(rex_sv);
7647 rex = ReANY(rex_sv);
7648 rexi = RXi_GET(rex);
7649 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7651 REGCP_SET(st->u.eval.lastcp);
7653 /* Restore parens of the outer rex without popping the
7655 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7658 st->u.eval.prev_eval = cur_eval;
7659 cur_eval = cur_eval->u.eval.prev_eval;
7661 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
7662 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7663 if ( nochange_depth )
7666 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7667 locinput); /* match B */
7670 if (locinput < reginfo->till) {
7671 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7672 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7674 (long)(locinput - startpos),
7675 (long)(reginfo->till - startpos),
7678 sayNO_SILENT; /* Cannot match: too short. */
7680 sayYES; /* Success! */
7682 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7684 PerlIO_printf(Perl_debug_log,
7685 "%*s %ssubpattern success...%s\n",
7686 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7687 sayYES; /* Success! */
7690 #define ST st->u.ifmatch
7695 case SUSPEND: /* (?>A) */
7697 newstart = locinput;
7700 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
7702 goto ifmatch_trivial_fail_test;
7704 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
7706 ifmatch_trivial_fail_test:
7708 char * const s = HOPBACKc(locinput, scan->flags);
7713 sw = 1 - cBOOL(ST.wanted);
7717 next = scan + ARG(scan);
7725 newstart = locinput;
7729 ST.logical = logical;
7730 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
7732 /* execute body of (?...A) */
7733 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
7735 NOT_REACHED; /* NOTREACHED */
7738 case IFMATCH_A_fail: /* body of (?...A) failed */
7739 ST.wanted = !ST.wanted;
7742 case IFMATCH_A: /* body of (?...A) succeeded */
7744 sw = cBOOL(ST.wanted);
7746 else if (!ST.wanted)
7749 if (OP(ST.me) != SUSPEND) {
7750 /* restore old position except for (?>...) */
7751 locinput = st->locinput;
7753 scan = ST.me + ARG(ST.me);
7756 continue; /* execute B */
7760 case LONGJMP: /* alternative with many branches compiles to
7761 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
7762 next = scan + ARG(scan);
7767 case COMMIT: /* (*COMMIT) */
7768 reginfo->cutpoint = reginfo->strend;
7771 case PRUNE: /* (*PRUNE) */
7773 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7774 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
7776 NOT_REACHED; /* NOTREACHED */
7778 case COMMIT_next_fail:
7782 NOT_REACHED; /* NOTREACHED */
7784 case OPFAIL: /* (*FAIL) */
7786 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7788 /* deal with (?(?!)X|Y) properly,
7789 * make sure we trigger the no branch
7790 * of the trailing IFTHEN structure*/
7797 NOT_REACHED; /* NOTREACHED */
7799 #define ST st->u.mark
7800 case MARKPOINT: /* (*MARK:foo) */
7801 ST.prev_mark = mark_state;
7802 ST.mark_name = sv_commit = sv_yes_mark
7803 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7805 ST.mark_loc = locinput;
7806 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
7808 NOT_REACHED; /* NOTREACHED */
7810 case MARKPOINT_next:
7811 mark_state = ST.prev_mark;
7814 NOT_REACHED; /* NOTREACHED */
7816 case MARKPOINT_next_fail:
7817 if (popmark && sv_eq(ST.mark_name,popmark))
7819 if (ST.mark_loc > startpoint)
7820 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7821 popmark = NULL; /* we found our mark */
7822 sv_commit = ST.mark_name;
7825 PerlIO_printf(Perl_debug_log,
7826 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
7827 REPORT_CODE_OFF+depth*2, "",
7828 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
7831 mark_state = ST.prev_mark;
7832 sv_yes_mark = mark_state ?
7833 mark_state->u.mark.mark_name : NULL;
7836 NOT_REACHED; /* NOTREACHED */
7838 case SKIP: /* (*SKIP) */
7840 /* (*SKIP) : if we fail we cut here*/
7841 ST.mark_name = NULL;
7842 ST.mark_loc = locinput;
7843 PUSH_STATE_GOTO(SKIP_next,next, locinput);
7845 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
7846 otherwise do nothing. Meaning we need to scan
7848 regmatch_state *cur = mark_state;
7849 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7852 if ( sv_eq( cur->u.mark.mark_name,
7855 ST.mark_name = find;
7856 PUSH_STATE_GOTO( SKIP_next, next, locinput);
7858 cur = cur->u.mark.prev_mark;
7861 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
7864 case SKIP_next_fail:
7866 /* (*CUT:NAME) - Set up to search for the name as we
7867 collapse the stack*/
7868 popmark = ST.mark_name;
7870 /* (*CUT) - No name, we cut here.*/
7871 if (ST.mark_loc > startpoint)
7872 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7873 /* but we set sv_commit to latest mark_name if there
7874 is one so they can test to see how things lead to this
7877 sv_commit=mark_state->u.mark.mark_name;
7882 NOT_REACHED; /* NOTREACHED */
7885 case LNBREAK: /* \R */
7886 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
7893 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
7894 PTR2UV(scan), OP(scan));
7895 Perl_croak(aTHX_ "regexp memory corruption");
7897 /* this is a point to jump to in order to increment
7898 * locinput by one character */
7900 assert(!NEXTCHR_IS_EOS);
7902 locinput += PL_utf8skip[nextchr];
7903 /* locinput is allowed to go 1 char off the end, but not 2+ */
7904 if (locinput > reginfo->strend)
7913 /* switch break jumps here */
7914 scan = next; /* prepare to execute the next op and ... */
7915 continue; /* ... jump back to the top, reusing st */
7919 /* push a state that backtracks on success */
7920 st->u.yes.prev_yes_state = yes_state;
7924 /* push a new regex state, then continue at scan */
7926 regmatch_state *newst;
7929 regmatch_state *cur = st;
7930 regmatch_state *curyes = yes_state;
7932 regmatch_slab *slab = PL_regmatch_slab;
7933 for (;curd > -1;cur--,curd--) {
7934 if (cur < SLAB_FIRST(slab)) {
7936 cur = SLAB_LAST(slab);
7938 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
7939 REPORT_CODE_OFF + 2 + depth * 2,"",
7940 curd, PL_reg_name[cur->resume_state],
7941 (curyes == cur) ? "yes" : ""
7944 curyes = cur->u.yes.prev_yes_state;
7947 DEBUG_STATE_pp("push")
7950 st->locinput = locinput;
7952 if (newst > SLAB_LAST(PL_regmatch_slab))
7953 newst = S_push_slab(aTHX);
7954 PL_regmatch_state = newst;
7956 locinput = pushinput;
7964 * We get here only if there's trouble -- normally "case END" is
7965 * the terminating point.
7967 Perl_croak(aTHX_ "corrupted regexp pointers");
7970 NOT_REACHED; /* NOTREACHED */
7974 /* we have successfully completed a subexpression, but we must now
7975 * pop to the state marked by yes_state and continue from there */
7976 assert(st != yes_state);
7978 while (st != yes_state) {
7980 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7981 PL_regmatch_slab = PL_regmatch_slab->prev;
7982 st = SLAB_LAST(PL_regmatch_slab);
7986 DEBUG_STATE_pp("pop (no final)");
7988 DEBUG_STATE_pp("pop (yes)");
7994 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
7995 || yes_state > SLAB_LAST(PL_regmatch_slab))
7997 /* not in this slab, pop slab */
7998 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
7999 PL_regmatch_slab = PL_regmatch_slab->prev;
8000 st = SLAB_LAST(PL_regmatch_slab);
8002 depth -= (st - yes_state);
8005 yes_state = st->u.yes.prev_yes_state;
8006 PL_regmatch_state = st;
8009 locinput= st->locinput;
8010 state_num = st->resume_state + no_final;
8011 goto reenter_switch;
8014 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
8015 PL_colors[4], PL_colors[5]));
8017 if (reginfo->info_aux_eval) {
8018 /* each successfully executed (?{...}) block does the equivalent of
8019 * local $^R = do {...}
8020 * When popping the save stack, all these locals would be undone;
8021 * bypass this by setting the outermost saved $^R to the latest
8023 /* I dont know if this is needed or works properly now.
8024 * see code related to PL_replgv elsewhere in this file.
8027 if (oreplsv != GvSV(PL_replgv))
8028 sv_setsv(oreplsv, GvSV(PL_replgv));
8035 PerlIO_printf(Perl_debug_log,
8036 "%*s %sfailed...%s\n",
8037 REPORT_CODE_OFF+depth*2, "",
8038 PL_colors[4], PL_colors[5])
8050 /* there's a previous state to backtrack to */
8052 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8053 PL_regmatch_slab = PL_regmatch_slab->prev;
8054 st = SLAB_LAST(PL_regmatch_slab);
8056 PL_regmatch_state = st;
8057 locinput= st->locinput;
8059 DEBUG_STATE_pp("pop");
8061 if (yes_state == st)
8062 yes_state = st->u.yes.prev_yes_state;
8064 state_num = st->resume_state + 1; /* failure = success + 1 */
8065 goto reenter_switch;
8070 if (rex->intflags & PREGf_VERBARG_SEEN) {
8071 SV *sv_err = get_sv("REGERROR", 1);
8072 SV *sv_mrk = get_sv("REGMARK", 1);
8074 sv_commit = &PL_sv_no;
8076 sv_yes_mark = &PL_sv_yes;
8079 sv_commit = &PL_sv_yes;
8080 sv_yes_mark = &PL_sv_no;
8084 sv_setsv(sv_err, sv_commit);
8085 sv_setsv(sv_mrk, sv_yes_mark);
8089 if (last_pushed_cv) {
8092 PERL_UNUSED_VAR(SP);
8095 assert(!result || locinput - reginfo->strbeg >= 0);
8096 return result ? locinput - reginfo->strbeg : -1;
8100 - regrepeat - repeatedly match something simple, report how many
8102 * What 'simple' means is a node which can be the operand of a quantifier like
8105 * startposp - pointer a pointer to the start position. This is updated
8106 * to point to the byte following the highest successful
8108 * p - the regnode to be repeatedly matched against.
8109 * reginfo - struct holding match state, such as strend
8110 * max - maximum number of things to match.
8111 * depth - (for debugging) backtracking depth.
8114 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8115 regmatch_info *const reginfo, I32 max, int depth)
8117 char *scan; /* Pointer to current position in target string */
8119 char *loceol = reginfo->strend; /* local version */
8120 I32 hardcount = 0; /* How many matches so far */
8121 bool utf8_target = reginfo->is_utf8_target;
8122 unsigned int to_complement = 0; /* Invert the result? */
8124 _char_class_number classnum;
8126 PERL_UNUSED_ARG(depth);
8129 PERL_ARGS_ASSERT_REGREPEAT;
8132 if (max == REG_INFTY)
8134 else if (! utf8_target && loceol - scan > max)
8135 loceol = scan + max;
8137 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8138 * to the maximum of how far we should go in it (leaving it set to the real
8139 * end, if the maximum permissible would take us beyond that). This allows
8140 * us to make the loop exit condition that we haven't gone past <loceol> to
8141 * also mean that we haven't exceeded the max permissible count, saving a
8142 * test each time through the loop. But it assumes that the OP matches a
8143 * single byte, which is true for most of the OPs below when applied to a
8144 * non-UTF-8 target. Those relatively few OPs that don't have this
8145 * characteristic will have to compensate.
8147 * There is no adjustment for UTF-8 targets, as the number of bytes per
8148 * character varies. OPs will have to test both that the count is less
8149 * than the max permissible (using <hardcount> to keep track), and that we
8150 * are still within the bounds of the string (using <loceol>. A few OPs
8151 * match a single byte no matter what the encoding. They can omit the max
8152 * test if, for the UTF-8 case, they do the adjustment that was skipped
8155 * Thus, the code above sets things up for the common case; and exceptional
8156 * cases need extra work; the common case is to make sure <scan> doesn't
8157 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8158 * count doesn't exceed the maximum permissible */
8163 while (scan < loceol && hardcount < max && *scan != '\n') {
8164 scan += UTF8SKIP(scan);
8168 while (scan < loceol && *scan != '\n')
8174 while (scan < loceol && hardcount < max) {
8175 scan += UTF8SKIP(scan);
8183 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8184 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8185 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8189 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8193 /* Can use a simple loop if the pattern char to match on is invariant
8194 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8195 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8196 * true iff it doesn't matter if the argument is in UTF-8 or not */
8197 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8198 if (utf8_target && loceol - scan > max) {
8199 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8200 * since here, to match at all, 1 char == 1 byte */
8201 loceol = scan + max;
8203 while (scan < loceol && UCHARAT(scan) == c) {
8207 else if (reginfo->is_utf8_pat) {
8209 STRLEN scan_char_len;
8211 /* When both target and pattern are UTF-8, we have to do
8213 while (hardcount < max
8215 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8216 && memEQ(scan, STRING(p), scan_char_len))
8218 scan += scan_char_len;
8222 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8224 /* Target isn't utf8; convert the character in the UTF-8
8225 * pattern to non-UTF8, and do a simple loop */
8226 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8227 while (scan < loceol && UCHARAT(scan) == c) {
8230 } /* else pattern char is above Latin1, can't possibly match the
8235 /* Here, the string must be utf8; pattern isn't, and <c> is
8236 * different in utf8 than not, so can't compare them directly.
8237 * Outside the loop, find the two utf8 bytes that represent c, and
8238 * then look for those in sequence in the utf8 string */
8239 U8 high = UTF8_TWO_BYTE_HI(c);
8240 U8 low = UTF8_TWO_BYTE_LO(c);
8242 while (hardcount < max
8243 && scan + 1 < loceol
8244 && UCHARAT(scan) == high
8245 && UCHARAT(scan + 1) == low)
8253 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8254 assert(! reginfo->is_utf8_pat);
8257 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8261 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8262 utf8_flags = FOLDEQ_LOCALE;
8265 case EXACTF: /* This node only generated for non-utf8 patterns */
8266 assert(! reginfo->is_utf8_pat);
8271 if (! utf8_target) {
8274 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8275 | FOLDEQ_S2_FOLDS_SANE;
8280 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8284 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8286 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8288 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8291 if (c1 == CHRTEST_VOID) {
8292 /* Use full Unicode fold matching */
8293 char *tmpeol = reginfo->strend;
8294 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8295 while (hardcount < max
8296 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8297 STRING(p), NULL, pat_len,
8298 reginfo->is_utf8_pat, utf8_flags))
8301 tmpeol = reginfo->strend;
8305 else if (utf8_target) {
8307 while (scan < loceol
8309 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8311 scan += UTF8SKIP(scan);
8316 while (scan < loceol
8318 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8319 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8321 scan += UTF8SKIP(scan);
8326 else if (c1 == c2) {
8327 while (scan < loceol && UCHARAT(scan) == c1) {
8332 while (scan < loceol &&
8333 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8342 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8344 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8345 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8351 while (hardcount < max
8353 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8355 scan += UTF8SKIP(scan);
8359 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
8364 /* The argument (FLAGS) to all the POSIX node types is the class number */
8371 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8372 if (! utf8_target) {
8373 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8379 while (hardcount < max && scan < loceol
8380 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8383 scan += UTF8SKIP(scan);
8396 if (utf8_target && loceol - scan > max) {
8398 /* We didn't adjust <loceol> at the beginning of this routine
8399 * because is UTF-8, but it is actually ok to do so, since here, to
8400 * match, 1 char == 1 byte. */
8401 loceol = scan + max;
8403 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8416 if (! utf8_target) {
8417 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8423 /* The complement of something that matches only ASCII matches all
8424 * non-ASCII, plus everything in ASCII that isn't in the class. */
8425 while (hardcount < max && scan < loceol
8426 && (! isASCII_utf8(scan)
8427 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8429 scan += UTF8SKIP(scan);
8440 if (! utf8_target) {
8441 while (scan < loceol && to_complement
8442 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8449 classnum = (_char_class_number) FLAGS(p);
8450 if (classnum < _FIRST_NON_SWASH_CC) {
8452 /* Here, a swash is needed for above-Latin1 code points.
8453 * Process as many Latin1 code points using the built-in rules.
8454 * Go to another loop to finish processing upon encountering
8455 * the first Latin1 code point. We could do that in this loop
8456 * as well, but the other way saves having to test if the swash
8457 * has been loaded every time through the loop: extra space to
8459 while (hardcount < max && scan < loceol) {
8460 if (UTF8_IS_INVARIANT(*scan)) {
8461 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8468 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8469 if (! (to_complement
8470 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
8479 goto found_above_latin1;
8486 /* For these character classes, the knowledge of how to handle
8487 * every code point is compiled in to Perl via a macro. This
8488 * code is written for making the loops as tight as possible.
8489 * It could be refactored to save space instead */
8491 case _CC_ENUM_SPACE:
8492 while (hardcount < max
8494 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8496 scan += UTF8SKIP(scan);
8500 case _CC_ENUM_BLANK:
8501 while (hardcount < max
8503 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8505 scan += UTF8SKIP(scan);
8509 case _CC_ENUM_XDIGIT:
8510 while (hardcount < max
8512 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8514 scan += UTF8SKIP(scan);
8518 case _CC_ENUM_VERTSPACE:
8519 while (hardcount < max
8521 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8523 scan += UTF8SKIP(scan);
8527 case _CC_ENUM_CNTRL:
8528 while (hardcount < max
8530 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8532 scan += UTF8SKIP(scan);
8537 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8543 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
8545 /* Load the swash if not already present */
8546 if (! PL_utf8_swash_ptrs[classnum]) {
8547 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8548 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8552 PL_XPosix_ptrs[classnum], &flags);
8555 while (hardcount < max && scan < loceol
8556 && to_complement ^ cBOOL(_generic_utf8(
8559 swash_fetch(PL_utf8_swash_ptrs[classnum],
8563 scan += UTF8SKIP(scan);
8570 while (hardcount < max && scan < loceol &&
8571 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8576 /* LNBREAK can match one or two latin chars, which is ok, but we
8577 * have to use hardcount in this situation, and throw away the
8578 * adjustment to <loceol> done before the switch statement */
8579 loceol = reginfo->strend;
8580 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8589 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8603 /* These are all 0 width, so match right here or not at all. */
8607 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8609 NOT_REACHED; /* NOTREACHED */
8616 c = scan - *startposp;
8620 GET_RE_DEBUG_FLAGS_DECL;
8622 SV * const prop = sv_newmortal();
8623 regprop(prog, prop, p, reginfo, NULL);
8624 PerlIO_printf(Perl_debug_log,
8625 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
8626 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8634 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8636 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
8637 create a copy so that changes the caller makes won't change the shared one.
8638 If <altsvp> is non-null, will return NULL in it, for back-compat.
8641 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8643 PERL_ARGS_ASSERT_REGCLASS_SWASH;
8649 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8652 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8655 - reginclass - determine if a character falls into a character class
8657 n is the ANYOF-type regnode
8658 p is the target string
8659 p_end points to one byte beyond the end of the target string
8660 utf8_target tells whether p is in UTF-8.
8662 Returns true if matched; false otherwise.
8664 Note that this can be a synthetic start class, a combination of various
8665 nodes, so things you think might be mutually exclusive, such as locale,
8666 aren't. It can match both locale and non-locale
8671 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8674 const char flags = ANYOF_FLAGS(n);
8678 PERL_ARGS_ASSERT_REGINCLASS;
8680 /* If c is not already the code point, get it. Note that
8681 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8682 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8684 c = utf8n_to_uvchr(p, p_end - p, &c_len,
8685 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8686 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8687 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8688 * UTF8_ALLOW_FFFF */
8689 if (c_len == (STRLEN)-1)
8690 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8691 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
8692 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8696 /* If this character is potentially in the bitmap, check it */
8697 if (c < NUM_ANYOF_CODE_POINTS) {
8698 if (ANYOF_BITMAP_TEST(n, c))
8701 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
8708 else if (flags & ANYOF_LOCALE_FLAGS) {
8709 if ((flags & ANYOFL_FOLD)
8711 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
8715 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
8719 /* The data structure is arranged so bits 0, 2, 4, ... are set
8720 * if the class includes the Posix character class given by
8721 * bit/2; and 1, 3, 5, ... are set if the class includes the
8722 * complemented Posix class given by int(bit/2). So we loop
8723 * through the bits, each time changing whether we complement
8724 * the result or not. Suppose for the sake of illustration
8725 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
8726 * is set, it means there is a match for this ANYOF node if the
8727 * character is in the class given by the expression (0 / 2 = 0
8728 * = \w). If it is in that class, isFOO_lc() will return 1,
8729 * and since 'to_complement' is 0, the result will stay TRUE,
8730 * and we exit the loop. Suppose instead that bit 0 is 0, but
8731 * bit 1 is 1. That means there is a match if the character
8732 * matches \W. We won't bother to call isFOO_lc() on bit 0,
8733 * but will on bit 1. On the second iteration 'to_complement'
8734 * will be 1, so the exclusive or will reverse things, so we
8735 * are testing for \W. On the third iteration, 'to_complement'
8736 * will be 0, and we would be testing for \s; the fourth
8737 * iteration would test for \S, etc.
8739 * Note that this code assumes that all the classes are closed
8740 * under folding. For example, if a character matches \w, then
8741 * its fold does too; and vice versa. This should be true for
8742 * any well-behaved locale for all the currently defined Posix
8743 * classes, except for :lower: and :upper:, which are handled
8744 * by the pseudo-class :cased: which matches if either of the
8745 * other two does. To get rid of this assumption, an outer
8746 * loop could be used below to iterate over both the source
8747 * character, and its fold (if different) */
8750 int to_complement = 0;
8752 while (count < ANYOF_MAX) {
8753 if (ANYOF_POSIXL_TEST(n, count)
8754 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
8767 /* If the bitmap didn't (or couldn't) match, and something outside the
8768 * bitmap could match, try that. */
8770 if (c >= NUM_ANYOF_CODE_POINTS
8771 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
8773 match = TRUE; /* Everything above the bitmap matches */
8775 /* Here doesn't match everything above the bitmap. If there is
8776 * some information available beyond the bitmap, we may find a
8777 * match in it. If so, this is most likely because the code point
8778 * is outside the bitmap range. But rarely, it could be because of
8779 * some other reason. If so, various flags are set to indicate
8780 * this possibility. On ANYOFD nodes, there may be matches that
8781 * happen only when the target string is UTF-8; or for other node
8782 * types, because runtime lookup is needed, regardless of the
8783 * UTF-8ness of the target string. Finally, under /il, there may
8784 * be some matches only possible if the locale is a UTF-8 one. */
8785 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
8786 && ( c >= NUM_ANYOF_CODE_POINTS
8787 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
8788 && ( UNLIKELY(OP(n) != ANYOFD)
8789 || (utf8_target && ! isASCII_uni(c)
8790 # if NUM_ANYOF_CODE_POINTS > 256
8794 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
8795 && IN_UTF8_CTYPE_LOCALE)))
8797 SV* only_utf8_locale = NULL;
8798 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
8799 &only_utf8_locale, NULL);
8805 } else { /* Convert to utf8 */
8806 utf8_p = utf8_buffer;
8807 append_utf8_from_native_byte(*p, &utf8_p);
8808 utf8_p = utf8_buffer;
8811 if (swash_fetch(sw, utf8_p, TRUE)) {
8815 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
8816 match = _invlist_contains_cp(only_utf8_locale, c);
8820 if (UNICODE_IS_SUPER(c)
8822 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
8824 && ckWARN_d(WARN_NON_UNICODE))
8826 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
8827 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
8831 #if ANYOF_INVERT != 1
8832 /* Depending on compiler optimization cBOOL takes time, so if don't have to
8834 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
8837 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
8838 return (flags & ANYOF_INVERT) ^ match;
8842 S_reghop3(U8 *s, SSize_t off, const U8* lim)
8844 /* return the position 'off' UTF-8 characters away from 's', forward if
8845 * 'off' >= 0, backwards if negative. But don't go outside of position
8846 * 'lim', which better be < s if off < 0 */
8848 PERL_ARGS_ASSERT_REGHOP3;
8851 while (off-- && s < lim) {
8852 /* XXX could check well-formedness here */
8857 while (off++ && s > lim) {
8859 if (UTF8_IS_CONTINUED(*s)) {
8860 while (s > lim && UTF8_IS_CONTINUATION(*s))
8862 if (! UTF8_IS_START(*s)) {
8863 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
8866 /* XXX could check well-formedness here */
8873 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
8875 PERL_ARGS_ASSERT_REGHOP4;
8878 while (off-- && s < rlim) {
8879 /* XXX could check well-formedness here */
8884 while (off++ && s > llim) {
8886 if (UTF8_IS_CONTINUED(*s)) {
8887 while (s > llim && UTF8_IS_CONTINUATION(*s))
8889 if (! UTF8_IS_START(*s)) {
8890 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
8893 /* XXX could check well-formedness here */
8899 /* like reghop3, but returns NULL on overrun, rather than returning last
8903 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
8905 PERL_ARGS_ASSERT_REGHOPMAYBE3;
8908 while (off-- && s < lim) {
8909 /* XXX could check well-formedness here */
8916 while (off++ && s > lim) {
8918 if (UTF8_IS_CONTINUED(*s)) {
8919 while (s > lim && UTF8_IS_CONTINUATION(*s))
8921 if (! UTF8_IS_START(*s)) {
8922 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
8925 /* XXX could check well-formedness here */
8934 /* when executing a regex that may have (?{}), extra stuff needs setting
8935 up that will be visible to the called code, even before the current
8936 match has finished. In particular:
8938 * $_ is localised to the SV currently being matched;
8939 * pos($_) is created if necessary, ready to be updated on each call-out
8941 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
8942 isn't set until the current pattern is successfully finished), so that
8943 $1 etc of the match-so-far can be seen;
8944 * save the old values of subbeg etc of the current regex, and set then
8945 to the current string (again, this is normally only done at the end
8950 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
8953 regexp *const rex = ReANY(reginfo->prog);
8954 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
8956 eval_state->rex = rex;
8959 /* Make $_ available to executed code. */
8960 if (reginfo->sv != DEFSV) {
8962 DEFSV_set(reginfo->sv);
8965 if (!(mg = mg_find_mglob(reginfo->sv))) {
8966 /* prepare for quick setting of pos */
8967 mg = sv_magicext_mglob(reginfo->sv);
8970 eval_state->pos_magic = mg;
8971 eval_state->pos = mg->mg_len;
8972 eval_state->pos_flags = mg->mg_flags;
8975 eval_state->pos_magic = NULL;
8977 if (!PL_reg_curpm) {
8978 /* PL_reg_curpm is a fake PMOP that we can attach the current
8979 * regex to and point PL_curpm at, so that $1 et al are visible
8980 * within a /(?{})/. It's just allocated once per interpreter the
8981 * first time its needed */
8982 Newxz(PL_reg_curpm, 1, PMOP);
8985 SV* const repointer = &PL_sv_undef;
8986 /* this regexp is also owned by the new PL_reg_curpm, which
8987 will try to free it. */
8988 av_push(PL_regex_padav, repointer);
8989 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
8990 PL_regex_pad = AvARRAY(PL_regex_padav);
8994 SET_reg_curpm(reginfo->prog);
8995 eval_state->curpm = PL_curpm;
8996 PL_curpm = PL_reg_curpm;
8997 if (RXp_MATCH_COPIED(rex)) {
8998 /* Here is a serious problem: we cannot rewrite subbeg,
8999 since it may be needed if this match fails. Thus
9000 $` inside (?{}) could fail... */
9001 eval_state->subbeg = rex->subbeg;
9002 eval_state->sublen = rex->sublen;
9003 eval_state->suboffset = rex->suboffset;
9004 eval_state->subcoffset = rex->subcoffset;
9006 eval_state->saved_copy = rex->saved_copy;
9008 RXp_MATCH_COPIED_off(rex);
9011 eval_state->subbeg = NULL;
9012 rex->subbeg = (char *)reginfo->strbeg;
9014 rex->subcoffset = 0;
9015 rex->sublen = reginfo->strend - reginfo->strbeg;
9019 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9022 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9024 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9025 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9028 Safefree(aux->poscache);
9032 /* undo the effects of S_setup_eval_state() */
9034 if (eval_state->subbeg) {
9035 regexp * const rex = eval_state->rex;
9036 rex->subbeg = eval_state->subbeg;
9037 rex->sublen = eval_state->sublen;
9038 rex->suboffset = eval_state->suboffset;
9039 rex->subcoffset = eval_state->subcoffset;
9041 rex->saved_copy = eval_state->saved_copy;
9043 RXp_MATCH_COPIED_on(rex);
9045 if (eval_state->pos_magic)
9047 eval_state->pos_magic->mg_len = eval_state->pos;
9048 eval_state->pos_magic->mg_flags =
9049 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9050 | (eval_state->pos_flags & MGf_BYTES);
9053 PL_curpm = eval_state->curpm;
9056 PL_regmatch_state = aux->old_regmatch_state;
9057 PL_regmatch_slab = aux->old_regmatch_slab;
9059 /* free all slabs above current one - this must be the last action
9060 * of this function, as aux and eval_state are allocated within
9061 * slabs and may be freed here */
9063 s = PL_regmatch_slab->next;
9065 PL_regmatch_slab->next = NULL;
9067 regmatch_slab * const osl = s;
9076 S_to_utf8_substr(pTHX_ regexp *prog)
9078 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9079 * on the converted value */
9083 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9086 if (prog->substrs->data[i].substr
9087 && !prog->substrs->data[i].utf8_substr) {
9088 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9089 prog->substrs->data[i].utf8_substr = sv;
9090 sv_utf8_upgrade(sv);
9091 if (SvVALID(prog->substrs->data[i].substr)) {
9092 if (SvTAIL(prog->substrs->data[i].substr)) {
9093 /* Trim the trailing \n that fbm_compile added last
9095 SvCUR_set(sv, SvCUR(sv) - 1);
9096 /* Whilst this makes the SV technically "invalid" (as its
9097 buffer is no longer followed by "\0") when fbm_compile()
9098 adds the "\n" back, a "\0" is restored. */
9099 fbm_compile(sv, FBMcf_TAIL);
9103 if (prog->substrs->data[i].substr == prog->check_substr)
9104 prog->check_utf8 = sv;
9110 S_to_byte_substr(pTHX_ regexp *prog)
9112 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9113 * on the converted value; returns FALSE if can't be converted. */
9117 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9120 if (prog->substrs->data[i].utf8_substr
9121 && !prog->substrs->data[i].substr) {
9122 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9123 if (! sv_utf8_downgrade(sv, TRUE)) {
9126 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9127 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9128 /* Trim the trailing \n that fbm_compile added last
9130 SvCUR_set(sv, SvCUR(sv) - 1);
9131 fbm_compile(sv, FBMcf_TAIL);
9135 prog->substrs->data[i].substr = sv;
9136 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9137 prog->check_substr = sv;
9145 * ex: set ts=8 sts=4 sw=4 et: