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
40 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
41 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
44 * pregcomp and pregexec -- regsub and regerror are not used in perl
46 * Copyright (c) 1986 by University of Toronto.
47 * Written by Henry Spencer. Not derived from licensed software.
49 * Permission is granted to anyone to use this software for any
50 * purpose on any computer system, and to redistribute it freely,
51 * subject to the following restrictions:
53 * 1. The author is not responsible for the consequences of use of
54 * this software, no matter how awful, even if they arise
57 * 2. The origin of this software must not be misrepresented, either
58 * by explicit claim or by omission.
60 * 3. Altered versions must be plainly marked as such, and must not
61 * be misrepresented as being the original software.
63 **** Alterations to Henry's code are...
65 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
66 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
67 **** by Larry Wall and others
69 **** You may distribute under the terms of either the GNU General Public
70 **** License or the Artistic License, as specified in the README file.
72 * Beware that some of this code is subtly aware of the way operator
73 * precedence is structured in regular expressions. Serious changes in
74 * regular-expression syntax might require a total rethink.
77 #define PERL_IN_REGEXEC_C
80 #ifdef PERL_IN_XSUB_RE
86 #include "inline_invlist.c"
87 #include "unicode_constants.h"
90 /* At least one required character in the target string is expressible only in
92 static const char* const non_utf8_target_but_utf8_required
93 = "Can't match, because target string needs to be in UTF-8\n";
96 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
97 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
101 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
104 #define STATIC static
107 /* Valid only for non-utf8 strings: avoids the reginclass
108 * call if there are no complications: i.e., if everything matchable is
109 * straight forward in the bitmap */
110 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
111 : ANYOF_BITMAP_TEST(p,*(c)))
117 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
118 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
120 #define HOPc(pos,off) \
121 (char *)(reginfo->is_utf8_target \
122 ? reghop3((U8*)pos, off, \
123 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
126 #define HOPBACKc(pos, off) \
127 (char*)(reginfo->is_utf8_target \
128 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
129 : (pos - off >= reginfo->strbeg) \
133 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
134 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
136 /* lim must be +ve. Returns NULL on overshoot */
137 #define HOPMAYBE3(pos,off,lim) \
138 (reginfo->is_utf8_target \
139 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
140 : ((U8*)pos + off <= lim) \
144 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
145 * off must be >=0; args should be vars rather than expressions */
146 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
147 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
148 : (U8*)((pos + off) > lim ? lim : (pos + off)))
150 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
151 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
153 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
155 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
156 #define NEXTCHR_IS_EOS (nextchr < 0)
158 #define SET_nextchr \
159 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
161 #define SET_locinput(p) \
166 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
168 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
169 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
170 1, 0, invlist, &flags); \
175 /* If in debug mode, we test that a known character properly matches */
177 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
180 utf8_char_in_property) \
181 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
182 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
184 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
187 utf8_char_in_property) \
188 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
191 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
192 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
194 PL_XPosix_ptrs[_CC_WORDCHAR], \
195 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
197 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
198 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
200 /* for use after a quantifier and before an EXACT-like node -- japhy */
201 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
203 * NOTE that *nothing* that affects backtracking should be in here, specifically
204 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
205 * node that is in between two EXACT like nodes when ascertaining what the required
206 * "follow" character is. This should probably be moved to regex compile time
207 * although it may be done at run time beause of the REF possibility - more
208 * investigation required. -- demerphq
210 #define JUMPABLE(rn) ( \
212 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
214 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
215 OP(rn) == PLUS || OP(rn) == MINMOD || \
217 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
219 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
221 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
224 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
225 we don't need this definition. XXX These are now out-of-sync*/
226 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
227 #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 )
228 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
231 /* ... so we use this as its faster. */
232 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
233 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
234 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
235 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
240 Search for mandatory following text node; for lookahead, the text must
241 follow but for lookbehind (rn->flags != 0) we skip to the next step.
243 #define FIND_NEXT_IMPT(rn) STMT_START { \
244 while (JUMPABLE(rn)) { \
245 const OPCODE type = OP(rn); \
246 if (type == SUSPEND || PL_regkind[type] == CURLY) \
247 rn = NEXTOPER(NEXTOPER(rn)); \
248 else if (type == PLUS) \
250 else if (type == IFMATCH) \
251 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
252 else rn += NEXT_OFF(rn); \
256 #define SLAB_FIRST(s) (&(s)->states[0])
257 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
259 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
260 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
261 static regmatch_state * S_push_slab(pTHX);
263 #define REGCP_PAREN_ELEMS 3
264 #define REGCP_OTHER_ELEMS 3
265 #define REGCP_FRAME_ELEMS 1
266 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
267 * are needed for the regexp context stack bookkeeping. */
270 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
272 const int retval = PL_savestack_ix;
273 const int paren_elems_to_push =
274 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
275 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
276 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
278 GET_RE_DEBUG_FLAGS_DECL;
280 PERL_ARGS_ASSERT_REGCPPUSH;
282 if (paren_elems_to_push < 0)
283 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
284 (int)paren_elems_to_push, (int)maxopenparen,
285 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
287 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
288 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
289 " out of range (%lu-%ld)",
291 (unsigned long)maxopenparen,
294 SSGROW(total_elems + REGCP_FRAME_ELEMS);
297 if ((int)maxopenparen > (int)parenfloor)
298 PerlIO_printf(Perl_debug_log,
299 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
304 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
305 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
306 SSPUSHIV(rex->offs[p].end);
307 SSPUSHIV(rex->offs[p].start);
308 SSPUSHINT(rex->offs[p].start_tmp);
309 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
310 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
312 (IV)rex->offs[p].start,
313 (IV)rex->offs[p].start_tmp,
317 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
318 SSPUSHINT(maxopenparen);
319 SSPUSHINT(rex->lastparen);
320 SSPUSHINT(rex->lastcloseparen);
321 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
326 /* These are needed since we do not localize EVAL nodes: */
327 #define REGCP_SET(cp) \
329 PerlIO_printf(Perl_debug_log, \
330 " Setting an EVAL scope, savestack=%"IVdf"\n", \
331 (IV)PL_savestack_ix)); \
334 #define REGCP_UNWIND(cp) \
336 if (cp != PL_savestack_ix) \
337 PerlIO_printf(Perl_debug_log, \
338 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
339 (IV)(cp), (IV)PL_savestack_ix)); \
342 #define UNWIND_PAREN(lp, lcp) \
343 for (n = rex->lastparen; n > lp; n--) \
344 rex->offs[n].end = -1; \
345 rex->lastparen = n; \
346 rex->lastcloseparen = lcp;
350 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
354 GET_RE_DEBUG_FLAGS_DECL;
356 PERL_ARGS_ASSERT_REGCPPOP;
358 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
360 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
361 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
362 rex->lastcloseparen = SSPOPINT;
363 rex->lastparen = SSPOPINT;
364 *maxopenparen_p = SSPOPINT;
366 i -= REGCP_OTHER_ELEMS;
367 /* Now restore the parentheses context. */
369 if (i || rex->lastparen + 1 <= rex->nparens)
370 PerlIO_printf(Perl_debug_log,
371 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
376 paren = *maxopenparen_p;
377 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
379 rex->offs[paren].start_tmp = SSPOPINT;
380 rex->offs[paren].start = SSPOPIV;
382 if (paren <= rex->lastparen)
383 rex->offs[paren].end = tmps;
384 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
385 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
387 (IV)rex->offs[paren].start,
388 (IV)rex->offs[paren].start_tmp,
389 (IV)rex->offs[paren].end,
390 (paren > rex->lastparen ? "(skipped)" : ""));
395 /* It would seem that the similar code in regtry()
396 * already takes care of this, and in fact it is in
397 * a better location to since this code can #if 0-ed out
398 * but the code in regtry() is needed or otherwise tests
399 * requiring null fields (pat.t#187 and split.t#{13,14}
400 * (as of patchlevel 7877) will fail. Then again,
401 * this code seems to be necessary or otherwise
402 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
403 * --jhi updated by dapm */
404 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
405 if (i > *maxopenparen_p)
406 rex->offs[i].start = -1;
407 rex->offs[i].end = -1;
408 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
409 " \\%"UVuf": %s ..-1 undeffing\n",
411 (i > *maxopenparen_p) ? "-1" : " "
417 /* restore the parens and associated vars at savestack position ix,
418 * but without popping the stack */
421 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
423 I32 tmpix = PL_savestack_ix;
424 PL_savestack_ix = ix;
425 regcppop(rex, maxopenparen_p);
426 PL_savestack_ix = tmpix;
429 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
432 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
434 /* Returns a boolean as to whether or not 'character' is a member of the
435 * Posix character class given by 'classnum' that should be equivalent to a
436 * value in the typedef '_char_class_number'.
438 * Ideally this could be replaced by a just an array of function pointers
439 * to the C library functions that implement the macros this calls.
440 * However, to compile, the precise function signatures are required, and
441 * these may vary from platform to to platform. To avoid having to figure
442 * out what those all are on each platform, I (khw) am using this method,
443 * which adds an extra layer of function call overhead (unless the C
444 * optimizer strips it away). But we don't particularly care about
445 * performance with locales anyway. */
447 switch ((_char_class_number) classnum) {
448 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
449 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
450 case _CC_ENUM_ASCII: return isASCII_LC(character);
451 case _CC_ENUM_BLANK: return isBLANK_LC(character);
452 case _CC_ENUM_CASED: return isLOWER_LC(character)
453 || isUPPER_LC(character);
454 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
455 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
456 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
457 case _CC_ENUM_LOWER: return isLOWER_LC(character);
458 case _CC_ENUM_PRINT: return isPRINT_LC(character);
459 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
460 case _CC_ENUM_SPACE: return isSPACE_LC(character);
461 case _CC_ENUM_UPPER: return isUPPER_LC(character);
462 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
463 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
464 default: /* VERTSPACE should never occur in locales */
465 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
468 NOT_REACHED; /* NOTREACHED */
473 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
475 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
476 * 'character' is a member of the Posix character class given by 'classnum'
477 * that should be equivalent to a value in the typedef
478 * '_char_class_number'.
480 * This just calls isFOO_lc on the code point for the character if it is in
481 * the range 0-255. Outside that range, all characters use Unicode
482 * rules, ignoring any locale. So use the Unicode function if this class
483 * requires a swash, and use the Unicode macro otherwise. */
485 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
487 if (UTF8_IS_INVARIANT(*character)) {
488 return isFOO_lc(classnum, *character);
490 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
491 return isFOO_lc(classnum,
492 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
495 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
497 if (classnum < _FIRST_NON_SWASH_CC) {
499 /* Initialize the swash unless done already */
500 if (! PL_utf8_swash_ptrs[classnum]) {
501 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
502 PL_utf8_swash_ptrs[classnum] =
503 _core_swash_init("utf8",
506 PL_XPosix_ptrs[classnum], &flags);
509 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
511 TRUE /* is UTF */ ));
514 switch ((_char_class_number) classnum) {
515 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
516 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
517 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
518 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
522 return FALSE; /* Things like CNTRL are always below 256 */
526 * pregexec and friends
529 #ifndef PERL_IN_XSUB_RE
531 - pregexec - match a regexp against a string
534 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
535 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
536 /* stringarg: the point in the string at which to begin matching */
537 /* strend: pointer to null at end of string */
538 /* strbeg: real beginning of string */
539 /* minend: end of match must be >= minend bytes after stringarg. */
540 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
541 * itself is accessed via the pointers above */
542 /* nosave: For optimizations. */
544 PERL_ARGS_ASSERT_PREGEXEC;
547 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
548 nosave ? 0 : REXEC_COPY_STR);
554 /* re_intuit_start():
556 * Based on some optimiser hints, try to find the earliest position in the
557 * string where the regex could match.
559 * rx: the regex to match against
560 * sv: the SV being matched: only used for utf8 flag; the string
561 * itself is accessed via the pointers below. Note that on
562 * something like an overloaded SV, SvPOK(sv) may be false
563 * and the string pointers may point to something unrelated to
565 * strbeg: real beginning of string
566 * strpos: the point in the string at which to begin matching
567 * strend: pointer to the byte following the last char of the string
568 * flags currently unused; set to 0
569 * data: currently unused; set to NULL
571 * The basic idea of re_intuit_start() is to use some known information
572 * about the pattern, namely:
574 * a) the longest known anchored substring (i.e. one that's at a
575 * constant offset from the beginning of the pattern; but not
576 * necessarily at a fixed offset from the beginning of the
578 * b) the longest floating substring (i.e. one that's not at a constant
579 * offset from the beginning of the pattern);
580 * c) Whether the pattern is anchored to the string; either
581 * an absolute anchor: /^../, or anchored to \n: /^.../m,
582 * or anchored to pos(): /\G/;
583 * d) A start class: a real or synthetic character class which
584 * represents which characters are legal at the start of the pattern;
586 * to either quickly reject the match, or to find the earliest position
587 * within the string at which the pattern might match, thus avoiding
588 * running the full NFA engine at those earlier locations, only to
589 * eventually fail and retry further along.
591 * Returns NULL if the pattern can't match, or returns the address within
592 * the string which is the earliest place the match could occur.
594 * The longest of the anchored and floating substrings is called 'check'
595 * and is checked first. The other is called 'other' and is checked
596 * second. The 'other' substring may not be present. For example,
598 * /(abc|xyz)ABC\d{0,3}DEFG/
602 * check substr (float) = "DEFG", offset 6..9 chars
603 * other substr (anchored) = "ABC", offset 3..3 chars
606 * Be aware that during the course of this function, sometimes 'anchored'
607 * refers to a substring being anchored relative to the start of the
608 * pattern, and sometimes to the pattern itself being anchored relative to
609 * the string. For example:
611 * /\dabc/: "abc" is anchored to the pattern;
612 * /^\dabc/: "abc" is anchored to the pattern and the string;
613 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
614 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
615 * but the pattern is anchored to the string.
619 Perl_re_intuit_start(pTHX_
622 const char * const strbeg,
626 re_scream_pos_data *data)
628 struct regexp *const prog = ReANY(rx);
629 SSize_t start_shift = prog->check_offset_min;
630 /* Should be nonnegative! */
631 SSize_t end_shift = 0;
632 /* current lowest pos in string where the regex can start matching */
633 char *rx_origin = strpos;
635 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
636 U8 other_ix = 1 - prog->substrs->check_ix;
638 char *other_last = strpos;/* latest pos 'other' substr already checked to */
639 char *check_at = NULL; /* check substr found at this pos */
640 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
641 RXi_GET_DECL(prog,progi);
642 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
643 regmatch_info *const reginfo = ®info_buf;
644 GET_RE_DEBUG_FLAGS_DECL;
646 PERL_ARGS_ASSERT_RE_INTUIT_START;
647 PERL_UNUSED_ARG(flags);
648 PERL_UNUSED_ARG(data);
650 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
651 "Intuit: trying to determine minimum start position...\n"));
653 /* for now, assume that all substr offsets are positive. If at some point
654 * in the future someone wants to do clever things with look-behind and
655 * -ve offsets, they'll need to fix up any code in this function
656 * which uses these offsets. See the thread beginning
657 * <20140113145929.GF27210@iabyn.com>
659 assert(prog->substrs->data[0].min_offset >= 0);
660 assert(prog->substrs->data[0].max_offset >= 0);
661 assert(prog->substrs->data[1].min_offset >= 0);
662 assert(prog->substrs->data[1].max_offset >= 0);
663 assert(prog->substrs->data[2].min_offset >= 0);
664 assert(prog->substrs->data[2].max_offset >= 0);
666 /* for now, assume that if both present, that the floating substring
667 * doesn't start before the anchored substring.
668 * If you break this assumption (e.g. doing better optimisations
669 * with lookahead/behind), then you'll need to audit the code in this
670 * function carefully first
673 ! ( (prog->anchored_utf8 || prog->anchored_substr)
674 && (prog->float_utf8 || prog->float_substr))
675 || (prog->float_min_offset >= prog->anchored_offset));
677 /* byte rather than char calculation for efficiency. It fails
678 * to quickly reject some cases that can't match, but will reject
679 * them later after doing full char arithmetic */
680 if (prog->minlen > strend - strpos) {
681 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
682 " String too short...\n"));
686 RX_MATCH_UTF8_set(rx,utf8_target);
687 reginfo->is_utf8_target = cBOOL(utf8_target);
688 reginfo->info_aux = NULL;
689 reginfo->strbeg = strbeg;
690 reginfo->strend = strend;
691 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
693 /* not actually used within intuit, but zero for safety anyway */
694 reginfo->poscache_maxiter = 0;
697 if (!prog->check_utf8 && prog->check_substr)
698 to_utf8_substr(prog);
699 check = prog->check_utf8;
701 if (!prog->check_substr && prog->check_utf8) {
702 if (! to_byte_substr(prog)) {
703 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
706 check = prog->check_substr;
709 /* dump the various substring data */
710 DEBUG_OPTIMISE_MORE_r({
712 for (i=0; i<=2; i++) {
713 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
714 : prog->substrs->data[i].substr);
718 PerlIO_printf(Perl_debug_log,
719 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
720 " useful=%"IVdf" utf8=%d [%s]\n",
722 (IV)prog->substrs->data[i].min_offset,
723 (IV)prog->substrs->data[i].max_offset,
724 (IV)prog->substrs->data[i].end_shift,
731 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
733 /* ml_anch: check after \n?
735 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
736 * with /.*.../, these flags will have been added by the
738 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
739 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
741 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
742 && !(prog->intflags & PREGf_IMPLICIT);
744 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
745 /* we are only allowed to match at BOS or \G */
747 /* trivially reject if there's a BOS anchor and we're not at BOS.
749 * Note that we don't try to do a similar quick reject for
750 * \G, since generally the caller will have calculated strpos
751 * based on pos() and gofs, so the string is already correctly
752 * anchored by definition; and handling the exceptions would
753 * be too fiddly (e.g. REXEC_IGNOREPOS).
755 if ( strpos != strbeg
756 && (prog->intflags & PREGf_ANCH_SBOL))
758 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
759 " Not at start...\n"));
763 /* in the presence of an anchor, the anchored (relative to the
764 * start of the regex) substr must also be anchored relative
765 * to strpos. So quickly reject if substr isn't found there.
766 * This works for \G too, because the caller will already have
767 * subtracted gofs from pos, and gofs is the offset from the
768 * \G to the start of the regex. For example, in /.abc\Gdef/,
769 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
770 * caller will have set strpos=pos()-4; we look for the substr
771 * at position pos()-4+1, which lines up with the "a" */
773 if (prog->check_offset_min == prog->check_offset_max) {
774 /* Substring at constant offset from beg-of-str... */
775 SSize_t slen = SvCUR(check);
776 char *s = HOP3c(strpos, prog->check_offset_min, strend);
778 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
779 " Looking for check substr at fixed offset %"IVdf"...\n",
780 (IV)prog->check_offset_min));
783 /* In this case, the regex is anchored at the end too.
784 * Unless it's a multiline match, the lengths must match
785 * exactly, give or take a \n. NB: slen >= 1 since
786 * the last char of check is \n */
788 && ( strend - s > slen
789 || strend - s < slen - 1
790 || (strend - s == slen && strend[-1] != '\n')))
792 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
793 " String too long...\n"));
796 /* Now should match s[0..slen-2] */
799 if (slen && (*SvPVX_const(check) != *s
800 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
802 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
803 " String not equal...\n"));
808 goto success_at_start;
813 end_shift = prog->check_end_shift;
815 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
817 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
818 (IV)end_shift, RX_PRECOMP(prog));
823 /* This is the (re)entry point of the main loop in this function.
824 * The goal of this loop is to:
825 * 1) find the "check" substring in the region rx_origin..strend
826 * (adjusted by start_shift / end_shift). If not found, reject
828 * 2) If it exists, look for the "other" substr too if defined; for
829 * example, if the check substr maps to the anchored substr, then
830 * check the floating substr, and vice-versa. If not found, go
831 * back to (1) with rx_origin suitably incremented.
832 * 3) If we find an rx_origin position that doesn't contradict
833 * either of the substrings, then check the possible additional
834 * constraints on rx_origin of /^.../m or a known start class.
835 * If these fail, then depending on which constraints fail, jump
836 * back to here, or to various other re-entry points further along
837 * that skip some of the first steps.
838 * 4) If we pass all those tests, update the BmUSEFUL() count on the
839 * substring. If the start position was determined to be at the
840 * beginning of the string - so, not rejected, but not optimised,
841 * since we have to run regmatch from position 0 - decrement the
842 * BmUSEFUL() count. Otherwise increment it.
846 /* first, look for the 'check' substring */
852 DEBUG_OPTIMISE_MORE_r({
853 PerlIO_printf(Perl_debug_log,
854 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
855 " Start shift: %"IVdf" End shift %"IVdf
856 " Real end Shift: %"IVdf"\n",
857 (IV)(rx_origin - strbeg),
858 (IV)prog->check_offset_min,
861 (IV)prog->check_end_shift);
864 end_point = HOP3(strend, -end_shift, strbeg);
865 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
870 /* If the regex is absolutely anchored to either the start of the
871 * string (SBOL) or to pos() (ANCH_GPOS), then
872 * check_offset_max represents an upper bound on the string where
873 * the substr could start. For the ANCH_GPOS case, we assume that
874 * the caller of intuit will have already set strpos to
875 * pos()-gofs, so in this case strpos + offset_max will still be
876 * an upper bound on the substr.
879 && prog->intflags & PREGf_ANCH
880 && prog->check_offset_max != SSize_t_MAX)
882 SSize_t len = SvCUR(check) - !!SvTAIL(check);
883 const char * const anchor =
884 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
886 /* do a bytes rather than chars comparison. It's conservative;
887 * so it skips doing the HOP if the result can't possibly end
888 * up earlier than the old value of end_point.
890 if ((char*)end_point - anchor > prog->check_offset_max) {
891 end_point = HOP3lim((U8*)anchor,
892 prog->check_offset_max,
898 check_at = fbm_instr( start_point, end_point,
899 check, multiline ? FBMrf_MULTILINE : 0);
901 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
902 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
903 (IV)((char*)start_point - strbeg),
904 (IV)((char*)end_point - strbeg),
905 (IV)(check_at ? check_at - strbeg : -1)
908 /* Update the count-of-usability, remove useless subpatterns,
912 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
913 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
914 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
915 (check_at ? "Found" : "Did not find"),
916 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
917 ? "anchored" : "floating"),
920 (check_at ? " at offset " : "...\n") );
925 /* set rx_origin to the minimum position where the regex could start
926 * matching, given the constraint of the just-matched check substring.
927 * But don't set it lower than previously.
930 if (check_at - rx_origin > prog->check_offset_max)
931 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
932 /* Finish the diagnostic message */
933 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
934 "%ld (rx_origin now %"IVdf")...\n",
935 (long)(check_at - strbeg),
936 (IV)(rx_origin - strbeg)
941 /* now look for the 'other' substring if defined */
943 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
944 : prog->substrs->data[other_ix].substr)
946 /* Take into account the "other" substring. */
950 struct reg_substr_datum *other;
953 other = &prog->substrs->data[other_ix];
955 /* if "other" is anchored:
956 * we've previously found a floating substr starting at check_at.
957 * This means that the regex origin must lie somewhere
958 * between min (rx_origin): HOP3(check_at, -check_offset_max)
959 * and max: HOP3(check_at, -check_offset_min)
960 * (except that min will be >= strpos)
961 * So the fixed substr must lie somewhere between
962 * HOP3(min, anchored_offset)
963 * HOP3(max, anchored_offset) + SvCUR(substr)
966 /* if "other" is floating
967 * Calculate last1, the absolute latest point where the
968 * floating substr could start in the string, ignoring any
969 * constraints from the earlier fixed match. It is calculated
972 * strend - prog->minlen (in chars) is the absolute latest
973 * position within the string where the origin of the regex
974 * could appear. The latest start point for the floating
975 * substr is float_min_offset(*) on from the start of the
976 * regex. last1 simply combines thee two offsets.
978 * (*) You might think the latest start point should be
979 * float_max_offset from the regex origin, and technically
980 * you'd be correct. However, consider
982 * Here, float min, max are 3,5 and minlen is 7.
983 * This can match either
987 * In the first case, the regex matches minlen chars; in the
988 * second, minlen+1, in the third, minlen+2.
989 * In the first case, the floating offset is 3 (which equals
990 * float_min), in the second, 4, and in the third, 5 (which
991 * equals float_max). In all cases, the floating string bcd
992 * can never start more than 4 chars from the end of the
993 * string, which equals minlen - float_min. As the substring
994 * starts to match more than float_min from the start of the
995 * regex, it makes the regex match more than minlen chars,
996 * and the two cancel each other out. So we can always use
997 * float_min - minlen, rather than float_max - minlen for the
998 * latest position in the string.
1000 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1001 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1004 assert(prog->minlen >= other->min_offset);
1005 last1 = HOP3c(strend,
1006 other->min_offset - prog->minlen, strbeg);
1008 if (other_ix) {/* i.e. if (other-is-float) */
1009 /* last is the latest point where the floating substr could
1010 * start, *given* any constraints from the earlier fixed
1011 * match. This constraint is that the floating string starts
1012 * <= float_max_offset chars from the regex origin (rx_origin).
1013 * If this value is less than last1, use it instead.
1015 assert(rx_origin <= last1);
1017 /* this condition handles the offset==infinity case, and
1018 * is a short-cut otherwise. Although it's comparing a
1019 * byte offset to a char length, it does so in a safe way,
1020 * since 1 char always occupies 1 or more bytes,
1021 * so if a string range is (last1 - rx_origin) bytes,
1022 * it will be less than or equal to (last1 - rx_origin)
1023 * chars; meaning it errs towards doing the accurate HOP3
1024 * rather than just using last1 as a short-cut */
1025 (last1 - rx_origin) < other->max_offset
1027 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1030 assert(strpos + start_shift <= check_at);
1031 last = HOP4c(check_at, other->min_offset - start_shift,
1035 s = HOP3c(rx_origin, other->min_offset, strend);
1036 if (s < other_last) /* These positions already checked */
1039 must = utf8_target ? other->utf8_substr : other->substr;
1040 assert(SvPOK(must));
1043 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1047 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1048 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1049 (IV)(from - strbeg),
1055 (unsigned char*)from,
1058 multiline ? FBMrf_MULTILINE : 0
1060 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1061 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1062 (IV)(from - strbeg),
1064 (IV)(s ? s - strbeg : -1)
1070 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1071 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1072 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1073 s ? "Found" : "Contradicts",
1074 other_ix ? "floating" : "anchored",
1075 quoted, RE_SV_TAIL(must));
1080 /* last1 is latest possible substr location. If we didn't
1081 * find it before there, we never will */
1082 if (last >= last1) {
1083 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1084 "; giving up...\n"));
1088 /* try to find the check substr again at a later
1089 * position. Maybe next time we'll find the "other" substr
1091 other_last = HOP3c(last, 1, strend) /* highest failure */;
1093 other_ix /* i.e. if other-is-float */
1094 ? HOP3c(rx_origin, 1, strend)
1095 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1096 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1097 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1098 (other_ix ? "floating" : "anchored"),
1099 (long)(HOP3c(check_at, 1, strend) - strbeg),
1100 (IV)(rx_origin - strbeg)
1105 if (other_ix) { /* if (other-is-float) */
1106 /* other_last is set to s, not s+1, since its possible for
1107 * a floating substr to fail first time, then succeed
1108 * second time at the same floating position; e.g.:
1109 * "-AB--AABZ" =~ /\wAB\d*Z/
1110 * The first time round, anchored and float match at
1111 * "-(AB)--AAB(Z)" then fail on the initial \w character
1112 * class. Second time round, they match at "-AB--A(AB)(Z)".
1117 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1118 other_last = HOP3c(s, 1, strend);
1120 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1121 " at offset %ld (rx_origin now %"IVdf")...\n",
1123 (IV)(rx_origin - strbeg)
1129 DEBUG_OPTIMISE_MORE_r(
1130 PerlIO_printf(Perl_debug_log,
1131 " Check-only match: offset min:%"IVdf" max:%"IVdf
1132 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1133 " strend:%"IVdf"\n",
1134 (IV)prog->check_offset_min,
1135 (IV)prog->check_offset_max,
1136 (IV)(check_at-strbeg),
1137 (IV)(rx_origin-strbeg),
1138 (IV)(rx_origin-check_at),
1144 postprocess_substr_matches:
1146 /* handle the extra constraint of /^.../m if present */
1148 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1151 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1152 " looking for /^/m anchor"));
1154 /* we have failed the constraint of a \n before rx_origin.
1155 * Find the next \n, if any, even if it's beyond the current
1156 * anchored and/or floating substrings. Whether we should be
1157 * scanning ahead for the next \n or the next substr is debatable.
1158 * On the one hand you'd expect rare substrings to appear less
1159 * often than \n's. On the other hand, searching for \n means
1160 * we're effectively flipping between check_substr and "\n" on each
1161 * iteration as the current "rarest" string candidate, which
1162 * means for example that we'll quickly reject the whole string if
1163 * hasn't got a \n, rather than trying every substr position
1167 s = HOP3c(strend, - prog->minlen, strpos);
1168 if (s <= rx_origin ||
1169 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1171 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1172 " Did not find /%s^%s/m...\n",
1173 PL_colors[0], PL_colors[1]));
1177 /* earliest possible origin is 1 char after the \n.
1178 * (since *rx_origin == '\n', it's safe to ++ here rather than
1179 * HOP(rx_origin, 1)) */
1182 if (prog->substrs->check_ix == 0 /* check is anchored */
1183 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1185 /* Position contradicts check-string; either because
1186 * check was anchored (and thus has no wiggle room),
1187 * or check was float and rx_origin is above the float range */
1188 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1189 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1190 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1194 /* if we get here, the check substr must have been float,
1195 * is in range, and we may or may not have had an anchored
1196 * "other" substr which still contradicts */
1197 assert(prog->substrs->check_ix); /* check is float */
1199 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1200 /* whoops, the anchored "other" substr exists, so we still
1201 * contradict. On the other hand, the float "check" substr
1202 * didn't contradict, so just retry the anchored "other"
1204 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1205 " Found /%s^%s/m, rescanning for anchored from offset %ld (rx_origin now %"IVdf")...\n",
1206 PL_colors[0], PL_colors[1],
1207 (long)(rx_origin - strbeg + prog->anchored_offset),
1208 (long)(rx_origin - strbeg)
1210 goto do_other_substr;
1213 /* success: we don't contradict the found floating substring
1214 * (and there's no anchored substr). */
1215 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1216 " Found /%s^%s/m with rx_origin %ld...\n",
1217 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1220 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1221 " (multiline anchor test skipped)\n"));
1227 /* if we have a starting character class, then test that extra constraint.
1228 * (trie stclasses are too expensive to use here, we are better off to
1229 * leave it to regmatch itself) */
1231 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1232 const U8* const str = (U8*)STRING(progi->regstclass);
1234 /* XXX this value could be pre-computed */
1235 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1236 ? (reginfo->is_utf8_pat
1237 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1238 : STR_LEN(progi->regstclass))
1242 /* latest pos that a matching float substr constrains rx start to */
1243 char *rx_max_float = NULL;
1245 /* if the current rx_origin is anchored, either by satisfying an
1246 * anchored substring constraint, or a /^.../m constraint, then we
1247 * can reject the current origin if the start class isn't found
1248 * at the current position. If we have a float-only match, then
1249 * rx_origin is constrained to a range; so look for the start class
1250 * in that range. if neither, then look for the start class in the
1251 * whole rest of the string */
1253 /* XXX DAPM it's not clear what the minlen test is for, and why
1254 * it's not used in the floating case. Nothing in the test suite
1255 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1256 * Here are some old comments, which may or may not be correct:
1258 * minlen == 0 is possible if regstclass is \b or \B,
1259 * and the fixed substr is ''$.
1260 * Since minlen is already taken into account, rx_origin+1 is
1261 * before strend; accidentally, minlen >= 1 guaranties no false
1262 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1263 * 0) below assumes that regstclass does not come from lookahead...
1264 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1265 * This leaves EXACTF-ish only, which are dealt with in
1269 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1270 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1271 else if (prog->float_substr || prog->float_utf8) {
1272 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1273 endpos= HOP3c(rx_max_float, cl_l, strend);
1278 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1279 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1280 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1281 (IV)start_shift, (IV)(check_at - strbeg),
1282 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1284 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1287 if (endpos == strend) {
1288 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1289 " Could not match STCLASS...\n") );
1292 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1293 " This position contradicts STCLASS...\n") );
1294 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1295 && !(prog->intflags & PREGf_IMPLICIT))
1298 /* Contradict one of substrings */
1299 if (prog->anchored_substr || prog->anchored_utf8) {
1300 if (prog->substrs->check_ix == 1) { /* check is float */
1301 /* Have both, check_string is floating */
1302 assert(rx_origin + start_shift <= check_at);
1303 if (rx_origin + start_shift != check_at) {
1304 /* not at latest position float substr could match:
1305 * Recheck anchored substring, but not floating.
1306 * The condition above is in bytes rather than
1307 * chars for efficiency. It's conservative, in
1308 * that it errs on the side of doing 'goto
1309 * do_other_substr'. In this case, at worst,
1310 * an extra anchored search may get done, but in
1311 * practice the extra fbm_instr() is likely to
1312 * get skipped anyway. */
1313 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1314 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1315 (long)(other_last - strbeg),
1316 (IV)(rx_origin - strbeg)
1318 goto do_other_substr;
1326 /* In the presence of ml_anch, we might be able to
1327 * find another \n without breaking the current float
1330 /* strictly speaking this should be HOP3c(..., 1, ...),
1331 * but since we goto a block of code that's going to
1332 * search for the next \n if any, its safe here */
1334 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1335 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1336 PL_colors[0], PL_colors[1],
1337 (long)(rx_origin - strbeg)) );
1338 goto postprocess_substr_matches;
1341 /* strictly speaking this can never be true; but might
1342 * be if we ever allow intuit without substrings */
1343 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1346 rx_origin = rx_max_float;
1349 /* at this point, any matching substrings have been
1350 * contradicted. Start again... */
1352 rx_origin = HOP3c(rx_origin, 1, strend);
1354 /* uses bytes rather than char calculations for efficiency.
1355 * It's conservative: it errs on the side of doing 'goto restart',
1356 * where there is code that does a proper char-based test */
1357 if (rx_origin + start_shift + end_shift > strend) {
1358 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1359 " Could not match STCLASS...\n") );
1362 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1363 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1364 (prog->substrs->check_ix ? "floating" : "anchored"),
1365 (long)(rx_origin + start_shift - strbeg),
1366 (IV)(rx_origin - strbeg)
1373 if (rx_origin != s) {
1374 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1375 " By STCLASS: moving %ld --> %ld\n",
1376 (long)(rx_origin - strbeg), (long)(s - strbeg))
1380 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1381 " Does not contradict STCLASS...\n");
1386 /* Decide whether using the substrings helped */
1388 if (rx_origin != strpos) {
1389 /* Fixed substring is found far enough so that the match
1390 cannot start at strpos. */
1392 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1393 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1396 /* The found rx_origin position does not prohibit matching at
1397 * strpos, so calling intuit didn't gain us anything. Decrement
1398 * the BmUSEFUL() count on the check substring, and if we reach
1400 if (!(prog->intflags & PREGf_NAUGHTY)
1402 prog->check_utf8 /* Could be deleted already */
1403 && --BmUSEFUL(prog->check_utf8) < 0
1404 && (prog->check_utf8 == prog->float_utf8)
1406 prog->check_substr /* Could be deleted already */
1407 && --BmUSEFUL(prog->check_substr) < 0
1408 && (prog->check_substr == prog->float_substr)
1411 /* If flags & SOMETHING - do not do it many times on the same match */
1412 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1413 /* XXX Does the destruction order has to change with utf8_target? */
1414 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1415 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1416 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1417 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1418 check = NULL; /* abort */
1419 /* XXXX This is a remnant of the old implementation. It
1420 looks wasteful, since now INTUIT can use many
1421 other heuristics. */
1422 prog->extflags &= ~RXf_USE_INTUIT;
1426 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1427 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1428 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1432 fail_finish: /* Substring not found */
1433 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1434 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1436 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1437 PL_colors[4], PL_colors[5]));
1442 #define DECL_TRIE_TYPE(scan) \
1443 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1444 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1445 trie_utf8l, trie_flu8 } \
1446 trie_type = ((scan->flags == EXACT) \
1447 ? (utf8_target ? trie_utf8 : trie_plain) \
1448 : (scan->flags == EXACTL) \
1449 ? (utf8_target ? trie_utf8l : trie_plain) \
1450 : (scan->flags == EXACTFA) \
1452 ? trie_utf8_exactfa_fold \
1453 : trie_latin_utf8_exactfa_fold) \
1454 : (scan->flags == EXACTFLU8 \
1458 : trie_latin_utf8_fold)))
1460 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1463 U8 flags = FOLD_FLAGS_FULL; \
1464 switch (trie_type) { \
1466 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1467 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1468 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1470 goto do_trie_utf8_fold; \
1471 case trie_utf8_exactfa_fold: \
1472 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1474 case trie_utf8_fold: \
1475 do_trie_utf8_fold: \
1476 if ( foldlen>0 ) { \
1477 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1482 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1483 len = UTF8SKIP(uc); \
1484 skiplen = UNISKIP( uvc ); \
1485 foldlen -= skiplen; \
1486 uscan = foldbuf + skiplen; \
1489 case trie_latin_utf8_exactfa_fold: \
1490 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1492 case trie_latin_utf8_fold: \
1493 if ( foldlen>0 ) { \
1494 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1500 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1501 skiplen = UNISKIP( uvc ); \
1502 foldlen -= skiplen; \
1503 uscan = foldbuf + skiplen; \
1507 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1508 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1509 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1513 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1520 charid = trie->charmap[ uvc ]; \
1524 if (widecharmap) { \
1525 SV** const svpp = hv_fetch(widecharmap, \
1526 (char*)&uvc, sizeof(UV), 0); \
1528 charid = (U16)SvIV(*svpp); \
1533 #define DUMP_EXEC_POS(li,s,doutf8) \
1534 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1537 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1541 && (ln == 1 || folder(s, pat_string, ln)) \
1542 && (reginfo->intuit || regtry(reginfo, &s)) )\
1548 #define REXEC_FBC_UTF8_SCAN(CODE) \
1550 while (s < strend) { \
1556 #define REXEC_FBC_SCAN(CODE) \
1558 while (s < strend) { \
1564 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1565 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1567 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1576 #define REXEC_FBC_CLASS_SCAN(COND) \
1577 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1579 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1588 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1589 if (utf8_target) { \
1590 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1593 REXEC_FBC_CLASS_SCAN(COND); \
1596 /* The three macros below are slightly different versions of the same logic.
1598 * The first is for /a and /aa when the target string is UTF-8. This can only
1599 * match ascii, but it must advance based on UTF-8. The other two handle the
1600 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1601 * for the boundary (or non-boundary) between a word and non-word character.
1602 * The utf8 and non-utf8 cases have the same logic, but the details must be
1603 * different. Find the "wordness" of the character just prior to this one, and
1604 * compare it with the wordness of this one. If they differ, we have a
1605 * boundary. At the beginning of the string, pretend that the previous
1606 * character was a new-line.
1608 * All these macros uncleanly have side-effects with each other and outside
1609 * variables. So far it's been too much trouble to clean-up
1611 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1612 * a word character or not.
1613 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1615 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1617 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1618 * are looking for a boundary or for a non-boundary. If we are looking for a
1619 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1620 * see if this tentative match actually works, and if so, to quit the loop
1621 * here. And vice-versa if we are looking for a non-boundary.
1623 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1624 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1625 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1626 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1627 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1628 * complement. But in that branch we complement tmp, meaning that at the
1629 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1630 * which means at the top of the loop in the next iteration, it is
1631 * TEST_NON_UTF8(s-1) */
1632 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1633 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1634 tmp = TEST_NON_UTF8(tmp); \
1635 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1636 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1638 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1645 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1646 * TEST_UTF8 is a macro that for the same input code points returns identically
1647 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1648 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1649 if (s == reginfo->strbeg) { \
1652 else { /* Back-up to the start of the previous character */ \
1653 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1654 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1655 0, UTF8_ALLOW_DEFAULT); \
1657 tmp = TEST_UV(tmp); \
1658 LOAD_UTF8_CHARCLASS_ALNUM(); \
1659 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1660 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1669 /* Like the above two macros. UTF8_CODE is the complete code for handling
1670 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1672 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1673 if (utf8_target) { \
1676 else { /* Not utf8 */ \
1677 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1678 tmp = TEST_NON_UTF8(tmp); \
1679 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1680 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1689 /* Here, things have been set up by the previous code so that tmp is the \
1690 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1691 * utf8ness of the target). We also have to check if this matches against \
1692 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1693 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1695 if (tmp == ! TEST_NON_UTF8('\n')) { \
1702 /* This is the macro to use when we want to see if something that looks like it
1703 * could match, actually does, and if so exits the loop */
1704 #define REXEC_FBC_TRYIT \
1705 if ((reginfo->intuit || regtry(reginfo, &s))) \
1708 /* The only difference between the BOUND and NBOUND cases is that
1709 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1710 * NBOUND. This is accomplished by passing it as either the if or else clause,
1711 * with the other one being empty (PLACEHOLDER is defined as empty).
1713 * The TEST_FOO parameters are for operating on different forms of input, but
1714 * all should be ones that return identically for the same underlying code
1716 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1718 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1719 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1721 #define FBC_BOUND_A(TEST_NON_UTF8) \
1723 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1724 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1726 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1728 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1729 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1731 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1733 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1734 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1736 /* Takes a pointer to an inversion list, a pointer to its corresponding
1737 * inversion map, and a code point, and returns the code point's value
1738 * according to the two arrays. It assumes that all code points have a value.
1739 * This is used as the base macro for macros for particular properties */
1740 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1741 invmap[_invlist_search(invlist, cp)]
1743 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1744 * of a code point, returning the value for the first code point in the string.
1745 * And it takes the particular macro name that finds the desired value given a
1746 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1747 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1748 (__ASSERT_(pos < strend) \
1749 /* Note assumes is valid UTF-8 */ \
1750 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1752 /* Returns the GCB value for the input code point */
1753 #define getGCB_VAL_CP(cp) \
1754 _generic_GET_BREAK_VAL_CP( \
1756 Grapheme_Cluster_Break_invmap, \
1759 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1760 * bounded by pos and strend */
1761 #define getGCB_VAL_UTF8(pos, strend) \
1762 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1765 /* Returns the SB value for the input code point */
1766 #define getSB_VAL_CP(cp) \
1767 _generic_GET_BREAK_VAL_CP( \
1769 Sentence_Break_invmap, \
1772 /* Returns the SB value for the first code point in the UTF-8 encoded string
1773 * bounded by pos and strend */
1774 #define getSB_VAL_UTF8(pos, strend) \
1775 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1777 /* Returns the WB value for the input code point */
1778 #define getWB_VAL_CP(cp) \
1779 _generic_GET_BREAK_VAL_CP( \
1781 Word_Break_invmap, \
1784 /* Returns the WB value for the first code point in the UTF-8 encoded string
1785 * bounded by pos and strend */
1786 #define getWB_VAL_UTF8(pos, strend) \
1787 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1789 /* We know what class REx starts with. Try to find this position... */
1790 /* if reginfo->intuit, its a dryrun */
1791 /* annoyingly all the vars in this routine have different names from their counterparts
1792 in regmatch. /grrr */
1794 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1795 const char *strend, regmatch_info *reginfo)
1798 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1799 char *pat_string; /* The pattern's exactish string */
1800 char *pat_end; /* ptr to end char of pat_string */
1801 re_fold_t folder; /* Function for computing non-utf8 folds */
1802 const U8 *fold_array; /* array for folding ords < 256 */
1808 I32 tmp = 1; /* Scratch variable? */
1809 const bool utf8_target = reginfo->is_utf8_target;
1810 UV utf8_fold_flags = 0;
1811 const bool is_utf8_pat = reginfo->is_utf8_pat;
1812 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1813 with a result inverts that result, as 0^1 =
1815 _char_class_number classnum;
1817 RXi_GET_DECL(prog,progi);
1819 PERL_ARGS_ASSERT_FIND_BYCLASS;
1821 /* We know what class it must start with. */
1824 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1828 REXEC_FBC_UTF8_CLASS_SCAN(
1829 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1832 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1836 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1837 assert(! is_utf8_pat);
1840 if (is_utf8_pat || utf8_target) {
1841 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1842 goto do_exactf_utf8;
1844 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1845 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1846 goto do_exactf_non_utf8; /* isn't dealt with by these */
1848 case EXACTF: /* This node only generated for non-utf8 patterns */
1849 assert(! is_utf8_pat);
1851 utf8_fold_flags = 0;
1852 goto do_exactf_utf8;
1854 fold_array = PL_fold;
1856 goto do_exactf_non_utf8;
1859 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1860 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1861 utf8_fold_flags = FOLDEQ_LOCALE;
1862 goto do_exactf_utf8;
1864 fold_array = PL_fold_locale;
1865 folder = foldEQ_locale;
1866 goto do_exactf_non_utf8;
1870 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1872 goto do_exactf_utf8;
1875 if (! utf8_target) { /* All code points in this node require
1876 UTF-8 to express. */
1879 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1880 | FOLDEQ_S2_FOLDS_SANE;
1881 goto do_exactf_utf8;
1884 if (is_utf8_pat || utf8_target) {
1885 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1886 goto do_exactf_utf8;
1889 /* Any 'ss' in the pattern should have been replaced by regcomp,
1890 * so we don't have to worry here about this single special case
1891 * in the Latin1 range */
1892 fold_array = PL_fold_latin1;
1893 folder = foldEQ_latin1;
1897 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1898 are no glitches with fold-length differences
1899 between the target string and pattern */
1901 /* The idea in the non-utf8 EXACTF* cases is to first find the
1902 * first character of the EXACTF* node and then, if necessary,
1903 * case-insensitively compare the full text of the node. c1 is the
1904 * first character. c2 is its fold. This logic will not work for
1905 * Unicode semantics and the german sharp ss, which hence should
1906 * not be compiled into a node that gets here. */
1907 pat_string = STRING(c);
1908 ln = STR_LEN(c); /* length to match in octets/bytes */
1910 /* We know that we have to match at least 'ln' bytes (which is the
1911 * same as characters, since not utf8). If we have to match 3
1912 * characters, and there are only 2 availabe, we know without
1913 * trying that it will fail; so don't start a match past the
1914 * required minimum number from the far end */
1915 e = HOP3c(strend, -((SSize_t)ln), s);
1917 if (reginfo->intuit && e < s) {
1918 e = s; /* Due to minlen logic of intuit() */
1922 c2 = fold_array[c1];
1923 if (c1 == c2) { /* If char and fold are the same */
1924 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1927 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1935 /* If one of the operands is in utf8, we can't use the simpler folding
1936 * above, due to the fact that many different characters can have the
1937 * same fold, or portion of a fold, or different- length fold */
1938 pat_string = STRING(c);
1939 ln = STR_LEN(c); /* length to match in octets/bytes */
1940 pat_end = pat_string + ln;
1941 lnc = is_utf8_pat /* length to match in characters */
1942 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1945 /* We have 'lnc' characters to match in the pattern, but because of
1946 * multi-character folding, each character in the target can match
1947 * up to 3 characters (Unicode guarantees it will never exceed
1948 * this) if it is utf8-encoded; and up to 2 if not (based on the
1949 * fact that the Latin 1 folds are already determined, and the
1950 * only multi-char fold in that range is the sharp-s folding to
1951 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1952 * string character. Adjust lnc accordingly, rounding up, so that
1953 * if we need to match at least 4+1/3 chars, that really is 5. */
1954 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1955 lnc = (lnc + expansion - 1) / expansion;
1957 /* As in the non-UTF8 case, if we have to match 3 characters, and
1958 * only 2 are left, it's guaranteed to fail, so don't start a
1959 * match that would require us to go beyond the end of the string
1961 e = HOP3c(strend, -((SSize_t)lnc), s);
1963 if (reginfo->intuit && e < s) {
1964 e = s; /* Due to minlen logic of intuit() */
1967 /* XXX Note that we could recalculate e to stop the loop earlier,
1968 * as the worst case expansion above will rarely be met, and as we
1969 * go along we would usually find that e moves further to the left.
1970 * This would happen only after we reached the point in the loop
1971 * where if there were no expansion we should fail. Unclear if
1972 * worth the expense */
1975 char *my_strend= (char *)strend;
1976 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1977 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1978 && (reginfo->intuit || regtry(reginfo, &s)) )
1982 s += (utf8_target) ? UTF8SKIP(s) : 1;
1988 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1989 if (FLAGS(c) != TRADITIONAL_BOUND) {
1990 if (! IN_UTF8_CTYPE_LOCALE) {
1991 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
1992 B_ON_NON_UTF8_LOCALE_IS_WRONG);
1997 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2001 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2002 if (FLAGS(c) != TRADITIONAL_BOUND) {
2003 if (! IN_UTF8_CTYPE_LOCALE) {
2004 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2005 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2010 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2013 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2015 assert(FLAGS(c) == TRADITIONAL_BOUND);
2017 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2020 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2022 assert(FLAGS(c) == TRADITIONAL_BOUND);
2024 FBC_BOUND_A(isWORDCHAR_A);
2027 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2029 assert(FLAGS(c) == TRADITIONAL_BOUND);
2031 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2034 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2036 assert(FLAGS(c) == TRADITIONAL_BOUND);
2038 FBC_NBOUND_A(isWORDCHAR_A);
2042 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2043 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2054 switch((bound_type) FLAGS(c)) {
2055 case TRADITIONAL_BOUND:
2056 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2059 if (s == reginfo->strbeg) { /* GCB always matches at begin and
2061 if (to_complement ^ cBOOL(reginfo->intuit
2062 || regtry(reginfo, &s)))
2066 s += (utf8_target) ? UTF8SKIP(s) : 1;
2070 GCB_enum before = getGCB_VAL_UTF8(
2072 (U8*)(reginfo->strbeg)),
2073 (U8*) reginfo->strend);
2074 while (s < strend) {
2075 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2076 (U8*) reginfo->strend);
2077 if (to_complement ^ isGCB(before, after)) {
2078 if (reginfo->intuit || regtry(reginfo, &s)) {
2086 else { /* Not utf8. Everything is a GCB except between CR and
2088 while (s < strend) {
2089 if (to_complement ^ (UCHARAT(s - 1) != '\r'
2090 || UCHARAT(s) != '\n'))
2092 if (reginfo->intuit || regtry(reginfo, &s)) {
2100 if (to_complement ^ cBOOL(reginfo->intuit || regtry(reginfo, &s))) {
2106 if (s == reginfo->strbeg) { /* SB always matches at beginning */
2108 ^ cBOOL(reginfo->intuit || regtry(reginfo, &s)))
2113 /* Didn't match. Go try at the next position */
2114 s += (utf8_target) ? UTF8SKIP(s) : 1;
2118 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2120 (U8*)(reginfo->strbeg)),
2121 (U8*) reginfo->strend);
2122 while (s < strend) {
2123 SB_enum after = getSB_VAL_UTF8((U8*) s,
2124 (U8*) reginfo->strend);
2125 if (to_complement ^ isSB(before,
2127 (U8*) reginfo->strbeg,
2129 (U8*) reginfo->strend,
2132 if (reginfo->intuit || regtry(reginfo, &s)) {
2140 else { /* Not utf8. */
2141 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2142 while (s < strend) {
2143 SB_enum after = getSB_VAL_CP((U8) *s);
2144 if (to_complement ^ isSB(before,
2146 (U8*) reginfo->strbeg,
2148 (U8*) reginfo->strend,
2151 if (reginfo->intuit || regtry(reginfo, &s)) {
2160 /* Here are at the final position in the target string. The SB
2161 * value is always true here, so matches, depending on other
2163 if (to_complement ^ cBOOL(reginfo->intuit
2164 || regtry(reginfo, &s)))
2172 if (s == reginfo->strbeg) {
2173 if (to_complement ^ cBOOL(reginfo->intuit
2174 || regtry(reginfo, &s)))
2178 s += (utf8_target) ? UTF8SKIP(s) : 1;
2182 /* We are at a boundary between char_sub_0 and char_sub_1.
2183 * We also keep track of the value for char_sub_-1 as we
2184 * loop through the line. Context may be needed to make a
2185 * determination, and if so, this can save having to
2187 WB_enum previous = WB_UNKNOWN;
2188 WB_enum before = getWB_VAL_UTF8(
2191 (U8*)(reginfo->strbeg)),
2192 (U8*) reginfo->strend);
2193 while (s < strend) {
2194 WB_enum after = getWB_VAL_UTF8((U8*) s,
2195 (U8*) reginfo->strend);
2196 if (to_complement ^ isWB(previous,
2199 (U8*) reginfo->strbeg,
2201 (U8*) reginfo->strend,
2204 if (reginfo->intuit || regtry(reginfo, &s)) {
2213 else { /* Not utf8. */
2214 WB_enum previous = WB_UNKNOWN;
2215 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2216 while (s < strend) {
2217 WB_enum after = getWB_VAL_CP((U8) *s);
2218 if (to_complement ^ isWB(previous,
2221 (U8*) reginfo->strbeg,
2223 (U8*) reginfo->strend,
2226 if (reginfo->intuit || regtry(reginfo, &s)) {
2236 if (to_complement ^ cBOOL(reginfo->intuit
2237 || regtry(reginfo, &s)))
2247 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2248 is_LNBREAK_latin1_safe(s, strend)
2252 /* The argument to all the POSIX node types is the class number to pass to
2253 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2260 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2261 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2262 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2277 /* The complement of something that matches only ASCII matches all
2278 * non-ASCII, plus everything in ASCII that isn't in the class. */
2279 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2280 || ! _generic_isCC_A(*s, FLAGS(c)));
2289 /* Don't need to worry about utf8, as it can match only a single
2290 * byte invariant character. */
2291 REXEC_FBC_CLASS_SCAN(
2292 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2300 if (! utf8_target) {
2301 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2307 classnum = (_char_class_number) FLAGS(c);
2308 if (classnum < _FIRST_NON_SWASH_CC) {
2309 while (s < strend) {
2311 /* We avoid loading in the swash as long as possible, but
2312 * should we have to, we jump to a separate loop. This
2313 * extra 'if' statement is what keeps this code from being
2314 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2315 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2316 goto found_above_latin1;
2318 if ((UTF8_IS_INVARIANT(*s)
2319 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2321 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2322 && to_complement ^ cBOOL(
2323 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2327 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2339 else switch (classnum) { /* These classes are implemented as
2341 case _CC_ENUM_SPACE:
2342 REXEC_FBC_UTF8_CLASS_SCAN(
2343 to_complement ^ cBOOL(isSPACE_utf8(s)));
2346 case _CC_ENUM_BLANK:
2347 REXEC_FBC_UTF8_CLASS_SCAN(
2348 to_complement ^ cBOOL(isBLANK_utf8(s)));
2351 case _CC_ENUM_XDIGIT:
2352 REXEC_FBC_UTF8_CLASS_SCAN(
2353 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2356 case _CC_ENUM_VERTSPACE:
2357 REXEC_FBC_UTF8_CLASS_SCAN(
2358 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2361 case _CC_ENUM_CNTRL:
2362 REXEC_FBC_UTF8_CLASS_SCAN(
2363 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2367 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2368 NOT_REACHED; /* NOTREACHED */
2373 found_above_latin1: /* Here we have to load a swash to get the result
2374 for the current code point */
2375 if (! PL_utf8_swash_ptrs[classnum]) {
2376 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2377 PL_utf8_swash_ptrs[classnum] =
2378 _core_swash_init("utf8",
2381 PL_XPosix_ptrs[classnum], &flags);
2384 /* This is a copy of the loop above for swash classes, though using the
2385 * FBC macro instead of being expanded out. Since we've loaded the
2386 * swash, we don't have to check for that each time through the loop */
2387 REXEC_FBC_UTF8_CLASS_SCAN(
2388 to_complement ^ cBOOL(_generic_utf8(
2391 swash_fetch(PL_utf8_swash_ptrs[classnum],
2399 /* what trie are we using right now */
2400 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2401 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2402 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2404 const char *last_start = strend - trie->minlen;
2406 const char *real_start = s;
2408 STRLEN maxlen = trie->maxlen;
2410 U8 **points; /* map of where we were in the input string
2411 when reading a given char. For ASCII this
2412 is unnecessary overhead as the relationship
2413 is always 1:1, but for Unicode, especially
2414 case folded Unicode this is not true. */
2415 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2419 GET_RE_DEBUG_FLAGS_DECL;
2421 /* We can't just allocate points here. We need to wrap it in
2422 * an SV so it gets freed properly if there is a croak while
2423 * running the match */
2426 sv_points=newSV(maxlen * sizeof(U8 *));
2427 SvCUR_set(sv_points,
2428 maxlen * sizeof(U8 *));
2429 SvPOK_on(sv_points);
2430 sv_2mortal(sv_points);
2431 points=(U8**)SvPV_nolen(sv_points );
2432 if ( trie_type != trie_utf8_fold
2433 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2436 bitmap=(U8*)trie->bitmap;
2438 bitmap=(U8*)ANYOF_BITMAP(c);
2440 /* this is the Aho-Corasick algorithm modified a touch
2441 to include special handling for long "unknown char" sequences.
2442 The basic idea being that we use AC as long as we are dealing
2443 with a possible matching char, when we encounter an unknown char
2444 (and we have not encountered an accepting state) we scan forward
2445 until we find a legal starting char.
2446 AC matching is basically that of trie matching, except that when
2447 we encounter a failing transition, we fall back to the current
2448 states "fail state", and try the current char again, a process
2449 we repeat until we reach the root state, state 1, or a legal
2450 transition. If we fail on the root state then we can either
2451 terminate if we have reached an accepting state previously, or
2452 restart the entire process from the beginning if we have not.
2455 while (s <= last_start) {
2456 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2464 U8 *uscan = (U8*)NULL;
2465 U8 *leftmost = NULL;
2467 U32 accepted_word= 0;
2471 while ( state && uc <= (U8*)strend ) {
2473 U32 word = aho->states[ state ].wordnum;
2477 DEBUG_TRIE_EXECUTE_r(
2478 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2479 dump_exec_pos( (char *)uc, c, strend, real_start,
2480 (char *)uc, utf8_target );
2481 PerlIO_printf( Perl_debug_log,
2482 " Scanning for legal start char...\n");
2486 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2490 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2496 if (uc >(U8*)last_start) break;
2500 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2501 if (!leftmost || lpos < leftmost) {
2502 DEBUG_r(accepted_word=word);
2508 points[pointpos++ % maxlen]= uc;
2509 if (foldlen || uc < (U8*)strend) {
2510 REXEC_TRIE_READ_CHAR(trie_type, trie,
2512 uscan, len, uvc, charid, foldlen,
2514 DEBUG_TRIE_EXECUTE_r({
2515 dump_exec_pos( (char *)uc, c, strend,
2516 real_start, s, utf8_target);
2517 PerlIO_printf(Perl_debug_log,
2518 " Charid:%3u CP:%4"UVxf" ",
2530 word = aho->states[ state ].wordnum;
2532 base = aho->states[ state ].trans.base;
2534 DEBUG_TRIE_EXECUTE_r({
2536 dump_exec_pos( (char *)uc, c, strend, real_start,
2538 PerlIO_printf( Perl_debug_log,
2539 "%sState: %4"UVxf", word=%"UVxf,
2540 failed ? " Fail transition to " : "",
2541 (UV)state, (UV)word);
2547 ( ((offset = base + charid
2548 - 1 - trie->uniquecharcount)) >= 0)
2549 && ((U32)offset < trie->lasttrans)
2550 && trie->trans[offset].check == state
2551 && (tmp=trie->trans[offset].next))
2553 DEBUG_TRIE_EXECUTE_r(
2554 PerlIO_printf( Perl_debug_log," - legal\n"));
2559 DEBUG_TRIE_EXECUTE_r(
2560 PerlIO_printf( Perl_debug_log," - fail\n"));
2562 state = aho->fail[state];
2566 /* we must be accepting here */
2567 DEBUG_TRIE_EXECUTE_r(
2568 PerlIO_printf( Perl_debug_log," - accepting\n"));
2577 if (!state) state = 1;
2580 if ( aho->states[ state ].wordnum ) {
2581 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2582 if (!leftmost || lpos < leftmost) {
2583 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2588 s = (char*)leftmost;
2589 DEBUG_TRIE_EXECUTE_r({
2591 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2592 (UV)accepted_word, (IV)(s - real_start)
2595 if (reginfo->intuit || regtry(reginfo, &s)) {
2601 DEBUG_TRIE_EXECUTE_r({
2602 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2605 DEBUG_TRIE_EXECUTE_r(
2606 PerlIO_printf( Perl_debug_log,"No match.\n"));
2615 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2622 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2623 * flags have same meanings as with regexec_flags() */
2626 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2633 struct regexp *const prog = ReANY(rx);
2635 if (flags & REXEC_COPY_STR) {
2639 PerlIO_printf(Perl_debug_log,
2640 "Copy on write: regexp capture, type %d\n",
2643 /* Create a new COW SV to share the match string and store
2644 * in saved_copy, unless the current COW SV in saved_copy
2645 * is valid and suitable for our purpose */
2646 if (( prog->saved_copy
2647 && SvIsCOW(prog->saved_copy)
2648 && SvPOKp(prog->saved_copy)
2651 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2653 /* just reuse saved_copy SV */
2654 if (RXp_MATCH_COPIED(prog)) {
2655 Safefree(prog->subbeg);
2656 RXp_MATCH_COPIED_off(prog);
2660 /* create new COW SV to share string */
2661 RX_MATCH_COPY_FREE(rx);
2662 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2664 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2665 assert (SvPOKp(prog->saved_copy));
2666 prog->sublen = strend - strbeg;
2667 prog->suboffset = 0;
2668 prog->subcoffset = 0;
2673 SSize_t max = strend - strbeg;
2676 if ( (flags & REXEC_COPY_SKIP_POST)
2677 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2678 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2679 ) { /* don't copy $' part of string */
2682 /* calculate the right-most part of the string covered
2683 * by a capture. Due to look-ahead, this may be to
2684 * the right of $&, so we have to scan all captures */
2685 while (n <= prog->lastparen) {
2686 if (prog->offs[n].end > max)
2687 max = prog->offs[n].end;
2691 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2692 ? prog->offs[0].start
2694 assert(max >= 0 && max <= strend - strbeg);
2697 if ( (flags & REXEC_COPY_SKIP_PRE)
2698 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2699 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2700 ) { /* don't copy $` part of string */
2703 /* calculate the left-most part of the string covered
2704 * by a capture. Due to look-behind, this may be to
2705 * the left of $&, so we have to scan all captures */
2706 while (min && n <= prog->lastparen) {
2707 if ( prog->offs[n].start != -1
2708 && prog->offs[n].start < min)
2710 min = prog->offs[n].start;
2714 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2715 && min > prog->offs[0].end
2717 min = prog->offs[0].end;
2721 assert(min >= 0 && min <= max && min <= strend - strbeg);
2724 if (RX_MATCH_COPIED(rx)) {
2725 if (sublen > prog->sublen)
2727 (char*)saferealloc(prog->subbeg, sublen+1);
2730 prog->subbeg = (char*)safemalloc(sublen+1);
2731 Copy(strbeg + min, prog->subbeg, sublen, char);
2732 prog->subbeg[sublen] = '\0';
2733 prog->suboffset = min;
2734 prog->sublen = sublen;
2735 RX_MATCH_COPIED_on(rx);
2737 prog->subcoffset = prog->suboffset;
2738 if (prog->suboffset && utf8_target) {
2739 /* Convert byte offset to chars.
2740 * XXX ideally should only compute this if @-/@+
2741 * has been seen, a la PL_sawampersand ??? */
2743 /* If there's a direct correspondence between the
2744 * string which we're matching and the original SV,
2745 * then we can use the utf8 len cache associated with
2746 * the SV. In particular, it means that under //g,
2747 * sv_pos_b2u() will use the previously cached
2748 * position to speed up working out the new length of
2749 * subcoffset, rather than counting from the start of
2750 * the string each time. This stops
2751 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2752 * from going quadratic */
2753 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2754 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2755 SV_GMAGIC|SV_CONST_RETURN);
2757 prog->subcoffset = utf8_length((U8*)strbeg,
2758 (U8*)(strbeg+prog->suboffset));
2762 RX_MATCH_COPY_FREE(rx);
2763 prog->subbeg = strbeg;
2764 prog->suboffset = 0;
2765 prog->subcoffset = 0;
2766 prog->sublen = strend - strbeg;
2774 - regexec_flags - match a regexp against a string
2777 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2778 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2779 /* stringarg: the point in the string at which to begin matching */
2780 /* strend: pointer to null at end of string */
2781 /* strbeg: real beginning of string */
2782 /* minend: end of match must be >= minend bytes after stringarg. */
2783 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2784 * itself is accessed via the pointers above */
2785 /* data: May be used for some additional optimizations.
2786 Currently unused. */
2787 /* flags: For optimizations. See REXEC_* in regexp.h */
2790 struct regexp *const prog = ReANY(rx);
2794 SSize_t minlen; /* must match at least this many chars */
2795 SSize_t dontbother = 0; /* how many characters not to try at end */
2796 const bool utf8_target = cBOOL(DO_UTF8(sv));
2798 RXi_GET_DECL(prog,progi);
2799 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2800 regmatch_info *const reginfo = ®info_buf;
2801 regexp_paren_pair *swap = NULL;
2803 GET_RE_DEBUG_FLAGS_DECL;
2805 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2806 PERL_UNUSED_ARG(data);
2808 /* Be paranoid... */
2810 Perl_croak(aTHX_ "NULL regexp parameter");
2814 debug_start_match(rx, utf8_target, stringarg, strend,
2818 startpos = stringarg;
2820 if (prog->intflags & PREGf_GPOS_SEEN) {
2823 /* set reginfo->ganch, the position where \G can match */
2826 (flags & REXEC_IGNOREPOS)
2827 ? stringarg /* use start pos rather than pos() */
2828 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2829 /* Defined pos(): */
2830 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2831 : strbeg; /* pos() not defined; use start of string */
2833 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2834 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2836 /* in the presence of \G, we may need to start looking earlier in
2837 * the string than the suggested start point of stringarg:
2838 * if prog->gofs is set, then that's a known, fixed minimum
2841 * /ab|c\G/: gofs = 1
2842 * or if the minimum offset isn't known, then we have to go back
2843 * to the start of the string, e.g. /w+\G/
2846 if (prog->intflags & PREGf_ANCH_GPOS) {
2847 startpos = reginfo->ganch - prog->gofs;
2849 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2851 DEBUG_r(PerlIO_printf(Perl_debug_log,
2852 "fail: ganch-gofs before earliest possible start\n"));
2856 else if (prog->gofs) {
2857 if (startpos - prog->gofs < strbeg)
2860 startpos -= prog->gofs;
2862 else if (prog->intflags & PREGf_GPOS_FLOAT)
2866 minlen = prog->minlen;
2867 if ((startpos + minlen) > strend || startpos < strbeg) {
2868 DEBUG_r(PerlIO_printf(Perl_debug_log,
2869 "Regex match can't succeed, so not even tried\n"));
2873 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2874 * which will call destuctors to reset PL_regmatch_state, free higher
2875 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2876 * regmatch_info_aux_eval */
2878 oldsave = PL_savestack_ix;
2882 if ((prog->extflags & RXf_USE_INTUIT)
2883 && !(flags & REXEC_CHECKED))
2885 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2890 if (prog->extflags & RXf_CHECK_ALL) {
2891 /* we can match based purely on the result of INTUIT.
2892 * Set up captures etc just for $& and $-[0]
2893 * (an intuit-only match wont have $1,$2,..) */
2894 assert(!prog->nparens);
2896 /* s/// doesn't like it if $& is earlier than where we asked it to
2897 * start searching (which can happen on something like /.\G/) */
2898 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2901 /* this should only be possible under \G */
2902 assert(prog->intflags & PREGf_GPOS_SEEN);
2903 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2904 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2908 /* match via INTUIT shouldn't have any captures.
2909 * Let @-, @+, $^N know */
2910 prog->lastparen = prog->lastcloseparen = 0;
2911 RX_MATCH_UTF8_set(rx, utf8_target);
2912 prog->offs[0].start = s - strbeg;
2913 prog->offs[0].end = utf8_target
2914 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2915 : s - strbeg + prog->minlenret;
2916 if ( !(flags & REXEC_NOT_FIRST) )
2917 S_reg_set_capture_string(aTHX_ rx,
2919 sv, flags, utf8_target);
2925 multiline = prog->extflags & RXf_PMf_MULTILINE;
2927 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2928 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2929 "String too short [regexec_flags]...\n"));
2933 /* Check validity of program. */
2934 if (UCHARAT(progi->program) != REG_MAGIC) {
2935 Perl_croak(aTHX_ "corrupted regexp program");
2938 RX_MATCH_TAINTED_off(rx);
2939 RX_MATCH_UTF8_set(rx, utf8_target);
2941 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2942 reginfo->intuit = 0;
2943 reginfo->is_utf8_target = cBOOL(utf8_target);
2944 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2945 reginfo->warned = FALSE;
2946 reginfo->strbeg = strbeg;
2948 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2949 reginfo->strend = strend;
2950 /* see how far we have to get to not match where we matched before */
2951 reginfo->till = stringarg + minend;
2953 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2954 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2955 S_cleanup_regmatch_info_aux has executed (registered by
2956 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2957 magic belonging to this SV.
2958 Not newSVsv, either, as it does not COW.
2960 reginfo->sv = newSV(0);
2961 SvSetSV_nosteal(reginfo->sv, sv);
2962 SAVEFREESV(reginfo->sv);
2965 /* reserve next 2 or 3 slots in PL_regmatch_state:
2966 * slot N+0: may currently be in use: skip it
2967 * slot N+1: use for regmatch_info_aux struct
2968 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2969 * slot N+3: ready for use by regmatch()
2973 regmatch_state *old_regmatch_state;
2974 regmatch_slab *old_regmatch_slab;
2975 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2977 /* on first ever match, allocate first slab */
2978 if (!PL_regmatch_slab) {
2979 Newx(PL_regmatch_slab, 1, regmatch_slab);
2980 PL_regmatch_slab->prev = NULL;
2981 PL_regmatch_slab->next = NULL;
2982 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2985 old_regmatch_state = PL_regmatch_state;
2986 old_regmatch_slab = PL_regmatch_slab;
2988 for (i=0; i <= max; i++) {
2990 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2992 reginfo->info_aux_eval =
2993 reginfo->info_aux->info_aux_eval =
2994 &(PL_regmatch_state->u.info_aux_eval);
2996 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2997 PL_regmatch_state = S_push_slab(aTHX);
3000 /* note initial PL_regmatch_state position; at end of match we'll
3001 * pop back to there and free any higher slabs */
3003 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3004 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3005 reginfo->info_aux->poscache = NULL;
3007 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3009 if ((prog->extflags & RXf_EVAL_SEEN))
3010 S_setup_eval_state(aTHX_ reginfo);
3012 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3015 /* If there is a "must appear" string, look for it. */
3017 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3018 /* We have to be careful. If the previous successful match
3019 was from this regex we don't want a subsequent partially
3020 successful match to clobber the old results.
3021 So when we detect this possibility we add a swap buffer
3022 to the re, and switch the buffer each match. If we fail,
3023 we switch it back; otherwise we leave it swapped.
3026 /* do we need a save destructor here for eval dies? */
3027 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3028 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3029 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3036 /* Simplest case: anchored match need be tried only once, or with
3037 * MBOL, only at the beginning of each line.
3039 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3040 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3041 * match at the start of the string then it won't match anywhere else
3042 * either; while with /.*.../, if it doesn't match at the beginning,
3043 * the earliest it could match is at the start of the next line */
3045 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3048 if (regtry(reginfo, &s))
3051 if (!(prog->intflags & PREGf_ANCH_MBOL))
3054 /* didn't match at start, try at other newline positions */
3057 dontbother = minlen - 1;
3058 end = HOP3c(strend, -dontbother, strbeg) - 1;
3060 /* skip to next newline */
3062 while (s <= end) { /* note it could be possible to match at the end of the string */
3063 /* NB: newlines are the same in unicode as they are in latin */
3066 if (prog->check_substr || prog->check_utf8) {
3067 /* note that with PREGf_IMPLICIT, intuit can only fail
3068 * or return the start position, so it's of limited utility.
3069 * Nevertheless, I made the decision that the potential for
3070 * quick fail was still worth it - DAPM */
3071 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3075 if (regtry(reginfo, &s))
3079 } /* end anchored search */
3081 if (prog->intflags & PREGf_ANCH_GPOS)
3083 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3084 assert(prog->intflags & PREGf_GPOS_SEEN);
3085 /* For anchored \G, the only position it can match from is
3086 * (ganch-gofs); we already set startpos to this above; if intuit
3087 * moved us on from there, we can't possibly succeed */
3088 assert(startpos == reginfo->ganch - prog->gofs);
3089 if (s == startpos && regtry(reginfo, &s))
3094 /* Messy cases: unanchored match. */
3095 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3096 /* we have /x+whatever/ */
3097 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3103 if (! prog->anchored_utf8) {
3104 to_utf8_substr(prog);
3106 ch = SvPVX_const(prog->anchored_utf8)[0];
3109 DEBUG_EXECUTE_r( did_match = 1 );
3110 if (regtry(reginfo, &s)) goto got_it;
3112 while (s < strend && *s == ch)
3119 if (! prog->anchored_substr) {
3120 if (! to_byte_substr(prog)) {
3121 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3124 ch = SvPVX_const(prog->anchored_substr)[0];
3127 DEBUG_EXECUTE_r( did_match = 1 );
3128 if (regtry(reginfo, &s)) goto got_it;
3130 while (s < strend && *s == ch)
3135 DEBUG_EXECUTE_r(if (!did_match)
3136 PerlIO_printf(Perl_debug_log,
3137 "Did not find anchored character...\n")
3140 else if (prog->anchored_substr != NULL
3141 || prog->anchored_utf8 != NULL
3142 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3143 && prog->float_max_offset < strend - s)) {
3148 char *last1; /* Last position checked before */
3152 if (prog->anchored_substr || prog->anchored_utf8) {
3154 if (! prog->anchored_utf8) {
3155 to_utf8_substr(prog);
3157 must = prog->anchored_utf8;
3160 if (! prog->anchored_substr) {
3161 if (! to_byte_substr(prog)) {
3162 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3165 must = prog->anchored_substr;
3167 back_max = back_min = prog->anchored_offset;
3170 if (! prog->float_utf8) {
3171 to_utf8_substr(prog);
3173 must = prog->float_utf8;
3176 if (! prog->float_substr) {
3177 if (! to_byte_substr(prog)) {
3178 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3181 must = prog->float_substr;
3183 back_max = prog->float_max_offset;
3184 back_min = prog->float_min_offset;
3190 last = HOP3c(strend, /* Cannot start after this */
3191 -(SSize_t)(CHR_SVLEN(must)
3192 - (SvTAIL(must) != 0) + back_min), strbeg);
3194 if (s > reginfo->strbeg)
3195 last1 = HOPc(s, -1);
3197 last1 = s - 1; /* bogus */
3199 /* XXXX check_substr already used to find "s", can optimize if
3200 check_substr==must. */
3202 strend = HOPc(strend, -dontbother);
3203 while ( (s <= last) &&
3204 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3205 (unsigned char*)strend, must,
3206 multiline ? FBMrf_MULTILINE : 0)) ) {
3207 DEBUG_EXECUTE_r( did_match = 1 );
3208 if (HOPc(s, -back_max) > last1) {
3209 last1 = HOPc(s, -back_min);
3210 s = HOPc(s, -back_max);
3213 char * const t = (last1 >= reginfo->strbeg)
3214 ? HOPc(last1, 1) : last1 + 1;
3216 last1 = HOPc(s, -back_min);
3220 while (s <= last1) {
3221 if (regtry(reginfo, &s))
3224 s++; /* to break out of outer loop */
3231 while (s <= last1) {
3232 if (regtry(reginfo, &s))
3238 DEBUG_EXECUTE_r(if (!did_match) {
3239 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3240 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3241 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3242 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3243 ? "anchored" : "floating"),
3244 quoted, RE_SV_TAIL(must));
3248 else if ( (c = progi->regstclass) ) {
3250 const OPCODE op = OP(progi->regstclass);
3251 /* don't bother with what can't match */
3252 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3253 strend = HOPc(strend, -(minlen - 1));
3256 SV * const prop = sv_newmortal();
3257 regprop(prog, prop, c, reginfo, NULL);
3259 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3261 PerlIO_printf(Perl_debug_log,
3262 "Matching stclass %.*s against %s (%d bytes)\n",
3263 (int)SvCUR(prop), SvPVX_const(prop),
3264 quoted, (int)(strend - s));
3267 if (find_byclass(prog, c, s, strend, reginfo))
3269 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3273 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3281 if (! prog->float_utf8) {
3282 to_utf8_substr(prog);
3284 float_real = prog->float_utf8;
3287 if (! prog->float_substr) {
3288 if (! to_byte_substr(prog)) {
3289 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3292 float_real = prog->float_substr;
3295 little = SvPV_const(float_real, len);
3296 if (SvTAIL(float_real)) {
3297 /* This means that float_real contains an artificial \n on
3298 * the end due to the presence of something like this:
3299 * /foo$/ where we can match both "foo" and "foo\n" at the
3300 * end of the string. So we have to compare the end of the
3301 * string first against the float_real without the \n and
3302 * then against the full float_real with the string. We
3303 * have to watch out for cases where the string might be
3304 * smaller than the float_real or the float_real without
3306 char *checkpos= strend - len;
3308 PerlIO_printf(Perl_debug_log,
3309 "%sChecking for float_real.%s\n",
3310 PL_colors[4], PL_colors[5]));
3311 if (checkpos + 1 < strbeg) {
3312 /* can't match, even if we remove the trailing \n
3313 * string is too short to match */
3315 PerlIO_printf(Perl_debug_log,
3316 "%sString shorter than required trailing substring, cannot match.%s\n",
3317 PL_colors[4], PL_colors[5]));
3319 } else if (memEQ(checkpos + 1, little, len - 1)) {
3320 /* can match, the end of the string matches without the
3322 last = checkpos + 1;
3323 } else if (checkpos < strbeg) {
3324 /* cant match, string is too short when the "\n" is
3327 PerlIO_printf(Perl_debug_log,
3328 "%sString does not contain required trailing substring, cannot match.%s\n",
3329 PL_colors[4], PL_colors[5]));
3331 } else if (!multiline) {
3332 /* non multiline match, so compare with the "\n" at the
3333 * end of the string */
3334 if (memEQ(checkpos, little, len)) {
3338 PerlIO_printf(Perl_debug_log,
3339 "%sString does not contain required trailing substring, cannot match.%s\n",
3340 PL_colors[4], PL_colors[5]));
3344 /* multiline match, so we have to search for a place
3345 * where the full string is located */
3351 last = rninstr(s, strend, little, little + len);
3353 last = strend; /* matching "$" */
3356 /* at one point this block contained a comment which was
3357 * probably incorrect, which said that this was a "should not
3358 * happen" case. Even if it was true when it was written I am
3359 * pretty sure it is not anymore, so I have removed the comment
3360 * and replaced it with this one. Yves */
3362 PerlIO_printf(Perl_debug_log,
3363 "%sString does not contain required substring, cannot match.%s\n",
3364 PL_colors[4], PL_colors[5]
3368 dontbother = strend - last + prog->float_min_offset;
3370 if (minlen && (dontbother < minlen))
3371 dontbother = minlen - 1;
3372 strend -= dontbother; /* this one's always in bytes! */
3373 /* We don't know much -- general case. */
3376 if (regtry(reginfo, &s))
3385 if (regtry(reginfo, &s))
3387 } while (s++ < strend);
3395 /* s/// doesn't like it if $& is earlier than where we asked it to
3396 * start searching (which can happen on something like /.\G/) */
3397 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3398 && (prog->offs[0].start < stringarg - strbeg))
3400 /* this should only be possible under \G */
3401 assert(prog->intflags & PREGf_GPOS_SEEN);
3402 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3403 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3409 PerlIO_printf(Perl_debug_log,
3410 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3417 /* clean up; this will trigger destructors that will free all slabs
3418 * above the current one, and cleanup the regmatch_info_aux
3419 * and regmatch_info_aux_eval sructs */
3421 LEAVE_SCOPE(oldsave);
3423 if (RXp_PAREN_NAMES(prog))
3424 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3426 /* make sure $`, $&, $', and $digit will work later */
3427 if ( !(flags & REXEC_NOT_FIRST) )
3428 S_reg_set_capture_string(aTHX_ rx,
3429 strbeg, reginfo->strend,
3430 sv, flags, utf8_target);
3435 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3436 PL_colors[4], PL_colors[5]));
3438 /* clean up; this will trigger destructors that will free all slabs
3439 * above the current one, and cleanup the regmatch_info_aux
3440 * and regmatch_info_aux_eval sructs */
3442 LEAVE_SCOPE(oldsave);
3445 /* we failed :-( roll it back */
3446 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3447 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3452 Safefree(prog->offs);
3459 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3460 * Do inc before dec, in case old and new rex are the same */
3461 #define SET_reg_curpm(Re2) \
3462 if (reginfo->info_aux_eval) { \
3463 (void)ReREFCNT_inc(Re2); \
3464 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3465 PM_SETRE((PL_reg_curpm), (Re2)); \
3470 - regtry - try match at specific point
3472 STATIC I32 /* 0 failure, 1 success */
3473 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3476 REGEXP *const rx = reginfo->prog;
3477 regexp *const prog = ReANY(rx);
3479 RXi_GET_DECL(prog,progi);
3480 GET_RE_DEBUG_FLAGS_DECL;
3482 PERL_ARGS_ASSERT_REGTRY;
3484 reginfo->cutpoint=NULL;
3486 prog->offs[0].start = *startposp - reginfo->strbeg;
3487 prog->lastparen = 0;
3488 prog->lastcloseparen = 0;
3490 /* XXXX What this code is doing here?!!! There should be no need
3491 to do this again and again, prog->lastparen should take care of
3494 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3495 * Actually, the code in regcppop() (which Ilya may be meaning by
3496 * prog->lastparen), is not needed at all by the test suite
3497 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3498 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3499 * Meanwhile, this code *is* needed for the
3500 * above-mentioned test suite tests to succeed. The common theme
3501 * on those tests seems to be returning null fields from matches.
3502 * --jhi updated by dapm */
3504 if (prog->nparens) {
3505 regexp_paren_pair *pp = prog->offs;
3507 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3515 result = regmatch(reginfo, *startposp, progi->program + 1);
3517 prog->offs[0].end = result;
3520 if (reginfo->cutpoint)
3521 *startposp= reginfo->cutpoint;
3522 REGCP_UNWIND(lastcp);
3527 #define sayYES goto yes
3528 #define sayNO goto no
3529 #define sayNO_SILENT goto no_silent
3531 /* we dont use STMT_START/END here because it leads to
3532 "unreachable code" warnings, which are bogus, but distracting. */
3533 #define CACHEsayNO \
3534 if (ST.cache_mask) \
3535 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3538 /* this is used to determine how far from the left messages like
3539 'failed...' are printed. It should be set such that messages
3540 are inline with the regop output that created them.
3542 #define REPORT_CODE_OFF 32
3545 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3546 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3547 #define CHRTEST_NOT_A_CP_1 -999
3548 #define CHRTEST_NOT_A_CP_2 -998
3550 /* grab a new slab and return the first slot in it */
3552 STATIC regmatch_state *
3555 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3558 regmatch_slab *s = PL_regmatch_slab->next;
3560 Newx(s, 1, regmatch_slab);
3561 s->prev = PL_regmatch_slab;
3563 PL_regmatch_slab->next = s;
3565 PL_regmatch_slab = s;
3566 return SLAB_FIRST(s);
3570 /* push a new state then goto it */
3572 #define PUSH_STATE_GOTO(state, node, input) \
3573 pushinput = input; \
3575 st->resume_state = state; \
3578 /* push a new state with success backtracking, then goto it */
3580 #define PUSH_YES_STATE_GOTO(state, node, input) \
3581 pushinput = input; \
3583 st->resume_state = state; \
3584 goto push_yes_state;
3591 regmatch() - main matching routine
3593 This is basically one big switch statement in a loop. We execute an op,
3594 set 'next' to point the next op, and continue. If we come to a point which
3595 we may need to backtrack to on failure such as (A|B|C), we push a
3596 backtrack state onto the backtrack stack. On failure, we pop the top
3597 state, and re-enter the loop at the state indicated. If there are no more
3598 states to pop, we return failure.
3600 Sometimes we also need to backtrack on success; for example /A+/, where
3601 after successfully matching one A, we need to go back and try to
3602 match another one; similarly for lookahead assertions: if the assertion
3603 completes successfully, we backtrack to the state just before the assertion
3604 and then carry on. In these cases, the pushed state is marked as
3605 'backtrack on success too'. This marking is in fact done by a chain of
3606 pointers, each pointing to the previous 'yes' state. On success, we pop to
3607 the nearest yes state, discarding any intermediate failure-only states.
3608 Sometimes a yes state is pushed just to force some cleanup code to be
3609 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3610 it to free the inner regex.
3612 Note that failure backtracking rewinds the cursor position, while
3613 success backtracking leaves it alone.
3615 A pattern is complete when the END op is executed, while a subpattern
3616 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3617 ops trigger the "pop to last yes state if any, otherwise return true"
3620 A common convention in this function is to use A and B to refer to the two
3621 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3622 the subpattern to be matched possibly multiple times, while B is the entire
3623 rest of the pattern. Variable and state names reflect this convention.
3625 The states in the main switch are the union of ops and failure/success of
3626 substates associated with with that op. For example, IFMATCH is the op
3627 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3628 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3629 successfully matched A and IFMATCH_A_fail is a state saying that we have
3630 just failed to match A. Resume states always come in pairs. The backtrack
3631 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3632 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3633 on success or failure.
3635 The struct that holds a backtracking state is actually a big union, with
3636 one variant for each major type of op. The variable st points to the
3637 top-most backtrack struct. To make the code clearer, within each
3638 block of code we #define ST to alias the relevant union.
3640 Here's a concrete example of a (vastly oversimplified) IFMATCH
3646 #define ST st->u.ifmatch
3648 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3649 ST.foo = ...; // some state we wish to save
3651 // push a yes backtrack state with a resume value of
3652 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3654 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3657 case IFMATCH_A: // we have successfully executed A; now continue with B
3659 bar = ST.foo; // do something with the preserved value
3662 case IFMATCH_A_fail: // A failed, so the assertion failed
3663 ...; // do some housekeeping, then ...
3664 sayNO; // propagate the failure
3671 For any old-timers reading this who are familiar with the old recursive
3672 approach, the code above is equivalent to:
3674 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3683 ...; // do some housekeeping, then ...
3684 sayNO; // propagate the failure
3687 The topmost backtrack state, pointed to by st, is usually free. If you
3688 want to claim it, populate any ST.foo fields in it with values you wish to
3689 save, then do one of
3691 PUSH_STATE_GOTO(resume_state, node, newinput);
3692 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3694 which sets that backtrack state's resume value to 'resume_state', pushes a
3695 new free entry to the top of the backtrack stack, then goes to 'node'.
3696 On backtracking, the free slot is popped, and the saved state becomes the
3697 new free state. An ST.foo field in this new top state can be temporarily
3698 accessed to retrieve values, but once the main loop is re-entered, it
3699 becomes available for reuse.
3701 Note that the depth of the backtrack stack constantly increases during the
3702 left-to-right execution of the pattern, rather than going up and down with
3703 the pattern nesting. For example the stack is at its maximum at Z at the
3704 end of the pattern, rather than at X in the following:
3706 /(((X)+)+)+....(Y)+....Z/
3708 The only exceptions to this are lookahead/behind assertions and the cut,
3709 (?>A), which pop all the backtrack states associated with A before
3712 Backtrack state structs are allocated in slabs of about 4K in size.
3713 PL_regmatch_state and st always point to the currently active state,
3714 and PL_regmatch_slab points to the slab currently containing
3715 PL_regmatch_state. The first time regmatch() is called, the first slab is
3716 allocated, and is never freed until interpreter destruction. When the slab
3717 is full, a new one is allocated and chained to the end. At exit from
3718 regmatch(), slabs allocated since entry are freed.
3723 #define DEBUG_STATE_pp(pp) \
3725 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3726 PerlIO_printf(Perl_debug_log, \
3727 " %*s"pp" %s%s%s%s%s\n", \
3729 PL_reg_name[st->resume_state], \
3730 ((st==yes_state||st==mark_state) ? "[" : ""), \
3731 ((st==yes_state) ? "Y" : ""), \
3732 ((st==mark_state) ? "M" : ""), \
3733 ((st==yes_state||st==mark_state) ? "]" : "") \
3738 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3743 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3744 const char *start, const char *end, const char *blurb)
3746 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3748 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3753 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3754 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3756 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3757 start, end - start, 60);
3759 PerlIO_printf(Perl_debug_log,
3760 "%s%s REx%s %s against %s\n",
3761 PL_colors[4], blurb, PL_colors[5], s0, s1);
3763 if (utf8_target||utf8_pat)
3764 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3765 utf8_pat ? "pattern" : "",
3766 utf8_pat && utf8_target ? " and " : "",
3767 utf8_target ? "string" : ""
3773 S_dump_exec_pos(pTHX_ const char *locinput,
3774 const regnode *scan,
3775 const char *loc_regeol,
3776 const char *loc_bostr,
3777 const char *loc_reg_starttry,
3778 const bool utf8_target)
3780 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3781 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3782 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3783 /* The part of the string before starttry has one color
3784 (pref0_len chars), between starttry and current
3785 position another one (pref_len - pref0_len chars),
3786 after the current position the third one.
3787 We assume that pref0_len <= pref_len, otherwise we
3788 decrease pref0_len. */
3789 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3790 ? (5 + taill) - l : locinput - loc_bostr;
3793 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3795 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3797 pref0_len = pref_len - (locinput - loc_reg_starttry);
3798 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3799 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3800 ? (5 + taill) - pref_len : loc_regeol - locinput);
3801 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3805 if (pref0_len > pref_len)
3806 pref0_len = pref_len;
3808 const int is_uni = utf8_target ? 1 : 0;
3810 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3811 (locinput - pref_len),pref0_len, 60, 4, 5);
3813 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3814 (locinput - pref_len + pref0_len),
3815 pref_len - pref0_len, 60, 2, 3);
3817 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3818 locinput, loc_regeol - locinput, 10, 0, 1);
3820 const STRLEN tlen=len0+len1+len2;
3821 PerlIO_printf(Perl_debug_log,
3822 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3823 (IV)(locinput - loc_bostr),
3826 (docolor ? "" : "> <"),
3828 (int)(tlen > 19 ? 0 : 19 - tlen),
3835 /* reg_check_named_buff_matched()
3836 * Checks to see if a named buffer has matched. The data array of
3837 * buffer numbers corresponding to the buffer is expected to reside
3838 * in the regexp->data->data array in the slot stored in the ARG() of
3839 * node involved. Note that this routine doesn't actually care about the
3840 * name, that information is not preserved from compilation to execution.
3841 * Returns the index of the leftmost defined buffer with the given name
3842 * or 0 if non of the buffers matched.
3845 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3848 RXi_GET_DECL(rex,rexi);
3849 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3850 I32 *nums=(I32*)SvPVX(sv_dat);
3852 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3854 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3855 if ((I32)rex->lastparen >= nums[n] &&
3856 rex->offs[nums[n]].end != -1)
3866 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3867 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3869 /* This function determines if there are one or two characters that match
3870 * the first character of the passed-in EXACTish node <text_node>, and if
3871 * so, returns them in the passed-in pointers.
3873 * If it determines that no possible character in the target string can
3874 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3875 * the first character in <text_node> requires UTF-8 to represent, and the
3876 * target string isn't in UTF-8.)
3878 * If there are more than two characters that could match the beginning of
3879 * <text_node>, or if more context is required to determine a match or not,
3880 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3882 * The motiviation behind this function is to allow the caller to set up
3883 * tight loops for matching. If <text_node> is of type EXACT, there is
3884 * only one possible character that can match its first character, and so
3885 * the situation is quite simple. But things get much more complicated if
3886 * folding is involved. It may be that the first character of an EXACTFish
3887 * node doesn't participate in any possible fold, e.g., punctuation, so it
3888 * can be matched only by itself. The vast majority of characters that are
3889 * in folds match just two things, their lower and upper-case equivalents.
3890 * But not all are like that; some have multiple possible matches, or match
3891 * sequences of more than one character. This function sorts all that out.
3893 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3894 * loop of trying to match A*, we know we can't exit where the thing
3895 * following it isn't a B. And something can't be a B unless it is the
3896 * beginning of B. By putting a quick test for that beginning in a tight
3897 * loop, we can rule out things that can't possibly be B without having to
3898 * break out of the loop, thus avoiding work. Similarly, if A is a single
3899 * character, we can make a tight loop matching A*, using the outputs of
3902 * If the target string to match isn't in UTF-8, and there aren't
3903 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3904 * the one or two possible octets (which are characters in this situation)
3905 * that can match. In all cases, if there is only one character that can
3906 * match, *<c1p> and *<c2p> will be identical.
3908 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3909 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3910 * can match the beginning of <text_node>. They should be declared with at
3911 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3912 * undefined what these contain.) If one or both of the buffers are
3913 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3914 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3915 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3916 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3917 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3919 const bool utf8_target = reginfo->is_utf8_target;
3921 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
3922 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
3923 bool use_chrtest_void = FALSE;
3924 const bool is_utf8_pat = reginfo->is_utf8_pat;
3926 /* Used when we have both utf8 input and utf8 output, to avoid converting
3927 * to/from code points */
3928 bool utf8_has_been_setup = FALSE;
3932 U8 *pat = (U8*)STRING(text_node);
3933 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3935 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
3937 /* In an exact node, only one thing can be matched, that first
3938 * character. If both the pat and the target are UTF-8, we can just
3939 * copy the input to the output, avoiding finding the code point of
3944 else if (utf8_target) {
3945 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3946 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3947 utf8_has_been_setup = TRUE;
3950 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3953 else { /* an EXACTFish node */
3954 U8 *pat_end = pat + STR_LEN(text_node);
3956 /* An EXACTFL node has at least some characters unfolded, because what
3957 * they match is not known until now. So, now is the time to fold
3958 * the first few of them, as many as are needed to determine 'c1' and
3959 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3960 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3961 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3962 * need to fold as many characters as a single character can fold to,
3963 * so that later we can check if the first ones are such a multi-char
3964 * fold. But, in such a pattern only locale-problematic characters
3965 * aren't folded, so we can skip this completely if the first character
3966 * in the node isn't one of the tricky ones */
3967 if (OP(text_node) == EXACTFL) {
3969 if (! is_utf8_pat) {
3970 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3972 folded[0] = folded[1] = 's';
3974 pat_end = folded + 2;
3977 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3982 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3984 *(d++) = (U8) toFOLD_LC(*s);
3989 _to_utf8_fold_flags(s,
3992 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4003 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4004 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4006 /* Multi-character folds require more context to sort out. Also
4007 * PL_utf8_foldclosures used below doesn't handle them, so have to
4008 * be handled outside this routine */
4009 use_chrtest_void = TRUE;
4011 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4012 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4014 /* Load the folds hash, if not already done */
4016 if (! PL_utf8_foldclosures) {
4017 _load_PL_utf8_foldclosures();
4020 /* The fold closures data structure is a hash with the keys
4021 * being the UTF-8 of every character that is folded to, like
4022 * 'k', and the values each an array of all code points that
4023 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4024 * Multi-character folds are not included */
4025 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4030 /* Not found in the hash, therefore there are no folds
4031 * containing it, so there is only a single character that
4035 else { /* Does participate in folds */
4036 AV* list = (AV*) *listp;
4037 if (av_tindex(list) != 1) {
4039 /* If there aren't exactly two folds to this, it is
4040 * outside the scope of this function */
4041 use_chrtest_void = TRUE;
4043 else { /* There are two. Get them */
4044 SV** c_p = av_fetch(list, 0, FALSE);
4046 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4050 c_p = av_fetch(list, 1, FALSE);
4052 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4056 /* Folds that cross the 255/256 boundary are forbidden
4057 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4058 * one is ASCIII. Since the pattern character is above
4059 * 255, and its only other match is below 256, the only
4060 * legal match will be to itself. We have thrown away
4061 * the original, so have to compute which is the one
4063 if ((c1 < 256) != (c2 < 256)) {
4064 if ((OP(text_node) == EXACTFL
4065 && ! IN_UTF8_CTYPE_LOCALE)
4066 || ((OP(text_node) == EXACTFA
4067 || OP(text_node) == EXACTFA_NO_TRIE)
4068 && (isASCII(c1) || isASCII(c2))))
4081 else /* Here, c1 is <= 255 */
4083 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4084 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4085 && ((OP(text_node) != EXACTFA
4086 && OP(text_node) != EXACTFA_NO_TRIE)
4089 /* Here, there could be something above Latin1 in the target
4090 * which folds to this character in the pattern. All such
4091 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4092 * than two characters involved in their folds, so are outside
4093 * the scope of this function */
4094 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4095 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4098 use_chrtest_void = TRUE;
4101 else { /* Here nothing above Latin1 can fold to the pattern
4103 switch (OP(text_node)) {
4105 case EXACTFL: /* /l rules */
4106 c2 = PL_fold_locale[c1];
4109 case EXACTF: /* This node only generated for non-utf8
4111 assert(! is_utf8_pat);
4112 if (! utf8_target) { /* /d rules */
4117 /* /u rules for all these. This happens to work for
4118 * EXACTFA as nothing in Latin1 folds to ASCII */
4119 case EXACTFA_NO_TRIE: /* This node only generated for
4120 non-utf8 patterns */
4121 assert(! is_utf8_pat);
4126 c2 = PL_fold_latin1[c1];
4130 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4131 NOT_REACHED; /* NOTREACHED */
4137 /* Here have figured things out. Set up the returns */
4138 if (use_chrtest_void) {
4139 *c2p = *c1p = CHRTEST_VOID;
4141 else if (utf8_target) {
4142 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4143 uvchr_to_utf8(c1_utf8, c1);
4144 uvchr_to_utf8(c2_utf8, c2);
4147 /* Invariants are stored in both the utf8 and byte outputs; Use
4148 * negative numbers otherwise for the byte ones. Make sure that the
4149 * byte ones are the same iff the utf8 ones are the same */
4150 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4151 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4154 ? CHRTEST_NOT_A_CP_1
4155 : CHRTEST_NOT_A_CP_2;
4157 else if (c1 > 255) {
4158 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4163 *c1p = *c2p = c2; /* c2 is the only representable value */
4165 else { /* c1 is representable; see about c2 */
4167 *c2p = (c2 < 256) ? c2 : c1;
4173 /* This creates a single number by combining two, with 'before' being like the
4174 * 10's digit, but this isn't necessarily base 10; it is base however many
4175 * elements of the enum there are */
4176 #define GCBcase(before, after) ((GCB_ENUM_COUNT * before) + after)
4179 S_isGCB(const GCB_enum before, const GCB_enum after)
4181 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4182 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4184 switch (GCBcase(before, after)) {
4186 /* Break at the start and end of text.
4190 Break before and after controls except between CR and LF
4191 GB4. ( Control | CR | LF ) ÷
4192 GB5. ÷ ( Control | CR | LF )
4194 Otherwise, break everywhere.
4199 /* Do not break between a CR and LF.
4201 case GCBcase(GCB_CR, GCB_LF):
4204 /* Do not break Hangul syllable sequences.
4205 GB6. L × ( L | V | LV | LVT ) */
4206 case GCBcase(GCB_L, GCB_L):
4207 case GCBcase(GCB_L, GCB_V):
4208 case GCBcase(GCB_L, GCB_LV):
4209 case GCBcase(GCB_L, GCB_LVT):
4212 /* GB7. ( LV | V ) × ( V | T ) */
4213 case GCBcase(GCB_LV, GCB_V):
4214 case GCBcase(GCB_LV, GCB_T):
4215 case GCBcase(GCB_V, GCB_V):
4216 case GCBcase(GCB_V, GCB_T):
4219 /* GB8. ( LVT | T) × T */
4220 case GCBcase(GCB_LVT, GCB_T):
4221 case GCBcase(GCB_T, GCB_T):
4224 /* Do not break between regional indicator symbols.
4225 GB8a. Regional_Indicator × Regional_Indicator */
4226 case GCBcase(GCB_Regional_Indicator, GCB_Regional_Indicator):
4229 /* Do not break before extending characters.
4231 case GCBcase(GCB_Other, GCB_Extend):
4232 case GCBcase(GCB_Extend, GCB_Extend):
4233 case GCBcase(GCB_L, GCB_Extend):
4234 case GCBcase(GCB_LV, GCB_Extend):
4235 case GCBcase(GCB_LVT, GCB_Extend):
4236 case GCBcase(GCB_Prepend, GCB_Extend):
4237 case GCBcase(GCB_Regional_Indicator, GCB_Extend):
4238 case GCBcase(GCB_SpacingMark, GCB_Extend):
4239 case GCBcase(GCB_T, GCB_Extend):
4240 case GCBcase(GCB_V, GCB_Extend):
4243 /* Do not break before SpacingMarks, or after Prepend characters.
4244 GB9a. × SpacingMark */
4245 case GCBcase(GCB_Other, GCB_SpacingMark):
4246 case GCBcase(GCB_Extend, GCB_SpacingMark):
4247 case GCBcase(GCB_L, GCB_SpacingMark):
4248 case GCBcase(GCB_LV, GCB_SpacingMark):
4249 case GCBcase(GCB_LVT, GCB_SpacingMark):
4250 case GCBcase(GCB_Prepend, GCB_SpacingMark):
4251 case GCBcase(GCB_Regional_Indicator, GCB_SpacingMark):
4252 case GCBcase(GCB_SpacingMark, GCB_SpacingMark):
4253 case GCBcase(GCB_T, GCB_SpacingMark):
4254 case GCBcase(GCB_V, GCB_SpacingMark):
4257 /* GB9b. Prepend × */
4258 case GCBcase(GCB_Prepend, GCB_Other):
4259 case GCBcase(GCB_Prepend, GCB_L):
4260 case GCBcase(GCB_Prepend, GCB_LV):
4261 case GCBcase(GCB_Prepend, GCB_LVT):
4262 case GCBcase(GCB_Prepend, GCB_Prepend):
4263 case GCBcase(GCB_Prepend, GCB_Regional_Indicator):
4264 case GCBcase(GCB_Prepend, GCB_T):
4265 case GCBcase(GCB_Prepend, GCB_V):
4269 NOT_REACHED; /* NOTREACHED */
4272 #define SBcase(before, after) ((SB_ENUM_COUNT * before) + after)
4275 S_isSB(pTHX_ SB_enum before,
4277 const U8 * const strbeg,
4278 const U8 * const curpos,
4279 const U8 * const strend,
4280 const bool utf8_target)
4282 /* returns a boolean indicating if there is a Sentence Boundary Break
4283 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4285 U8 * lpos = (U8 *) curpos;
4289 PERL_ARGS_ASSERT_ISSB;
4291 /* Break at the start and end of text.
4294 if (before == SB_EDGE || after == SB_EDGE) {
4298 /* SB 3: Do not break within CRLF. */
4299 if (before == SB_CR && after == SB_LF) {
4303 /* Break after paragraph separators. (though why CR and LF are considered
4304 * so is beyond me (khw)
4305 SB4. Sep | CR | LF ÷ */
4306 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4310 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4311 * (See Section 6.2, Replacing Ignore Rules.)
4312 SB5. X (Extend | Format)* → X */
4313 if (after == SB_Extend || after == SB_Format) {
4317 if (before == SB_Extend || before == SB_Format) {
4318 before = backup_one_SB(strbeg, &lpos, utf8_target);
4321 /* Do not break after ambiguous terminators like period, if they are
4322 * immediately followed by a number or lowercase letter, if they are
4323 * between uppercase letters, if the first following letter (optionally
4324 * after certain punctuation) is lowercase, or if they are followed by
4325 * "continuation" punctuation such as comma, colon, or semicolon. For
4326 * example, a period may be an abbreviation or numeric period, and thus may
4327 * not mark the end of a sentence.
4329 * SB6. ATerm × Numeric */
4330 if (before == SB_ATerm && after == SB_Numeric) {
4334 /* SB7. (Upper | Lower) ATerm × Upper */
4335 if (before == SB_ATerm && after == SB_Upper) {
4337 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4338 if (backup == SB_Upper || backup == SB_Lower) {
4343 /* SB8a. (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4344 * SB10. (STerm | ATerm) Close* Sp* × ( Sp | Sep | CR | LF ) */
4347 while (backup == SB_Sp) {
4348 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4350 while (backup == SB_Close) {
4351 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4353 if ((backup == SB_STerm || backup == SB_ATerm)
4354 && ( after == SB_SContinue
4355 || after == SB_STerm
4356 || after == SB_ATerm
4365 /* SB8. ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR | LF |
4366 * STerm | ATerm) )* Lower */
4367 if (backup == SB_ATerm) {
4368 U8 * rpos = (U8 *) curpos;
4369 SB_enum later = after;
4371 while ( later != SB_OLetter
4372 && later != SB_Upper
4373 && later != SB_Lower
4377 && later != SB_STerm
4378 && later != SB_ATerm
4379 && later != SB_EDGE)
4381 later = advance_one_SB(&rpos, strend, utf8_target);
4383 if (later == SB_Lower) {
4388 /* Break after sentence terminators, but include closing punctuation,
4389 * trailing spaces, and a paragraph separator (if present). [See note
4391 * SB9. ( STerm | ATerm ) Close* × ( Close | Sp | Sep | CR | LF ) */
4394 while (backup == SB_Close) {
4395 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4397 if ((backup == SB_STerm || backup == SB_ATerm)
4398 && ( after == SB_Close
4408 /* SB11. ( STerm | ATerm ) Close* Sp* ( Sep | CR | LF )? ÷ */
4410 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4411 if ( backup == SB_Sep
4420 while (backup == SB_Sp) {
4421 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4423 while (backup == SB_Close) {
4424 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4426 if (backup == SB_STerm || backup == SB_ATerm) {
4430 /* Otherwise, do not break.
4437 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4441 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4443 if (*curpos >= strend) {
4449 *curpos += UTF8SKIP(*curpos);
4450 if (*curpos >= strend) {
4453 sb = getSB_VAL_UTF8(*curpos, strend);
4454 } while (sb == SB_Extend || sb == SB_Format);
4459 if (*curpos >= strend) {
4462 sb = getSB_VAL_CP(**curpos);
4463 } while (sb == SB_Extend || sb == SB_Format);
4470 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4474 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4476 if (*curpos < strbeg) {
4481 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4482 if (! prev_char_pos) {
4486 /* Back up over Extend and Format. curpos is always just to the right
4487 * of the characater whose value we are getting */
4489 U8 * prev_prev_char_pos;
4490 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4493 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4494 *curpos = prev_char_pos;
4495 prev_char_pos = prev_prev_char_pos;
4498 *curpos = (U8 *) strbeg;
4501 } while (sb == SB_Extend || sb == SB_Format);
4505 if (*curpos - 2 < strbeg) {
4506 *curpos = (U8 *) strbeg;
4510 sb = getSB_VAL_CP(*(*curpos - 1));
4511 } while (sb == SB_Extend || sb == SB_Format);
4517 #define WBcase(before, after) ((WB_ENUM_COUNT * before) + after)
4520 S_isWB(pTHX_ WB_enum previous,
4523 const U8 * const strbeg,
4524 const U8 * const curpos,
4525 const U8 * const strend,
4526 const bool utf8_target)
4528 /* Return a boolean as to if the boundary between 'before' and 'after' is
4529 * a Unicode word break, using their published algorithm. Context may be
4530 * needed to make this determination. If the value for the character
4531 * before 'before' is known, it is passed as 'previous'; otherwise that
4532 * should be set to WB_UNKNOWN. The other input parameters give the
4533 * boundaries and current position in the matching of the string. That
4534 * is, 'curpos' marks the position where the character whose wb value is
4535 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
4537 U8 * before_pos = (U8 *) curpos;
4538 U8 * after_pos = (U8 *) curpos;
4540 PERL_ARGS_ASSERT_ISWB;
4542 /* WB1 and WB2: Break at the start and end of text. */
4543 if (before == WB_EDGE || after == WB_EDGE) {
4547 /* WB 3: Do not break within CRLF. */
4548 if (before == WB_CR && after == WB_LF) {
4552 /* WB 3a and WB 3b: Otherwise break before and after Newlines (including CR
4554 if ( before == WB_CR || before == WB_LF || before == WB_Newline
4555 || after == WB_CR || after == WB_LF || after == WB_Newline)
4560 /* Ignore Format and Extend characters, except when they appear at the
4561 * beginning of a region of text.
4562 * WB4. X (Extend | Format)* → X. */
4564 if (after == WB_Extend || after == WB_Format) {
4568 if (before == WB_Extend || before == WB_Format) {
4569 before = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4572 switch (WBcase(before, after)) {
4573 /* Otherwise, break everywhere (including around ideographs).
4578 /* Do not break between most letters.
4579 WB5. (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) */
4580 case WBcase(WB_ALetter, WB_ALetter):
4581 case WBcase(WB_ALetter, WB_Hebrew_Letter):
4582 case WBcase(WB_Hebrew_Letter, WB_ALetter):
4583 case WBcase(WB_Hebrew_Letter, WB_Hebrew_Letter):
4586 /* Do not break letters across certain punctuation.
4587 WB6. (ALetter | Hebrew_Letter)
4588 × (MidLetter | MidNumLet | Single_Quote) (ALetter
4590 case WBcase(WB_ALetter, WB_MidLetter):
4591 case WBcase(WB_ALetter, WB_MidNumLet):
4592 case WBcase(WB_ALetter, WB_Single_Quote):
4593 case WBcase(WB_Hebrew_Letter, WB_MidLetter):
4594 case WBcase(WB_Hebrew_Letter, WB_MidNumLet):
4595 /*case WBcase(WB_Hebrew_Letter, WB_Single_Quote):*/
4596 after = advance_one_WB(&after_pos, strend, utf8_target);
4597 return after != WB_ALetter && after != WB_Hebrew_Letter;
4599 /* WB7. (ALetter | Hebrew_Letter) (MidLetter | MidNumLet |
4600 * Single_Quote) × (ALetter | Hebrew_Letter) */
4601 case WBcase(WB_MidLetter, WB_ALetter):
4602 case WBcase(WB_MidLetter, WB_Hebrew_Letter):
4603 case WBcase(WB_MidNumLet, WB_ALetter):
4604 case WBcase(WB_MidNumLet, WB_Hebrew_Letter):
4605 case WBcase(WB_Single_Quote, WB_ALetter):
4606 case WBcase(WB_Single_Quote, WB_Hebrew_Letter):
4608 = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4609 return before != WB_ALetter && before != WB_Hebrew_Letter;
4611 /* WB7a. Hebrew_Letter × Single_Quote */
4612 case WBcase(WB_Hebrew_Letter, WB_Single_Quote):
4615 /* WB7b. Hebrew_Letter × Double_Quote Hebrew_Letter */
4616 case WBcase(WB_Hebrew_Letter, WB_Double_Quote):
4617 return advance_one_WB(&after_pos, strend, utf8_target)
4618 != WB_Hebrew_Letter;
4620 /* WB7c. Hebrew_Letter Double_Quote × Hebrew_Letter */
4621 case WBcase(WB_Double_Quote, WB_Hebrew_Letter):
4622 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4623 != WB_Hebrew_Letter;
4625 /* Do not break within sequences of digits, or digits adjacent to
4626 * letters (“3a”, or “A3”).
4627 WB8. Numeric × Numeric */
4628 case WBcase(WB_Numeric, WB_Numeric):
4631 /* WB9. (ALetter | Hebrew_Letter) × Numeric */
4632 case WBcase(WB_ALetter, WB_Numeric):
4633 case WBcase(WB_Hebrew_Letter, WB_Numeric):
4636 /* WB10. Numeric × (ALetter | Hebrew_Letter) */
4637 case WBcase(WB_Numeric, WB_ALetter):
4638 case WBcase(WB_Numeric, WB_Hebrew_Letter):
4641 /* Do not break within sequences, such as “3.2” or “3,456.789”.
4642 WB11. Numeric (MidNum | MidNumLet | Single_Quote) × Numeric
4644 case WBcase(WB_MidNum, WB_Numeric):
4645 case WBcase(WB_MidNumLet, WB_Numeric):
4646 case WBcase(WB_Single_Quote, WB_Numeric):
4647 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4650 /* WB12. Numeric × (MidNum | MidNumLet | Single_Quote) Numeric
4652 case WBcase(WB_Numeric, WB_MidNum):
4653 case WBcase(WB_Numeric, WB_MidNumLet):
4654 case WBcase(WB_Numeric, WB_Single_Quote):
4655 return advance_one_WB(&after_pos, strend, utf8_target)
4658 /* Do not break between Katakana.
4659 WB13. Katakana × Katakana */
4660 case WBcase(WB_Katakana, WB_Katakana):
4663 /* Do not break from extenders.
4664 WB13a. (ALetter | Hebrew_Letter | Numeric | Katakana |
4665 ExtendNumLet) × ExtendNumLet */
4666 case WBcase(WB_ALetter, WB_ExtendNumLet):
4667 case WBcase(WB_Hebrew_Letter, WB_ExtendNumLet):
4668 case WBcase(WB_Numeric, WB_ExtendNumLet):
4669 case WBcase(WB_Katakana, WB_ExtendNumLet):
4670 case WBcase(WB_ExtendNumLet, WB_ExtendNumLet):
4673 /* WB13b. ExtendNumLet × (ALetter | Hebrew_Letter | Numeric
4675 case WBcase(WB_ExtendNumLet, WB_ALetter):
4676 case WBcase(WB_ExtendNumLet, WB_Hebrew_Letter):
4677 case WBcase(WB_ExtendNumLet, WB_Numeric):
4678 case WBcase(WB_ExtendNumLet, WB_Katakana):
4681 /* Do not break between regional indicator symbols.
4682 WB13c. Regional_Indicator × Regional_Indicator */
4683 case WBcase(WB_Regional_Indicator, WB_Regional_Indicator):
4688 NOT_REACHED; /* NOTREACHED */
4692 S_advance_one_WB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4696 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
4698 if (*curpos >= strend) {
4704 /* Advance over Extend and Format */
4706 *curpos += UTF8SKIP(*curpos);
4707 if (*curpos >= strend) {
4710 wb = getWB_VAL_UTF8(*curpos, strend);
4711 } while (wb == WB_Extend || wb == WB_Format);
4716 if (*curpos >= strend) {
4719 wb = getWB_VAL_CP(**curpos);
4720 } while (wb == WB_Extend || wb == WB_Format);
4727 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4731 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
4733 /* If we know what the previous character's break value is, don't have
4735 if (*previous != WB_UNKNOWN) {
4737 *previous = WB_UNKNOWN;
4738 /* XXX Note that doesn't change curpos, and maybe should */
4740 /* But we always back up over these two types */
4741 if (wb != WB_Extend && wb != WB_Format) {
4746 if (*curpos < strbeg) {
4751 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4752 if (! prev_char_pos) {
4756 /* Back up over Extend and Format. curpos is always just to the right
4757 * of the characater whose value we are getting */
4759 U8 * prev_prev_char_pos;
4760 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
4764 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4765 *curpos = prev_char_pos;
4766 prev_char_pos = prev_prev_char_pos;
4769 *curpos = (U8 *) strbeg;
4772 } while (wb == WB_Extend || wb == WB_Format);
4776 if (*curpos - 2 < strbeg) {
4777 *curpos = (U8 *) strbeg;
4781 wb = getWB_VAL_CP(*(*curpos - 1));
4782 } while (wb == WB_Extend || wb == WB_Format);
4788 /* returns -1 on failure, $+[0] on success */
4790 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
4792 #if PERL_VERSION < 9 && !defined(PERL_CORE)
4796 const bool utf8_target = reginfo->is_utf8_target;
4797 const U32 uniflags = UTF8_ALLOW_DEFAULT;
4798 REGEXP *rex_sv = reginfo->prog;
4799 regexp *rex = ReANY(rex_sv);
4800 RXi_GET_DECL(rex,rexi);
4801 /* the current state. This is a cached copy of PL_regmatch_state */
4803 /* cache heavy used fields of st in registers */
4806 U32 n = 0; /* general value; init to avoid compiler warning */
4807 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
4808 char *locinput = startpos;
4809 char *pushinput; /* where to continue after a PUSH */
4810 I32 nextchr; /* is always set to UCHARAT(locinput) */
4812 bool result = 0; /* return value of S_regmatch */
4813 int depth = 0; /* depth of backtrack stack */
4814 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
4815 const U32 max_nochange_depth =
4816 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
4817 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
4818 regmatch_state *yes_state = NULL; /* state to pop to on success of
4820 /* mark_state piggy backs on the yes_state logic so that when we unwind
4821 the stack on success we can update the mark_state as we go */
4822 regmatch_state *mark_state = NULL; /* last mark state we have seen */
4823 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
4824 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
4826 bool no_final = 0; /* prevent failure from backtracking? */
4827 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
4828 char *startpoint = locinput;
4829 SV *popmark = NULL; /* are we looking for a mark? */
4830 SV *sv_commit = NULL; /* last mark name seen in failure */
4831 SV *sv_yes_mark = NULL; /* last mark name we have seen
4832 during a successful match */
4833 U32 lastopen = 0; /* last open we saw */
4834 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
4835 SV* const oreplsv = GvSVn(PL_replgv);
4836 /* these three flags are set by various ops to signal information to
4837 * the very next op. They have a useful lifetime of exactly one loop
4838 * iteration, and are not preserved or restored by state pushes/pops
4840 bool sw = 0; /* the condition value in (?(cond)a|b) */
4841 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
4842 int logical = 0; /* the following EVAL is:
4846 or the following IFMATCH/UNLESSM is:
4847 false: plain (?=foo)
4848 true: used as a condition: (?(?=foo))
4850 PAD* last_pad = NULL;
4852 I32 gimme = G_SCALAR;
4853 CV *caller_cv = NULL; /* who called us */
4854 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
4855 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
4856 U32 maxopenparen = 0; /* max '(' index seen so far */
4857 int to_complement; /* Invert the result? */
4858 _char_class_number classnum;
4859 bool is_utf8_pat = reginfo->is_utf8_pat;
4864 GET_RE_DEBUG_FLAGS_DECL;
4867 /* protect against undef(*^R) */
4868 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
4870 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
4871 multicall_oldcatch = 0;
4872 multicall_cv = NULL;
4874 PERL_UNUSED_VAR(multicall_cop);
4875 PERL_UNUSED_VAR(newsp);
4878 PERL_ARGS_ASSERT_REGMATCH;
4880 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
4881 PerlIO_printf(Perl_debug_log,"regmatch start\n");
4884 st = PL_regmatch_state;
4886 /* Note that nextchr is a byte even in UTF */
4889 while (scan != NULL) {
4892 SV * const prop = sv_newmortal();
4893 regnode *rnext=regnext(scan);
4894 DUMP_EXEC_POS( locinput, scan, utf8_target );
4895 regprop(rex, prop, scan, reginfo, NULL);
4897 PerlIO_printf(Perl_debug_log,
4898 "%3"IVdf":%*s%s(%"IVdf")\n",
4899 (IV)(scan - rexi->program), depth*2, "",
4901 (PL_regkind[OP(scan)] == END || !rnext) ?
4902 0 : (IV)(rnext - rexi->program));
4905 next = scan + NEXT_OFF(scan);
4908 state_num = OP(scan);
4914 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
4916 switch (state_num) {
4917 case SBOL: /* /^../ and /\A../ */
4918 if (locinput == reginfo->strbeg)
4922 case MBOL: /* /^../m */
4923 if (locinput == reginfo->strbeg ||
4924 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4931 if (locinput == reginfo->ganch)
4935 case KEEPS: /* \K */
4936 /* update the startpoint */
4937 st->u.keeper.val = rex->offs[0].start;
4938 rex->offs[0].start = locinput - reginfo->strbeg;
4939 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4941 NOT_REACHED; /* NOTREACHED */
4943 case KEEPS_next_fail:
4944 /* rollback the start point change */
4945 rex->offs[0].start = st->u.keeper.val;
4948 NOT_REACHED; /* NOTREACHED */
4950 case MEOL: /* /..$/m */
4951 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4955 case SEOL: /* /..$/ */
4956 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4958 if (reginfo->strend - locinput > 1)
4963 if (!NEXTCHR_IS_EOS)
4967 case SANY: /* /./s */
4970 goto increment_locinput;
4972 case REG_ANY: /* /./ */
4973 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4975 goto increment_locinput;
4979 #define ST st->u.trie
4980 case TRIEC: /* (ab|cd) with known charclass */
4981 /* In this case the charclass data is available inline so
4982 we can fail fast without a lot of extra overhead.
4984 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
4986 PerlIO_printf(Perl_debug_log,
4987 "%*s %sfailed to match trie start class...%s\n",
4988 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4992 NOT_REACHED; /* NOTREACHED */
4995 case TRIE: /* (ab|cd) */
4996 /* the basic plan of execution of the trie is:
4997 * At the beginning, run though all the states, and
4998 * find the longest-matching word. Also remember the position
4999 * of the shortest matching word. For example, this pattern:
5002 * when matched against the string "abcde", will generate
5003 * accept states for all words except 3, with the longest
5004 * matching word being 4, and the shortest being 2 (with
5005 * the position being after char 1 of the string).
5007 * Then for each matching word, in word order (i.e. 1,2,4,5),
5008 * we run the remainder of the pattern; on each try setting
5009 * the current position to the character following the word,
5010 * returning to try the next word on failure.
5012 * We avoid having to build a list of words at runtime by
5013 * using a compile-time structure, wordinfo[].prev, which
5014 * gives, for each word, the previous accepting word (if any).
5015 * In the case above it would contain the mappings 1->2, 2->0,
5016 * 3->0, 4->5, 5->1. We can use this table to generate, from
5017 * the longest word (4 above), a list of all words, by
5018 * following the list of prev pointers; this gives us the
5019 * unordered list 4,5,1,2. Then given the current word we have
5020 * just tried, we can go through the list and find the
5021 * next-biggest word to try (so if we just failed on word 2,
5022 * the next in the list is 4).
5024 * Since at runtime we don't record the matching position in
5025 * the string for each word, we have to work that out for
5026 * each word we're about to process. The wordinfo table holds
5027 * the character length of each word; given that we recorded
5028 * at the start: the position of the shortest word and its
5029 * length in chars, we just need to move the pointer the
5030 * difference between the two char lengths. Depending on
5031 * Unicode status and folding, that's cheap or expensive.
5033 * This algorithm is optimised for the case where are only a
5034 * small number of accept states, i.e. 0,1, or maybe 2.
5035 * With lots of accepts states, and having to try all of them,
5036 * it becomes quadratic on number of accept states to find all
5041 /* what type of TRIE am I? (utf8 makes this contextual) */
5042 DECL_TRIE_TYPE(scan);
5044 /* what trie are we using right now */
5045 reg_trie_data * const trie
5046 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5047 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5048 U32 state = trie->startstate;
5050 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5051 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5053 && UTF8_IS_ABOVE_LATIN1(nextchr)
5054 && scan->flags == EXACTL)
5056 /* We only output for EXACTL, as we let the folder
5057 * output this message for EXACTFLU8 to avoid
5059 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5064 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5066 if (trie->states[ state ].wordnum) {
5068 PerlIO_printf(Perl_debug_log,
5069 "%*s %smatched empty string...%s\n",
5070 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5076 PerlIO_printf(Perl_debug_log,
5077 "%*s %sfailed to match trie start class...%s\n",
5078 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5085 U8 *uc = ( U8* )locinput;
5089 U8 *uscan = (U8*)NULL;
5090 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5091 U32 charcount = 0; /* how many input chars we have matched */
5092 U32 accepted = 0; /* have we seen any accepting states? */
5094 ST.jump = trie->jump;
5097 ST.longfold = FALSE; /* char longer if folded => it's harder */
5100 /* fully traverse the TRIE; note the position of the
5101 shortest accept state and the wordnum of the longest
5104 while ( state && uc <= (U8*)(reginfo->strend) ) {
5105 U32 base = trie->states[ state ].trans.base;
5109 wordnum = trie->states[ state ].wordnum;
5111 if (wordnum) { /* it's an accept state */
5114 /* record first match position */
5116 ST.firstpos = (U8*)locinput;
5121 ST.firstchars = charcount;
5124 if (!ST.nextword || wordnum < ST.nextword)
5125 ST.nextword = wordnum;
5126 ST.topword = wordnum;
5129 DEBUG_TRIE_EXECUTE_r({
5130 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5131 PerlIO_printf( Perl_debug_log,
5132 "%*s %sState: %4"UVxf" Accepted: %c ",
5133 2+depth * 2, "", PL_colors[4],
5134 (UV)state, (accepted ? 'Y' : 'N'));
5137 /* read a char and goto next state */
5138 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5140 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5141 uscan, len, uvc, charid, foldlen,
5148 base + charid - 1 - trie->uniquecharcount)) >= 0)
5150 && ((U32)offset < trie->lasttrans)
5151 && trie->trans[offset].check == state)
5153 state = trie->trans[offset].next;
5164 DEBUG_TRIE_EXECUTE_r(
5165 PerlIO_printf( Perl_debug_log,
5166 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5167 charid, uvc, (UV)state, PL_colors[5] );
5173 /* calculate total number of accept states */
5178 w = trie->wordinfo[w].prev;
5181 ST.accepted = accepted;
5185 PerlIO_printf( Perl_debug_log,
5186 "%*s %sgot %"IVdf" possible matches%s\n",
5187 REPORT_CODE_OFF + depth * 2, "",
5188 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5190 goto trie_first_try; /* jump into the fail handler */
5193 NOT_REACHED; /* NOTREACHED */
5195 case TRIE_next_fail: /* we failed - try next alternative */
5199 REGCP_UNWIND(ST.cp);
5200 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5202 if (!--ST.accepted) {
5204 PerlIO_printf( Perl_debug_log,
5205 "%*s %sTRIE failed...%s\n",
5206 REPORT_CODE_OFF+depth*2, "",
5213 /* Find next-highest word to process. Note that this code
5214 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5217 U16 const nextword = ST.nextword;
5218 reg_trie_wordinfo * const wordinfo
5219 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5220 for (word=ST.topword; word; word=wordinfo[word].prev) {
5221 if (word > nextword && (!min || word < min))
5234 ST.lastparen = rex->lastparen;
5235 ST.lastcloseparen = rex->lastcloseparen;
5239 /* find start char of end of current word */
5241 U32 chars; /* how many chars to skip */
5242 reg_trie_data * const trie
5243 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5245 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5247 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5252 /* the hard option - fold each char in turn and find
5253 * its folded length (which may be different */
5254 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5262 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5270 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5275 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5291 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5292 ? ST.jump[ST.nextword]
5296 PerlIO_printf( Perl_debug_log,
5297 "%*s %sTRIE matched word #%d, continuing%s\n",
5298 REPORT_CODE_OFF+depth*2, "",
5305 if (ST.accepted > 1 || has_cutgroup) {
5306 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5308 NOT_REACHED; /* NOTREACHED */
5310 /* only one choice left - just continue */
5312 AV *const trie_words
5313 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5314 SV ** const tmp = trie_words
5315 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5316 SV *sv= tmp ? sv_newmortal() : NULL;
5318 PerlIO_printf( Perl_debug_log,
5319 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
5320 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5322 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5323 PL_colors[0], PL_colors[1],
5324 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5326 : "not compiled under -Dr",
5330 locinput = (char*)uc;
5331 continue; /* execute rest of RE */
5336 case EXACTL: /* /abc/l */
5337 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5339 /* Complete checking would involve going through every character
5340 * matched by the string to see if any is above latin1. But the
5341 * comparision otherwise might very well be a fast assembly
5342 * language routine, and I (khw) don't think slowing things down
5343 * just to check for this warning is worth it. So this just checks
5344 * the first character */
5345 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5346 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5349 case EXACT: { /* /abc/ */
5350 char *s = STRING(scan);
5352 if (utf8_target != is_utf8_pat) {
5353 /* The target and the pattern have differing utf8ness. */
5355 const char * const e = s + ln;
5358 /* The target is utf8, the pattern is not utf8.
5359 * Above-Latin1 code points can't match the pattern;
5360 * invariants match exactly, and the other Latin1 ones need
5361 * to be downgraded to a single byte in order to do the
5362 * comparison. (If we could be confident that the target
5363 * is not malformed, this could be refactored to have fewer
5364 * tests by just assuming that if the first bytes match, it
5365 * is an invariant, but there are tests in the test suite
5366 * dealing with (??{...}) which violate this) */
5368 if (l >= reginfo->strend
5369 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5373 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5380 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5390 /* The target is not utf8, the pattern is utf8. */
5392 if (l >= reginfo->strend
5393 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5397 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5404 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5416 /* The target and the pattern have the same utf8ness. */
5417 /* Inline the first character, for speed. */
5418 if (reginfo->strend - locinput < ln
5419 || UCHARAT(s) != nextchr
5420 || (ln > 1 && memNE(s, locinput, ln)))
5429 case EXACTFL: { /* /abc/il */
5431 const U8 * fold_array;
5433 U32 fold_utf8_flags;
5435 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5436 folder = foldEQ_locale;
5437 fold_array = PL_fold_locale;
5438 fold_utf8_flags = FOLDEQ_LOCALE;
5441 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5442 is effectively /u; hence to match, target
5444 if (! utf8_target) {
5447 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5448 | FOLDEQ_S1_FOLDS_SANE;
5449 folder = foldEQ_latin1;
5450 fold_array = PL_fold_latin1;
5453 case EXACTFU_SS: /* /\x{df}/iu */
5454 case EXACTFU: /* /abc/iu */
5455 folder = foldEQ_latin1;
5456 fold_array = PL_fold_latin1;
5457 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5460 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5462 assert(! is_utf8_pat);
5464 case EXACTFA: /* /abc/iaa */
5465 folder = foldEQ_latin1;
5466 fold_array = PL_fold_latin1;
5467 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5470 case EXACTF: /* /abc/i This node only generated for
5471 non-utf8 patterns */
5472 assert(! is_utf8_pat);
5474 fold_array = PL_fold;
5475 fold_utf8_flags = 0;
5483 || state_num == EXACTFU_SS
5484 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5486 /* Either target or the pattern are utf8, or has the issue where
5487 * the fold lengths may differ. */
5488 const char * const l = locinput;
5489 char *e = reginfo->strend;
5491 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
5492 l, &e, 0, utf8_target, fold_utf8_flags))
5500 /* Neither the target nor the pattern are utf8 */
5501 if (UCHARAT(s) != nextchr
5503 && UCHARAT(s) != fold_array[nextchr])
5507 if (reginfo->strend - locinput < ln)
5509 if (ln > 1 && ! folder(s, locinput, ln))
5515 case NBOUNDL: /* /\B/l */
5519 case BOUNDL: /* /\b/l */
5520 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5522 if (FLAGS(scan) != TRADITIONAL_BOUND) {
5523 if (! IN_UTF8_CTYPE_LOCALE) {
5524 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5525 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5531 if (locinput == reginfo->strbeg)
5532 ln = isWORDCHAR_LC('\n');
5534 ln = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5535 (U8*)(reginfo->strbeg)));
5537 n = (NEXTCHR_IS_EOS)
5538 ? isWORDCHAR_LC('\n')
5539 : isWORDCHAR_LC_utf8((U8*)locinput);
5541 else { /* Here the string isn't utf8 */
5542 ln = (locinput == reginfo->strbeg)
5543 ? isWORDCHAR_LC('\n')
5544 : isWORDCHAR_LC(UCHARAT(locinput - 1));
5545 n = (NEXTCHR_IS_EOS)
5546 ? isWORDCHAR_LC('\n')
5547 : isWORDCHAR_LC(nextchr);
5549 if (to_complement ^ (ln == n)) {
5554 case NBOUND: /* /\B/ */
5558 case BOUND: /* /\b/ */
5562 goto bound_ascii_match_only;
5564 case NBOUNDA: /* /\B/a */
5568 case BOUNDA: /* /\b/a */
5570 bound_ascii_match_only:
5571 /* Here the string isn't utf8, or is utf8 and only ascii characters
5572 * are to match \w. In the latter case looking at the byte just
5573 * prior to the current one may be just the final byte of a
5574 * multi-byte character. This is ok. There are two cases:
5575 * 1) it is a single byte character, and then the test is doing
5576 * just what it's supposed to.
5577 * 2) it is a multi-byte character, in which case the final byte is
5578 * never mistakable for ASCII, and so the test will say it is
5579 * not a word character, which is the correct answer. */
5580 ln = (locinput == reginfo->strbeg)
5581 ? isWORDCHAR_A('\n')
5582 : isWORDCHAR_A(UCHARAT(locinput - 1));
5583 n = (NEXTCHR_IS_EOS)
5584 ? isWORDCHAR_A('\n')
5585 : isWORDCHAR_A(nextchr);
5586 if (to_complement ^ (ln == n)) {
5591 case NBOUNDU: /* /\B/u */
5595 case BOUNDU: /* /\b/u */
5601 switch((bound_type) FLAGS(scan)) {
5602 case TRADITIONAL_BOUND:
5603 ln = (locinput == reginfo->strbeg)
5604 ? 0 /* isWORDCHAR_L1('\n') */
5605 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5606 (U8*)(reginfo->strbeg)));
5607 n = (NEXTCHR_IS_EOS)
5608 ? 0 /* isWORDCHAR_L1('\n') */
5609 : isWORDCHAR_utf8((U8*)locinput);
5610 match = cBOOL(ln != n);
5613 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5614 match = TRUE; /* GCB always matches at begin and
5618 /* Find the gcb values of previous and current
5619 * chars, then see if is a break point */
5620 match = isGCB(getGCB_VAL_UTF8(
5621 reghop3((U8*)locinput,
5623 (U8*)(reginfo->strbeg)),
5624 (U8*) reginfo->strend),
5625 getGCB_VAL_UTF8((U8*) locinput,
5626 (U8*) reginfo->strend));
5630 case SB_BOUND: /* Always matches at begin and end */
5631 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5635 match = isSB(getSB_VAL_UTF8(
5636 reghop3((U8*)locinput,
5638 (U8*)(reginfo->strbeg)),
5639 (U8*) reginfo->strend),
5640 getSB_VAL_UTF8((U8*) locinput,
5641 (U8*) reginfo->strend),
5642 (U8*) reginfo->strbeg,
5644 (U8*) reginfo->strend,
5650 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5654 match = isWB(WB_UNKNOWN,
5656 reghop3((U8*)locinput,
5658 (U8*)(reginfo->strbeg)),
5659 (U8*) reginfo->strend),
5660 getWB_VAL_UTF8((U8*) locinput,
5661 (U8*) reginfo->strend),
5662 (U8*) reginfo->strbeg,
5664 (U8*) reginfo->strend,
5670 else { /* Not utf8 target */
5671 switch((bound_type) FLAGS(scan)) {
5672 case TRADITIONAL_BOUND:
5673 ln = (locinput == reginfo->strbeg)
5674 ? 0 /* isWORDCHAR_L1('\n') */
5675 : isWORDCHAR_L1(UCHARAT(locinput - 1));
5676 n = (NEXTCHR_IS_EOS)
5677 ? 0 /* isWORDCHAR_L1('\n') */
5678 : isWORDCHAR_L1(nextchr);
5679 match = cBOOL(ln != n);
5683 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5684 match = TRUE; /* GCB always matches at begin and
5687 else { /* Only CR-LF combo isn't a GCB in 0-255
5689 match = UCHARAT(locinput - 1) != '\r'
5690 || UCHARAT(locinput) != '\n';
5694 case SB_BOUND: /* Always matches at begin and end */
5695 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5699 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
5700 getSB_VAL_CP(UCHARAT(locinput)),
5701 (U8*) reginfo->strbeg,
5703 (U8*) reginfo->strend,
5709 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5713 match = isWB(WB_UNKNOWN,
5714 getWB_VAL_CP(UCHARAT(locinput -1)),
5715 getWB_VAL_CP(UCHARAT(locinput)),
5716 (U8*) reginfo->strbeg,
5718 (U8*) reginfo->strend,
5725 if (to_complement ^ ! match) {
5730 case ANYOFL: /* /[abc]/l */
5731 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5733 case ANYOF: /* /[abc]/ */
5737 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
5740 locinput += UTF8SKIP(locinput);
5743 if (!REGINCLASS(rex, scan, (U8*)locinput))
5749 /* The argument (FLAGS) to all the POSIX node types is the class number
5752 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
5756 case POSIXL: /* \w or [:punct:] etc. under /l */
5757 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5761 /* Use isFOO_lc() for characters within Latin1. (Note that
5762 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5763 * wouldn't be invariant) */
5764 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5765 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
5769 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5770 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
5771 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
5772 *(locinput + 1))))))
5777 else { /* Here, must be an above Latin-1 code point */
5778 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5779 goto utf8_posix_above_latin1;
5782 /* Here, must be utf8 */
5783 locinput += UTF8SKIP(locinput);
5786 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
5790 case POSIXD: /* \w or [:punct:] etc. under /d */
5796 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
5798 if (NEXTCHR_IS_EOS) {
5802 /* All UTF-8 variants match */
5803 if (! UTF8_IS_INVARIANT(nextchr)) {
5804 goto increment_locinput;
5810 case POSIXA: /* \w or [:punct:] etc. under /a */
5813 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
5814 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
5815 * character is a single byte */
5818 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
5824 /* Here we are either not in utf8, or we matched a utf8-invariant,
5825 * so the next char is the next byte */
5829 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
5833 case POSIXU: /* \w or [:punct:] etc. under /u */
5835 if (NEXTCHR_IS_EOS) {
5839 /* Use _generic_isCC() for characters within Latin1. (Note that
5840 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5841 * wouldn't be invariant) */
5842 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5843 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
5850 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5851 if (! (to_complement
5852 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
5860 else { /* Handle above Latin-1 code points */
5861 utf8_posix_above_latin1:
5862 classnum = (_char_class_number) FLAGS(scan);
5863 if (classnum < _FIRST_NON_SWASH_CC) {
5865 /* Here, uses a swash to find such code points. Load if if
5866 * not done already */
5867 if (! PL_utf8_swash_ptrs[classnum]) {
5868 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
5869 PL_utf8_swash_ptrs[classnum]
5870 = _core_swash_init("utf8",
5873 PL_XPosix_ptrs[classnum], &flags);
5875 if (! (to_complement
5876 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
5877 (U8 *) locinput, TRUE))))
5882 else { /* Here, uses macros to find above Latin-1 code points */
5884 case _CC_ENUM_SPACE:
5885 if (! (to_complement
5886 ^ cBOOL(is_XPERLSPACE_high(locinput))))
5891 case _CC_ENUM_BLANK:
5892 if (! (to_complement
5893 ^ cBOOL(is_HORIZWS_high(locinput))))
5898 case _CC_ENUM_XDIGIT:
5899 if (! (to_complement
5900 ^ cBOOL(is_XDIGIT_high(locinput))))
5905 case _CC_ENUM_VERTSPACE:
5906 if (! (to_complement
5907 ^ cBOOL(is_VERTWS_high(locinput))))
5912 default: /* The rest, e.g. [:cntrl:], can't match
5914 if (! to_complement) {
5920 locinput += UTF8SKIP(locinput);
5924 case CLUMP: /* Match \X: logical Unicode character. This is defined as
5925 a Unicode extended Grapheme Cluster */
5928 if (! utf8_target) {
5930 /* Match either CR LF or '.', as all the other possibilities
5932 locinput++; /* Match the . or CR */
5933 if (nextchr == '\r' /* And if it was CR, and the next is LF,
5935 && locinput < reginfo->strend
5936 && UCHARAT(locinput) == '\n')
5943 /* Get the gcb type for the current character */
5944 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
5945 (U8*) reginfo->strend);
5947 /* Then scan through the input until we get to the first
5948 * character whose type is supposed to be a gcb with the
5949 * current character. (There is always a break at the
5951 locinput += UTF8SKIP(locinput);
5952 while (locinput < reginfo->strend) {
5953 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
5954 (U8*) reginfo->strend);
5955 if (isGCB(prev_gcb, cur_gcb)) {
5960 locinput += UTF8SKIP(locinput);
5967 case NREFFL: /* /\g{name}/il */
5968 { /* The capture buffer cases. The ones beginning with N for the
5969 named buffers just convert to the equivalent numbered and
5970 pretend they were called as the corresponding numbered buffer
5972 /* don't initialize these in the declaration, it makes C++
5977 const U8 *fold_array;
5980 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5981 folder = foldEQ_locale;
5982 fold_array = PL_fold_locale;
5984 utf8_fold_flags = FOLDEQ_LOCALE;
5987 case NREFFA: /* /\g{name}/iaa */
5988 folder = foldEQ_latin1;
5989 fold_array = PL_fold_latin1;
5991 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5994 case NREFFU: /* /\g{name}/iu */
5995 folder = foldEQ_latin1;
5996 fold_array = PL_fold_latin1;
5998 utf8_fold_flags = 0;
6001 case NREFF: /* /\g{name}/i */
6003 fold_array = PL_fold;
6005 utf8_fold_flags = 0;
6008 case NREF: /* /\g{name}/ */
6012 utf8_fold_flags = 0;
6015 /* For the named back references, find the corresponding buffer
6017 n = reg_check_named_buff_matched(rex,scan);
6022 goto do_nref_ref_common;
6024 case REFFL: /* /\1/il */
6025 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6026 folder = foldEQ_locale;
6027 fold_array = PL_fold_locale;
6028 utf8_fold_flags = FOLDEQ_LOCALE;
6031 case REFFA: /* /\1/iaa */
6032 folder = foldEQ_latin1;
6033 fold_array = PL_fold_latin1;
6034 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6037 case REFFU: /* /\1/iu */
6038 folder = foldEQ_latin1;
6039 fold_array = PL_fold_latin1;
6040 utf8_fold_flags = 0;
6043 case REFF: /* /\1/i */
6045 fold_array = PL_fold;
6046 utf8_fold_flags = 0;
6049 case REF: /* /\1/ */
6052 utf8_fold_flags = 0;
6056 n = ARG(scan); /* which paren pair */
6059 ln = rex->offs[n].start;
6060 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6061 if (rex->lastparen < n || ln == -1)
6062 sayNO; /* Do not match unless seen CLOSEn. */
6063 if (ln == rex->offs[n].end)
6066 s = reginfo->strbeg + ln;
6067 if (type != REF /* REF can do byte comparison */
6068 && (utf8_target || type == REFFU || type == REFFL))
6070 char * limit = reginfo->strend;
6072 /* This call case insensitively compares the entire buffer
6073 * at s, with the current input starting at locinput, but
6074 * not going off the end given by reginfo->strend, and
6075 * returns in <limit> upon success, how much of the
6076 * current input was matched */
6077 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6078 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6086 /* Not utf8: Inline the first character, for speed. */
6087 if (!NEXTCHR_IS_EOS &&
6088 UCHARAT(s) != nextchr &&
6090 UCHARAT(s) != fold_array[nextchr]))
6092 ln = rex->offs[n].end - ln;
6093 if (locinput + ln > reginfo->strend)
6095 if (ln > 1 && (type == REF
6096 ? memNE(s, locinput, ln)
6097 : ! folder(s, locinput, ln)))
6103 case NOTHING: /* null op; e.g. the 'nothing' following
6104 * the '*' in m{(a+|b)*}' */
6106 case TAIL: /* placeholder while compiling (A|B|C) */
6110 #define ST st->u.eval
6115 regexp_internal *rei;
6116 regnode *startpoint;
6118 case GOSTART: /* (?R) */
6119 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6120 if (cur_eval && cur_eval->locinput==locinput) {
6121 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
6122 Perl_croak(aTHX_ "Infinite recursion in regex");
6123 if ( ++nochange_depth > max_nochange_depth )
6125 "Pattern subroutine nesting without pos change"
6126 " exceeded limit in regex");
6133 if (OP(scan)==GOSUB) {
6134 startpoint = scan + ARG2L(scan);
6135 ST.close_paren = ARG(scan);
6137 startpoint = rei->program+1;
6141 /* Save all the positions seen so far. */
6142 ST.cp = regcppush(rex, 0, maxopenparen);
6143 REGCP_SET(ST.lastcp);
6145 /* and then jump to the code we share with EVAL */
6146 goto eval_recurse_doit;
6149 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6150 if (cur_eval && cur_eval->locinput==locinput) {
6151 if ( ++nochange_depth > max_nochange_depth )
6152 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6157 /* execute the code in the {...} */
6161 OP * const oop = PL_op;
6162 COP * const ocurcop = PL_curcop;
6166 /* save *all* paren positions */
6167 regcppush(rex, 0, maxopenparen);
6168 REGCP_SET(runops_cp);
6171 caller_cv = find_runcv(NULL);
6175 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6177 (REGEXP*)(rexi->data->data[n])
6180 nop = (OP*)rexi->data->data[n+1];
6182 else if (rexi->data->what[n] == 'l') { /* literal code */
6184 nop = (OP*)rexi->data->data[n];
6185 assert(CvDEPTH(newcv));
6188 /* literal with own CV */
6189 assert(rexi->data->what[n] == 'L');
6190 newcv = rex->qr_anoncv;
6191 nop = (OP*)rexi->data->data[n];
6194 /* normally if we're about to execute code from the same
6195 * CV that we used previously, we just use the existing
6196 * CX stack entry. However, its possible that in the
6197 * meantime we may have backtracked, popped from the save
6198 * stack, and undone the SAVECOMPPAD(s) associated with
6199 * PUSH_MULTICALL; in which case PL_comppad no longer
6200 * points to newcv's pad. */
6201 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6203 U8 flags = (CXp_SUB_RE |
6204 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6205 if (last_pushed_cv) {
6206 CHANGE_MULTICALL_FLAGS(newcv, flags);
6209 PUSH_MULTICALL_FLAGS(newcv, flags);
6211 last_pushed_cv = newcv;
6214 /* these assignments are just to silence compiler
6216 multicall_cop = NULL;
6219 last_pad = PL_comppad;
6221 /* the initial nextstate you would normally execute
6222 * at the start of an eval (which would cause error
6223 * messages to come from the eval), may be optimised
6224 * away from the execution path in the regex code blocks;
6225 * so manually set PL_curcop to it initially */
6227 OP *o = cUNOPx(nop)->op_first;
6228 assert(o->op_type == OP_NULL);
6229 if (o->op_targ == OP_SCOPE) {
6230 o = cUNOPo->op_first;
6233 assert(o->op_targ == OP_LEAVE);
6234 o = cUNOPo->op_first;
6235 assert(o->op_type == OP_ENTER);
6239 if (o->op_type != OP_STUB) {
6240 assert( o->op_type == OP_NEXTSTATE
6241 || o->op_type == OP_DBSTATE
6242 || (o->op_type == OP_NULL
6243 && ( o->op_targ == OP_NEXTSTATE
6244 || o->op_targ == OP_DBSTATE
6248 PL_curcop = (COP*)o;
6253 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
6254 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6256 rex->offs[0].end = locinput - reginfo->strbeg;
6257 if (reginfo->info_aux_eval->pos_magic)
6258 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6259 reginfo->sv, reginfo->strbeg,
6260 locinput - reginfo->strbeg);
6263 SV *sv_mrk = get_sv("REGMARK", 1);
6264 sv_setsv(sv_mrk, sv_yes_mark);
6267 /* we don't use MULTICALL here as we want to call the
6268 * first op of the block of interest, rather than the
6269 * first op of the sub */
6270 before = (IV)(SP-PL_stack_base);
6272 CALLRUNOPS(aTHX); /* Scalar context. */
6274 if ((IV)(SP-PL_stack_base) == before)
6275 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6281 /* before restoring everything, evaluate the returned
6282 * value, so that 'uninit' warnings don't use the wrong
6283 * PL_op or pad. Also need to process any magic vars
6284 * (e.g. $1) *before* parentheses are restored */
6289 if (logical == 0) /* (?{})/ */
6290 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6291 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6292 sw = cBOOL(SvTRUE(ret));
6295 else { /* /(??{}) */
6296 /* if its overloaded, let the regex compiler handle
6297 * it; otherwise extract regex, or stringify */
6298 if (SvGMAGICAL(ret))
6299 ret = sv_mortalcopy(ret);
6300 if (!SvAMAGIC(ret)) {
6304 if (SvTYPE(sv) == SVt_REGEXP)
6305 re_sv = (REGEXP*) sv;
6306 else if (SvSMAGICAL(ret)) {
6307 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6309 re_sv = (REGEXP *) mg->mg_obj;
6312 /* force any undef warnings here */
6313 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6314 ret = sv_mortalcopy(ret);
6315 (void) SvPV_force_nolen(ret);
6321 /* *** Note that at this point we don't restore
6322 * PL_comppad, (or pop the CxSUB) on the assumption it may
6323 * be used again soon. This is safe as long as nothing
6324 * in the regexp code uses the pad ! */
6326 PL_curcop = ocurcop;
6327 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6328 PL_curpm = PL_reg_curpm;
6334 /* only /(??{})/ from now on */
6337 /* extract RE object from returned value; compiling if
6341 re_sv = reg_temp_copy(NULL, re_sv);
6346 if (SvUTF8(ret) && IN_BYTES) {
6347 /* In use 'bytes': make a copy of the octet
6348 * sequence, but without the flag on */
6350 const char *const p = SvPV(ret, len);
6351 ret = newSVpvn_flags(p, len, SVs_TEMP);
6353 if (rex->intflags & PREGf_USE_RE_EVAL)
6354 pm_flags |= PMf_USE_RE_EVAL;
6356 /* if we got here, it should be an engine which
6357 * supports compiling code blocks and stuff */
6358 assert(rex->engine && rex->engine->op_comp);
6359 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6360 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6361 rex->engine, NULL, NULL,
6362 /* copy /msixn etc to inner pattern */
6367 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6368 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6369 /* This isn't a first class regexp. Instead, it's
6370 caching a regexp onto an existing, Perl visible
6372 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6378 RXp_MATCH_COPIED_off(re);
6379 re->subbeg = rex->subbeg;
6380 re->sublen = rex->sublen;
6381 re->suboffset = rex->suboffset;
6382 re->subcoffset = rex->subcoffset;
6384 re->lastcloseparen = 0;
6387 debug_start_match(re_sv, utf8_target, locinput,
6388 reginfo->strend, "Matching embedded");
6390 startpoint = rei->program + 1;
6391 ST.close_paren = 0; /* only used for GOSUB */
6392 /* Save all the seen positions so far. */
6393 ST.cp = regcppush(rex, 0, maxopenparen);
6394 REGCP_SET(ST.lastcp);
6395 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6397 /* run the pattern returned from (??{...}) */
6399 eval_recurse_doit: /* Share code with GOSUB below this line
6400 * At this point we expect the stack context to be
6401 * set up correctly */
6403 /* invalidate the S-L poscache. We're now executing a
6404 * different set of WHILEM ops (and their associated
6405 * indexes) against the same string, so the bits in the
6406 * cache are meaningless. Setting maxiter to zero forces
6407 * the cache to be invalidated and zeroed before reuse.
6408 * XXX This is too dramatic a measure. Ideally we should
6409 * save the old cache and restore when running the outer
6411 reginfo->poscache_maxiter = 0;
6413 /* the new regexp might have a different is_utf8_pat than we do */
6414 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6416 ST.prev_rex = rex_sv;
6417 ST.prev_curlyx = cur_curlyx;
6419 SET_reg_curpm(rex_sv);
6424 ST.prev_eval = cur_eval;
6426 /* now continue from first node in postoned RE */
6427 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
6429 NOT_REACHED; /* NOTREACHED */
6432 case EVAL_AB: /* cleanup after a successful (??{A})B */
6433 /* note: this is called twice; first after popping B, then A */
6434 rex_sv = ST.prev_rex;
6435 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6436 SET_reg_curpm(rex_sv);
6437 rex = ReANY(rex_sv);
6438 rexi = RXi_GET(rex);
6440 /* preserve $^R across LEAVE's. See Bug 121070. */
6441 SV *save_sv= GvSV(PL_replgv);
6442 SvREFCNT_inc(save_sv);
6443 regcpblow(ST.cp); /* LEAVE in disguise */
6444 sv_setsv(GvSV(PL_replgv), save_sv);
6445 SvREFCNT_dec(save_sv);
6447 cur_eval = ST.prev_eval;
6448 cur_curlyx = ST.prev_curlyx;
6450 /* Invalidate cache. See "invalidate" comment above. */
6451 reginfo->poscache_maxiter = 0;
6452 if ( nochange_depth )
6457 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
6458 /* note: this is called twice; first after popping B, then A */
6459 rex_sv = ST.prev_rex;
6460 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6461 SET_reg_curpm(rex_sv);
6462 rex = ReANY(rex_sv);
6463 rexi = RXi_GET(rex);
6465 REGCP_UNWIND(ST.lastcp);
6466 regcppop(rex, &maxopenparen);
6467 cur_eval = ST.prev_eval;
6468 cur_curlyx = ST.prev_curlyx;
6469 /* Invalidate cache. See "invalidate" comment above. */
6470 reginfo->poscache_maxiter = 0;
6471 if ( nochange_depth )
6477 n = ARG(scan); /* which paren pair */
6478 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
6479 if (n > maxopenparen)
6481 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
6482 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
6486 (IV)rex->offs[n].start_tmp,
6492 /* XXX really need to log other places start/end are set too */
6493 #define CLOSE_CAPTURE \
6494 rex->offs[n].start = rex->offs[n].start_tmp; \
6495 rex->offs[n].end = locinput - reginfo->strbeg; \
6496 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
6497 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
6499 PTR2UV(rex->offs), \
6501 (IV)rex->offs[n].start, \
6502 (IV)rex->offs[n].end \
6506 n = ARG(scan); /* which paren pair */
6508 if (n > rex->lastparen)
6510 rex->lastcloseparen = n;
6511 if (cur_eval && cur_eval->u.eval.close_paren == n) {
6516 case ACCEPT: /* (*ACCEPT) */
6520 cursor && OP(cursor)!=END;
6521 cursor=regnext(cursor))
6523 if ( OP(cursor)==CLOSE ){
6525 if ( n <= lastopen ) {
6527 if (n > rex->lastparen)
6529 rex->lastcloseparen = n;
6530 if ( n == ARG(scan) || (cur_eval &&
6531 cur_eval->u.eval.close_paren == n))
6540 case GROUPP: /* (?(1)) */
6541 n = ARG(scan); /* which paren pair */
6542 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
6545 case NGROUPP: /* (?(<name>)) */
6546 /* reg_check_named_buff_matched returns 0 for no match */
6547 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
6550 case INSUBP: /* (?(R)) */
6552 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
6555 case DEFINEP: /* (?(DEFINE)) */
6559 case IFTHEN: /* (?(cond)A|B) */
6560 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6562 next = NEXTOPER(NEXTOPER(scan));
6564 next = scan + ARG(scan);
6565 if (OP(next) == IFTHEN) /* Fake one. */
6566 next = NEXTOPER(NEXTOPER(next));
6570 case LOGICAL: /* modifier for EVAL and IFMATCH */
6571 logical = scan->flags;
6574 /*******************************************************************
6576 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
6577 pattern, where A and B are subpatterns. (For simple A, CURLYM or
6578 STAR/PLUS/CURLY/CURLYN are used instead.)
6580 A*B is compiled as <CURLYX><A><WHILEM><B>
6582 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
6583 state, which contains the current count, initialised to -1. It also sets
6584 cur_curlyx to point to this state, with any previous value saved in the
6587 CURLYX then jumps straight to the WHILEM op, rather than executing A,
6588 since the pattern may possibly match zero times (i.e. it's a while {} loop
6589 rather than a do {} while loop).
6591 Each entry to WHILEM represents a successful match of A. The count in the
6592 CURLYX block is incremented, another WHILEM state is pushed, and execution
6593 passes to A or B depending on greediness and the current count.
6595 For example, if matching against the string a1a2a3b (where the aN are
6596 substrings that match /A/), then the match progresses as follows: (the
6597 pushed states are interspersed with the bits of strings matched so far):
6600 <CURLYX cnt=0><WHILEM>
6601 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
6602 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
6603 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
6604 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
6606 (Contrast this with something like CURLYM, which maintains only a single
6610 a1 <CURLYM cnt=1> a2
6611 a1 a2 <CURLYM cnt=2> a3
6612 a1 a2 a3 <CURLYM cnt=3> b
6615 Each WHILEM state block marks a point to backtrack to upon partial failure
6616 of A or B, and also contains some minor state data related to that
6617 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
6618 overall state, such as the count, and pointers to the A and B ops.
6620 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
6621 must always point to the *current* CURLYX block, the rules are:
6623 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
6624 and set cur_curlyx to point the new block.
6626 When popping the CURLYX block after a successful or unsuccessful match,
6627 restore the previous cur_curlyx.
6629 When WHILEM is about to execute B, save the current cur_curlyx, and set it
6630 to the outer one saved in the CURLYX block.
6632 When popping the WHILEM block after a successful or unsuccessful B match,
6633 restore the previous cur_curlyx.
6635 Here's an example for the pattern (AI* BI)*BO
6636 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
6639 curlyx backtrack stack
6640 ------ ---------------
6642 CO <CO prev=NULL> <WO>
6643 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6644 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6645 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
6647 At this point the pattern succeeds, and we work back down the stack to
6648 clean up, restoring as we go:
6650 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6651 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6652 CO <CO prev=NULL> <WO>
6655 *******************************************************************/
6657 #define ST st->u.curlyx
6659 case CURLYX: /* start of /A*B/ (for complex A) */
6661 /* No need to save/restore up to this paren */
6662 I32 parenfloor = scan->flags;
6664 assert(next); /* keep Coverity happy */
6665 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
6668 /* XXXX Probably it is better to teach regpush to support
6669 parenfloor > maxopenparen ... */
6670 if (parenfloor > (I32)rex->lastparen)
6671 parenfloor = rex->lastparen; /* Pessimization... */
6673 ST.prev_curlyx= cur_curlyx;
6675 ST.cp = PL_savestack_ix;
6677 /* these fields contain the state of the current curly.
6678 * they are accessed by subsequent WHILEMs */
6679 ST.parenfloor = parenfloor;
6684 ST.count = -1; /* this will be updated by WHILEM */
6685 ST.lastloc = NULL; /* this will be updated by WHILEM */
6687 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
6689 NOT_REACHED; /* NOTREACHED */
6692 case CURLYX_end: /* just finished matching all of A*B */
6693 cur_curlyx = ST.prev_curlyx;
6696 NOT_REACHED; /* NOTREACHED */
6698 case CURLYX_end_fail: /* just failed to match all of A*B */
6700 cur_curlyx = ST.prev_curlyx;
6703 NOT_REACHED; /* NOTREACHED */
6707 #define ST st->u.whilem
6709 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
6711 /* see the discussion above about CURLYX/WHILEM */
6716 assert(cur_curlyx); /* keep Coverity happy */
6718 min = ARG1(cur_curlyx->u.curlyx.me);
6719 max = ARG2(cur_curlyx->u.curlyx.me);
6720 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
6721 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
6722 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
6723 ST.cache_offset = 0;
6727 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6728 "%*s whilem: matched %ld out of %d..%d\n",
6729 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
6732 /* First just match a string of min A's. */
6735 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6737 cur_curlyx->u.curlyx.lastloc = locinput;
6738 REGCP_SET(ST.lastcp);
6740 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
6742 NOT_REACHED; /* NOTREACHED */
6745 /* If degenerate A matches "", assume A done. */
6747 if (locinput == cur_curlyx->u.curlyx.lastloc) {
6748 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6749 "%*s whilem: empty match detected, trying continuation...\n",
6750 REPORT_CODE_OFF+depth*2, "")
6752 goto do_whilem_B_max;
6755 /* super-linear cache processing.
6757 * The idea here is that for certain types of CURLYX/WHILEM -
6758 * principally those whose upper bound is infinity (and
6759 * excluding regexes that have things like \1 and other very
6760 * non-regular expresssiony things), then if a pattern like
6761 * /....A*.../ fails and we backtrack to the WHILEM, then we
6762 * make a note that this particular WHILEM op was at string
6763 * position 47 (say) when the rest of pattern failed. Then, if
6764 * we ever find ourselves back at that WHILEM, and at string
6765 * position 47 again, we can just fail immediately rather than
6766 * running the rest of the pattern again.
6768 * This is very handy when patterns start to go
6769 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
6770 * with a combinatorial explosion of backtracking.
6772 * The cache is implemented as a bit array, with one bit per
6773 * string byte position per WHILEM op (up to 16) - so its
6774 * between 0.25 and 2x the string size.
6776 * To avoid allocating a poscache buffer every time, we do an
6777 * initially countdown; only after we have executed a WHILEM
6778 * op (string-length x #WHILEMs) times do we allocate the
6781 * The top 4 bits of scan->flags byte say how many different
6782 * relevant CURLLYX/WHILEM op pairs there are, while the
6783 * bottom 4-bits is the identifying index number of this
6789 if (!reginfo->poscache_maxiter) {
6790 /* start the countdown: Postpone detection until we
6791 * know the match is not *that* much linear. */
6792 reginfo->poscache_maxiter
6793 = (reginfo->strend - reginfo->strbeg + 1)
6795 /* possible overflow for long strings and many CURLYX's */
6796 if (reginfo->poscache_maxiter < 0)
6797 reginfo->poscache_maxiter = I32_MAX;
6798 reginfo->poscache_iter = reginfo->poscache_maxiter;
6801 if (reginfo->poscache_iter-- == 0) {
6802 /* initialise cache */
6803 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
6804 regmatch_info_aux *const aux = reginfo->info_aux;
6805 if (aux->poscache) {
6806 if ((SSize_t)reginfo->poscache_size < size) {
6807 Renew(aux->poscache, size, char);
6808 reginfo->poscache_size = size;
6810 Zero(aux->poscache, size, char);
6813 reginfo->poscache_size = size;
6814 Newxz(aux->poscache, size, char);
6816 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6817 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
6818 PL_colors[4], PL_colors[5])
6822 if (reginfo->poscache_iter < 0) {
6823 /* have we already failed at this position? */
6824 SSize_t offset, mask;
6826 reginfo->poscache_iter = -1; /* stop eventual underflow */
6827 offset = (scan->flags & 0xf) - 1
6828 + (locinput - reginfo->strbeg)
6830 mask = 1 << (offset % 8);
6832 if (reginfo->info_aux->poscache[offset] & mask) {
6833 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6834 "%*s whilem: (cache) already tried at this position...\n",
6835 REPORT_CODE_OFF+depth*2, "")
6837 sayNO; /* cache records failure */
6839 ST.cache_offset = offset;
6840 ST.cache_mask = mask;
6844 /* Prefer B over A for minimal matching. */
6846 if (cur_curlyx->u.curlyx.minmod) {
6847 ST.save_curlyx = cur_curlyx;
6848 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6849 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
6851 REGCP_SET(ST.lastcp);
6852 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
6855 NOT_REACHED; /* NOTREACHED */
6858 /* Prefer A over B for maximal matching. */
6860 if (n < max) { /* More greed allowed? */
6861 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6863 cur_curlyx->u.curlyx.lastloc = locinput;
6864 REGCP_SET(ST.lastcp);
6865 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
6867 NOT_REACHED; /* NOTREACHED */
6869 goto do_whilem_B_max;
6872 NOT_REACHED; /* NOTREACHED */
6874 case WHILEM_B_min: /* just matched B in a minimal match */
6875 case WHILEM_B_max: /* just matched B in a maximal match */
6876 cur_curlyx = ST.save_curlyx;
6879 NOT_REACHED; /* NOTREACHED */
6881 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
6882 cur_curlyx = ST.save_curlyx;
6883 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6884 cur_curlyx->u.curlyx.count--;
6887 NOT_REACHED; /* NOTREACHED */
6889 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
6891 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
6892 REGCP_UNWIND(ST.lastcp);
6893 regcppop(rex, &maxopenparen);
6894 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6895 cur_curlyx->u.curlyx.count--;
6898 NOT_REACHED; /* NOTREACHED */
6900 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
6901 REGCP_UNWIND(ST.lastcp);
6902 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
6903 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6904 "%*s whilem: failed, trying continuation...\n",
6905 REPORT_CODE_OFF+depth*2, "")
6908 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6909 && ckWARN(WARN_REGEXP)
6910 && !reginfo->warned)
6912 reginfo->warned = TRUE;
6913 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6914 "Complex regular subexpression recursion limit (%d) "
6920 ST.save_curlyx = cur_curlyx;
6921 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6922 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
6925 NOT_REACHED; /* NOTREACHED */
6927 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
6928 cur_curlyx = ST.save_curlyx;
6929 REGCP_UNWIND(ST.lastcp);
6930 regcppop(rex, &maxopenparen);
6932 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
6933 /* Maximum greed exceeded */
6934 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6935 && ckWARN(WARN_REGEXP)
6936 && !reginfo->warned)
6938 reginfo->warned = TRUE;
6939 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6940 "Complex regular subexpression recursion "
6941 "limit (%d) exceeded",
6944 cur_curlyx->u.curlyx.count--;
6948 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6949 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
6951 /* Try grabbing another A and see if it helps. */
6952 cur_curlyx->u.curlyx.lastloc = locinput;
6953 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6955 REGCP_SET(ST.lastcp);
6956 PUSH_STATE_GOTO(WHILEM_A_min,
6957 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6960 NOT_REACHED; /* NOTREACHED */
6963 #define ST st->u.branch
6965 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6966 next = scan + ARG(scan);
6969 scan = NEXTOPER(scan);
6972 case BRANCH: /* /(...|A|...)/ */
6973 scan = NEXTOPER(scan); /* scan now points to inner node */
6974 ST.lastparen = rex->lastparen;
6975 ST.lastcloseparen = rex->lastcloseparen;
6976 ST.next_branch = next;
6979 /* Now go into the branch */
6981 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
6983 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
6986 NOT_REACHED; /* NOTREACHED */
6988 case CUTGROUP: /* /(*THEN)/ */
6989 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
6990 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6991 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
6993 NOT_REACHED; /* NOTREACHED */
6995 case CUTGROUP_next_fail:
6998 if (st->u.mark.mark_name)
6999 sv_commit = st->u.mark.mark_name;
7002 NOT_REACHED; /* NOTREACHED */
7007 NOT_REACHED; /* NOTREACHED */
7009 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7014 REGCP_UNWIND(ST.cp);
7015 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7016 scan = ST.next_branch;
7017 /* no more branches? */
7018 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7020 PerlIO_printf( Perl_debug_log,
7021 "%*s %sBRANCH failed...%s\n",
7022 REPORT_CODE_OFF+depth*2, "",
7028 continue; /* execute next BRANCH[J] op */
7031 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7036 #define ST st->u.curlym
7038 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7040 /* This is an optimisation of CURLYX that enables us to push
7041 * only a single backtracking state, no matter how many matches
7042 * there are in {m,n}. It relies on the pattern being constant
7043 * length, with no parens to influence future backrefs
7047 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7049 ST.lastparen = rex->lastparen;
7050 ST.lastcloseparen = rex->lastcloseparen;
7052 /* if paren positive, emulate an OPEN/CLOSE around A */
7054 U32 paren = ST.me->flags;
7055 if (paren > maxopenparen)
7056 maxopenparen = paren;
7057 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7065 ST.c1 = CHRTEST_UNINIT;
7068 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7071 curlym_do_A: /* execute the A in /A{m,n}B/ */
7072 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7074 NOT_REACHED; /* NOTREACHED */
7076 case CURLYM_A: /* we've just matched an A */
7078 /* after first match, determine A's length: u.curlym.alen */
7079 if (ST.count == 1) {
7080 if (reginfo->is_utf8_target) {
7081 char *s = st->locinput;
7082 while (s < locinput) {
7088 ST.alen = locinput - st->locinput;
7091 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7094 PerlIO_printf(Perl_debug_log,
7095 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7096 (int)(REPORT_CODE_OFF+(depth*2)), "",
7097 (IV) ST.count, (IV)ST.alen)
7100 if (cur_eval && cur_eval->u.eval.close_paren &&
7101 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7105 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7106 if ( max == REG_INFTY || ST.count < max )
7107 goto curlym_do_A; /* try to match another A */
7109 goto curlym_do_B; /* try to match B */
7111 case CURLYM_A_fail: /* just failed to match an A */
7112 REGCP_UNWIND(ST.cp);
7114 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7115 || (cur_eval && cur_eval->u.eval.close_paren &&
7116 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7119 curlym_do_B: /* execute the B in /A{m,n}B/ */
7120 if (ST.c1 == CHRTEST_UNINIT) {
7121 /* calculate c1 and c2 for possible match of 1st char
7122 * following curly */
7123 ST.c1 = ST.c2 = CHRTEST_VOID;
7125 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7126 regnode *text_node = ST.B;
7127 if (! HAS_TEXT(text_node))
7128 FIND_NEXT_IMPT(text_node);
7131 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7133 But the former is redundant in light of the latter.
7135 if this changes back then the macro for
7136 IS_TEXT and friends need to change.
7138 if (PL_regkind[OP(text_node)] == EXACT) {
7139 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7140 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7150 PerlIO_printf(Perl_debug_log,
7151 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
7152 (int)(REPORT_CODE_OFF+(depth*2)),
7155 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7156 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7157 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7158 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7160 /* simulate B failing */
7162 PerlIO_printf(Perl_debug_log,
7163 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7164 (int)(REPORT_CODE_OFF+(depth*2)),"",
7165 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7166 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7167 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7169 state_num = CURLYM_B_fail;
7170 goto reenter_switch;
7173 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7174 /* simulate B failing */
7176 PerlIO_printf(Perl_debug_log,
7177 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7178 (int)(REPORT_CODE_OFF+(depth*2)),"",
7179 (int) nextchr, ST.c1, ST.c2)
7181 state_num = CURLYM_B_fail;
7182 goto reenter_switch;
7187 /* emulate CLOSE: mark current A as captured */
7188 I32 paren = ST.me->flags;
7190 rex->offs[paren].start
7191 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7192 rex->offs[paren].end = locinput - reginfo->strbeg;
7193 if ((U32)paren > rex->lastparen)
7194 rex->lastparen = paren;
7195 rex->lastcloseparen = paren;
7198 rex->offs[paren].end = -1;
7199 if (cur_eval && cur_eval->u.eval.close_paren &&
7200 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7209 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7211 NOT_REACHED; /* NOTREACHED */
7213 case CURLYM_B_fail: /* just failed to match a B */
7214 REGCP_UNWIND(ST.cp);
7215 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7217 I32 max = ARG2(ST.me);
7218 if (max != REG_INFTY && ST.count == max)
7220 goto curlym_do_A; /* try to match a further A */
7222 /* backtrack one A */
7223 if (ST.count == ARG1(ST.me) /* min */)
7226 SET_locinput(HOPc(locinput, -ST.alen));
7227 goto curlym_do_B; /* try to match B */
7230 #define ST st->u.curly
7232 #define CURLY_SETPAREN(paren, success) \
7235 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7236 rex->offs[paren].end = locinput - reginfo->strbeg; \
7237 if (paren > rex->lastparen) \
7238 rex->lastparen = paren; \
7239 rex->lastcloseparen = paren; \
7242 rex->offs[paren].end = -1; \
7243 rex->lastparen = ST.lastparen; \
7244 rex->lastcloseparen = ST.lastcloseparen; \
7248 case STAR: /* /A*B/ where A is width 1 char */
7252 scan = NEXTOPER(scan);
7255 case PLUS: /* /A+B/ where A is width 1 char */
7259 scan = NEXTOPER(scan);
7262 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7263 ST.paren = scan->flags; /* Which paren to set */
7264 ST.lastparen = rex->lastparen;
7265 ST.lastcloseparen = rex->lastcloseparen;
7266 if (ST.paren > maxopenparen)
7267 maxopenparen = ST.paren;
7268 ST.min = ARG1(scan); /* min to match */
7269 ST.max = ARG2(scan); /* max to match */
7270 if (cur_eval && cur_eval->u.eval.close_paren &&
7271 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7275 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7278 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7280 ST.min = ARG1(scan); /* min to match */
7281 ST.max = ARG2(scan); /* max to match */
7282 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7285 * Lookahead to avoid useless match attempts
7286 * when we know what character comes next.
7288 * Used to only do .*x and .*?x, but now it allows
7289 * for )'s, ('s and (?{ ... })'s to be in the way
7290 * of the quantifier and the EXACT-like node. -- japhy
7293 assert(ST.min <= ST.max);
7294 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7295 ST.c1 = ST.c2 = CHRTEST_VOID;
7298 regnode *text_node = next;
7300 if (! HAS_TEXT(text_node))
7301 FIND_NEXT_IMPT(text_node);
7303 if (! HAS_TEXT(text_node))
7304 ST.c1 = ST.c2 = CHRTEST_VOID;
7306 if ( PL_regkind[OP(text_node)] != EXACT ) {
7307 ST.c1 = ST.c2 = CHRTEST_VOID;
7311 /* Currently we only get here when
7313 PL_rekind[OP(text_node)] == EXACT
7315 if this changes back then the macro for IS_TEXT and
7316 friends need to change. */
7317 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7318 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7330 char *li = locinput;
7333 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7339 if (ST.c1 == CHRTEST_VOID)
7340 goto curly_try_B_min;
7342 ST.oldloc = locinput;
7344 /* set ST.maxpos to the furthest point along the
7345 * string that could possibly match */
7346 if (ST.max == REG_INFTY) {
7347 ST.maxpos = reginfo->strend - 1;
7349 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7352 else if (utf8_target) {
7353 int m = ST.max - ST.min;
7354 for (ST.maxpos = locinput;
7355 m >0 && ST.maxpos < reginfo->strend; m--)
7356 ST.maxpos += UTF8SKIP(ST.maxpos);
7359 ST.maxpos = locinput + ST.max - ST.min;
7360 if (ST.maxpos >= reginfo->strend)
7361 ST.maxpos = reginfo->strend - 1;
7363 goto curly_try_B_min_known;
7367 /* avoid taking address of locinput, so it can remain
7369 char *li = locinput;
7370 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7371 if (ST.count < ST.min)
7374 if ((ST.count > ST.min)
7375 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7377 /* A{m,n} must come at the end of the string, there's
7378 * no point in backing off ... */
7380 /* ...except that $ and \Z can match before *and* after
7381 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7382 We may back off by one in this case. */
7383 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7387 goto curly_try_B_max;
7390 NOT_REACHED; /* NOTREACHED */
7392 case CURLY_B_min_known_fail:
7393 /* failed to find B in a non-greedy match where c1,c2 valid */
7395 REGCP_UNWIND(ST.cp);
7397 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7399 /* Couldn't or didn't -- move forward. */
7400 ST.oldloc = locinput;
7402 locinput += UTF8SKIP(locinput);
7406 curly_try_B_min_known:
7407 /* find the next place where 'B' could work, then call B */
7411 n = (ST.oldloc == locinput) ? 0 : 1;
7412 if (ST.c1 == ST.c2) {
7413 /* set n to utf8_distance(oldloc, locinput) */
7414 while (locinput <= ST.maxpos
7415 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7417 locinput += UTF8SKIP(locinput);
7422 /* set n to utf8_distance(oldloc, locinput) */
7423 while (locinput <= ST.maxpos
7424 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7425 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7427 locinput += UTF8SKIP(locinput);
7432 else { /* Not utf8_target */
7433 if (ST.c1 == ST.c2) {
7434 while (locinput <= ST.maxpos &&
7435 UCHARAT(locinput) != ST.c1)
7439 while (locinput <= ST.maxpos
7440 && UCHARAT(locinput) != ST.c1
7441 && UCHARAT(locinput) != ST.c2)
7444 n = locinput - ST.oldloc;
7446 if (locinput > ST.maxpos)
7449 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7450 * at b; check that everything between oldloc and
7451 * locinput matches */
7452 char *li = ST.oldloc;
7454 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7456 assert(n == REG_INFTY || locinput == li);
7458 CURLY_SETPAREN(ST.paren, ST.count);
7459 if (cur_eval && cur_eval->u.eval.close_paren &&
7460 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7463 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7466 NOT_REACHED; /* NOTREACHED */
7468 case CURLY_B_min_fail:
7469 /* failed to find B in a non-greedy match where c1,c2 invalid */
7471 REGCP_UNWIND(ST.cp);
7473 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7475 /* failed -- move forward one */
7477 char *li = locinput;
7478 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7485 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7486 ST.count > 0)) /* count overflow ? */
7489 CURLY_SETPAREN(ST.paren, ST.count);
7490 if (cur_eval && cur_eval->u.eval.close_paren &&
7491 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7494 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7499 NOT_REACHED; /* NOTREACHED */
7502 /* a successful greedy match: now try to match B */
7503 if (cur_eval && cur_eval->u.eval.close_paren &&
7504 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7508 bool could_match = locinput < reginfo->strend;
7510 /* If it could work, try it. */
7511 if (ST.c1 != CHRTEST_VOID && could_match) {
7512 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7514 could_match = memEQ(locinput,
7519 UTF8SKIP(locinput));
7522 could_match = UCHARAT(locinput) == ST.c1
7523 || UCHARAT(locinput) == ST.c2;
7526 if (ST.c1 == CHRTEST_VOID || could_match) {
7527 CURLY_SETPAREN(ST.paren, ST.count);
7528 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7530 NOT_REACHED; /* NOTREACHED */
7535 case CURLY_B_max_fail:
7536 /* failed to find B in a greedy match */
7538 REGCP_UNWIND(ST.cp);
7540 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7543 if (--ST.count < ST.min)
7545 locinput = HOPc(locinput, -1);
7546 goto curly_try_B_max;
7550 case END: /* last op of main pattern */
7553 /* we've just finished A in /(??{A})B/; now continue with B */
7555 st->u.eval.prev_rex = rex_sv; /* inner */
7557 /* Save *all* the positions. */
7558 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7559 rex_sv = cur_eval->u.eval.prev_rex;
7560 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7561 SET_reg_curpm(rex_sv);
7562 rex = ReANY(rex_sv);
7563 rexi = RXi_GET(rex);
7564 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7566 REGCP_SET(st->u.eval.lastcp);
7568 /* Restore parens of the outer rex without popping the
7570 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7573 st->u.eval.prev_eval = cur_eval;
7574 cur_eval = cur_eval->u.eval.prev_eval;
7576 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
7577 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7578 if ( nochange_depth )
7581 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7582 locinput); /* match B */
7585 if (locinput < reginfo->till) {
7586 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7587 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7589 (long)(locinput - startpos),
7590 (long)(reginfo->till - startpos),
7593 sayNO_SILENT; /* Cannot match: too short. */
7595 sayYES; /* Success! */
7597 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7599 PerlIO_printf(Perl_debug_log,
7600 "%*s %ssubpattern success...%s\n",
7601 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7602 sayYES; /* Success! */
7605 #define ST st->u.ifmatch
7610 case SUSPEND: /* (?>A) */
7612 newstart = locinput;
7615 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
7617 goto ifmatch_trivial_fail_test;
7619 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
7621 ifmatch_trivial_fail_test:
7623 char * const s = HOPBACKc(locinput, scan->flags);
7628 sw = 1 - cBOOL(ST.wanted);
7632 next = scan + ARG(scan);
7640 newstart = locinput;
7644 ST.logical = logical;
7645 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
7647 /* execute body of (?...A) */
7648 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
7650 NOT_REACHED; /* NOTREACHED */
7653 case IFMATCH_A_fail: /* body of (?...A) failed */
7654 ST.wanted = !ST.wanted;
7657 case IFMATCH_A: /* body of (?...A) succeeded */
7659 sw = cBOOL(ST.wanted);
7661 else if (!ST.wanted)
7664 if (OP(ST.me) != SUSPEND) {
7665 /* restore old position except for (?>...) */
7666 locinput = st->locinput;
7668 scan = ST.me + ARG(ST.me);
7671 continue; /* execute B */
7675 case LONGJMP: /* alternative with many branches compiles to
7676 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
7677 next = scan + ARG(scan);
7682 case COMMIT: /* (*COMMIT) */
7683 reginfo->cutpoint = reginfo->strend;
7686 case PRUNE: /* (*PRUNE) */
7688 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7689 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
7691 NOT_REACHED; /* NOTREACHED */
7693 case COMMIT_next_fail:
7697 case OPFAIL: /* (*FAIL) */
7700 NOT_REACHED; /* NOTREACHED */
7702 #define ST st->u.mark
7703 case MARKPOINT: /* (*MARK:foo) */
7704 ST.prev_mark = mark_state;
7705 ST.mark_name = sv_commit = sv_yes_mark
7706 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7708 ST.mark_loc = locinput;
7709 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
7711 NOT_REACHED; /* NOTREACHED */
7713 case MARKPOINT_next:
7714 mark_state = ST.prev_mark;
7717 NOT_REACHED; /* NOTREACHED */
7719 case MARKPOINT_next_fail:
7720 if (popmark && sv_eq(ST.mark_name,popmark))
7722 if (ST.mark_loc > startpoint)
7723 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7724 popmark = NULL; /* we found our mark */
7725 sv_commit = ST.mark_name;
7728 PerlIO_printf(Perl_debug_log,
7729 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
7730 REPORT_CODE_OFF+depth*2, "",
7731 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
7734 mark_state = ST.prev_mark;
7735 sv_yes_mark = mark_state ?
7736 mark_state->u.mark.mark_name : NULL;
7739 NOT_REACHED; /* NOTREACHED */
7741 case SKIP: /* (*SKIP) */
7743 /* (*SKIP) : if we fail we cut here*/
7744 ST.mark_name = NULL;
7745 ST.mark_loc = locinput;
7746 PUSH_STATE_GOTO(SKIP_next,next, locinput);
7748 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
7749 otherwise do nothing. Meaning we need to scan
7751 regmatch_state *cur = mark_state;
7752 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7755 if ( sv_eq( cur->u.mark.mark_name,
7758 ST.mark_name = find;
7759 PUSH_STATE_GOTO( SKIP_next, next, locinput);
7761 cur = cur->u.mark.prev_mark;
7764 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
7767 case SKIP_next_fail:
7769 /* (*CUT:NAME) - Set up to search for the name as we
7770 collapse the stack*/
7771 popmark = ST.mark_name;
7773 /* (*CUT) - No name, we cut here.*/
7774 if (ST.mark_loc > startpoint)
7775 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7776 /* but we set sv_commit to latest mark_name if there
7777 is one so they can test to see how things lead to this
7780 sv_commit=mark_state->u.mark.mark_name;
7785 NOT_REACHED; /* NOTREACHED */
7788 case LNBREAK: /* \R */
7789 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
7796 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
7797 PTR2UV(scan), OP(scan));
7798 Perl_croak(aTHX_ "regexp memory corruption");
7800 /* this is a point to jump to in order to increment
7801 * locinput by one character */
7803 assert(!NEXTCHR_IS_EOS);
7805 locinput += PL_utf8skip[nextchr];
7806 /* locinput is allowed to go 1 char off the end, but not 2+ */
7807 if (locinput > reginfo->strend)
7816 /* switch break jumps here */
7817 scan = next; /* prepare to execute the next op and ... */
7818 continue; /* ... jump back to the top, reusing st */
7822 /* push a state that backtracks on success */
7823 st->u.yes.prev_yes_state = yes_state;
7827 /* push a new regex state, then continue at scan */
7829 regmatch_state *newst;
7832 regmatch_state *cur = st;
7833 regmatch_state *curyes = yes_state;
7835 regmatch_slab *slab = PL_regmatch_slab;
7836 for (;curd > -1;cur--,curd--) {
7837 if (cur < SLAB_FIRST(slab)) {
7839 cur = SLAB_LAST(slab);
7841 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
7842 REPORT_CODE_OFF + 2 + depth * 2,"",
7843 curd, PL_reg_name[cur->resume_state],
7844 (curyes == cur) ? "yes" : ""
7847 curyes = cur->u.yes.prev_yes_state;
7850 DEBUG_STATE_pp("push")
7853 st->locinput = locinput;
7855 if (newst > SLAB_LAST(PL_regmatch_slab))
7856 newst = S_push_slab(aTHX);
7857 PL_regmatch_state = newst;
7859 locinput = pushinput;
7867 * We get here only if there's trouble -- normally "case END" is
7868 * the terminating point.
7870 Perl_croak(aTHX_ "corrupted regexp pointers");
7873 NOT_REACHED; /* NOTREACHED */
7877 /* we have successfully completed a subexpression, but we must now
7878 * pop to the state marked by yes_state and continue from there */
7879 assert(st != yes_state);
7881 while (st != yes_state) {
7883 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7884 PL_regmatch_slab = PL_regmatch_slab->prev;
7885 st = SLAB_LAST(PL_regmatch_slab);
7889 DEBUG_STATE_pp("pop (no final)");
7891 DEBUG_STATE_pp("pop (yes)");
7897 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
7898 || yes_state > SLAB_LAST(PL_regmatch_slab))
7900 /* not in this slab, pop slab */
7901 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
7902 PL_regmatch_slab = PL_regmatch_slab->prev;
7903 st = SLAB_LAST(PL_regmatch_slab);
7905 depth -= (st - yes_state);
7908 yes_state = st->u.yes.prev_yes_state;
7909 PL_regmatch_state = st;
7912 locinput= st->locinput;
7913 state_num = st->resume_state + no_final;
7914 goto reenter_switch;
7917 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
7918 PL_colors[4], PL_colors[5]));
7920 if (reginfo->info_aux_eval) {
7921 /* each successfully executed (?{...}) block does the equivalent of
7922 * local $^R = do {...}
7923 * When popping the save stack, all these locals would be undone;
7924 * bypass this by setting the outermost saved $^R to the latest
7926 /* I dont know if this is needed or works properly now.
7927 * see code related to PL_replgv elsewhere in this file.
7930 if (oreplsv != GvSV(PL_replgv))
7931 sv_setsv(oreplsv, GvSV(PL_replgv));
7938 PerlIO_printf(Perl_debug_log,
7939 "%*s %sfailed...%s\n",
7940 REPORT_CODE_OFF+depth*2, "",
7941 PL_colors[4], PL_colors[5])
7953 /* there's a previous state to backtrack to */
7955 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7956 PL_regmatch_slab = PL_regmatch_slab->prev;
7957 st = SLAB_LAST(PL_regmatch_slab);
7959 PL_regmatch_state = st;
7960 locinput= st->locinput;
7962 DEBUG_STATE_pp("pop");
7964 if (yes_state == st)
7965 yes_state = st->u.yes.prev_yes_state;
7967 state_num = st->resume_state + 1; /* failure = success + 1 */
7968 goto reenter_switch;
7973 if (rex->intflags & PREGf_VERBARG_SEEN) {
7974 SV *sv_err = get_sv("REGERROR", 1);
7975 SV *sv_mrk = get_sv("REGMARK", 1);
7977 sv_commit = &PL_sv_no;
7979 sv_yes_mark = &PL_sv_yes;
7982 sv_commit = &PL_sv_yes;
7983 sv_yes_mark = &PL_sv_no;
7987 sv_setsv(sv_err, sv_commit);
7988 sv_setsv(sv_mrk, sv_yes_mark);
7992 if (last_pushed_cv) {
7995 PERL_UNUSED_VAR(SP);
7998 assert(!result || locinput - reginfo->strbeg >= 0);
7999 return result ? locinput - reginfo->strbeg : -1;
8003 - regrepeat - repeatedly match something simple, report how many
8005 * What 'simple' means is a node which can be the operand of a quantifier like
8008 * startposp - pointer a pointer to the start position. This is updated
8009 * to point to the byte following the highest successful
8011 * p - the regnode to be repeatedly matched against.
8012 * reginfo - struct holding match state, such as strend
8013 * max - maximum number of things to match.
8014 * depth - (for debugging) backtracking depth.
8017 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8018 regmatch_info *const reginfo, I32 max, int depth)
8020 char *scan; /* Pointer to current position in target string */
8022 char *loceol = reginfo->strend; /* local version */
8023 I32 hardcount = 0; /* How many matches so far */
8024 bool utf8_target = reginfo->is_utf8_target;
8025 unsigned int to_complement = 0; /* Invert the result? */
8027 _char_class_number classnum;
8029 PERL_UNUSED_ARG(depth);
8032 PERL_ARGS_ASSERT_REGREPEAT;
8035 if (max == REG_INFTY)
8037 else if (! utf8_target && loceol - scan > max)
8038 loceol = scan + max;
8040 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8041 * to the maximum of how far we should go in it (leaving it set to the real
8042 * end, if the maximum permissible would take us beyond that). This allows
8043 * us to make the loop exit condition that we haven't gone past <loceol> to
8044 * also mean that we haven't exceeded the max permissible count, saving a
8045 * test each time through the loop. But it assumes that the OP matches a
8046 * single byte, which is true for most of the OPs below when applied to a
8047 * non-UTF-8 target. Those relatively few OPs that don't have this
8048 * characteristic will have to compensate.
8050 * There is no adjustment for UTF-8 targets, as the number of bytes per
8051 * character varies. OPs will have to test both that the count is less
8052 * than the max permissible (using <hardcount> to keep track), and that we
8053 * are still within the bounds of the string (using <loceol>. A few OPs
8054 * match a single byte no matter what the encoding. They can omit the max
8055 * test if, for the UTF-8 case, they do the adjustment that was skipped
8058 * Thus, the code above sets things up for the common case; and exceptional
8059 * cases need extra work; the common case is to make sure <scan> doesn't
8060 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8061 * count doesn't exceed the maximum permissible */
8066 while (scan < loceol && hardcount < max && *scan != '\n') {
8067 scan += UTF8SKIP(scan);
8071 while (scan < loceol && *scan != '\n')
8077 while (scan < loceol && hardcount < max) {
8078 scan += UTF8SKIP(scan);
8086 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8087 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8088 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8092 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8096 /* Can use a simple loop if the pattern char to match on is invariant
8097 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8098 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8099 * true iff it doesn't matter if the argument is in UTF-8 or not */
8100 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8101 if (utf8_target && loceol - scan > max) {
8102 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8103 * since here, to match at all, 1 char == 1 byte */
8104 loceol = scan + max;
8106 while (scan < loceol && UCHARAT(scan) == c) {
8110 else if (reginfo->is_utf8_pat) {
8112 STRLEN scan_char_len;
8114 /* When both target and pattern are UTF-8, we have to do
8116 while (hardcount < max
8118 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8119 && memEQ(scan, STRING(p), scan_char_len))
8121 scan += scan_char_len;
8125 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8127 /* Target isn't utf8; convert the character in the UTF-8
8128 * pattern to non-UTF8, and do a simple loop */
8129 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8130 while (scan < loceol && UCHARAT(scan) == c) {
8133 } /* else pattern char is above Latin1, can't possibly match the
8138 /* Here, the string must be utf8; pattern isn't, and <c> is
8139 * different in utf8 than not, so can't compare them directly.
8140 * Outside the loop, find the two utf8 bytes that represent c, and
8141 * then look for those in sequence in the utf8 string */
8142 U8 high = UTF8_TWO_BYTE_HI(c);
8143 U8 low = UTF8_TWO_BYTE_LO(c);
8145 while (hardcount < max
8146 && scan + 1 < loceol
8147 && UCHARAT(scan) == high
8148 && UCHARAT(scan + 1) == low)
8156 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8157 assert(! reginfo->is_utf8_pat);
8160 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8164 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8165 utf8_flags = FOLDEQ_LOCALE;
8168 case EXACTF: /* This node only generated for non-utf8 patterns */
8169 assert(! reginfo->is_utf8_pat);
8174 if (! utf8_target) {
8177 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8178 | FOLDEQ_S2_FOLDS_SANE;
8183 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8187 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8189 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8191 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8194 if (c1 == CHRTEST_VOID) {
8195 /* Use full Unicode fold matching */
8196 char *tmpeol = reginfo->strend;
8197 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8198 while (hardcount < max
8199 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8200 STRING(p), NULL, pat_len,
8201 reginfo->is_utf8_pat, utf8_flags))
8204 tmpeol = reginfo->strend;
8208 else if (utf8_target) {
8210 while (scan < loceol
8212 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8214 scan += UTF8SKIP(scan);
8219 while (scan < loceol
8221 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8222 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8224 scan += UTF8SKIP(scan);
8229 else if (c1 == c2) {
8230 while (scan < loceol && UCHARAT(scan) == c1) {
8235 while (scan < loceol &&
8236 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8245 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8249 while (hardcount < max
8251 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8253 scan += UTF8SKIP(scan);
8257 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
8262 /* The argument (FLAGS) to all the POSIX node types is the class number */
8269 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8270 if (! utf8_target) {
8271 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8277 while (hardcount < max && scan < loceol
8278 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8281 scan += UTF8SKIP(scan);
8294 if (utf8_target && loceol - scan > max) {
8296 /* We didn't adjust <loceol> at the beginning of this routine
8297 * because is UTF-8, but it is actually ok to do so, since here, to
8298 * match, 1 char == 1 byte. */
8299 loceol = scan + max;
8301 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8314 if (! utf8_target) {
8315 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8321 /* The complement of something that matches only ASCII matches all
8322 * non-ASCII, plus everything in ASCII that isn't in the class. */
8323 while (hardcount < max && scan < loceol
8324 && (! isASCII_utf8(scan)
8325 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8327 scan += UTF8SKIP(scan);
8338 if (! utf8_target) {
8339 while (scan < loceol && to_complement
8340 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8347 classnum = (_char_class_number) FLAGS(p);
8348 if (classnum < _FIRST_NON_SWASH_CC) {
8350 /* Here, a swash is needed for above-Latin1 code points.
8351 * Process as many Latin1 code points using the built-in rules.
8352 * Go to another loop to finish processing upon encountering
8353 * the first Latin1 code point. We could do that in this loop
8354 * as well, but the other way saves having to test if the swash
8355 * has been loaded every time through the loop: extra space to
8357 while (hardcount < max && scan < loceol) {
8358 if (UTF8_IS_INVARIANT(*scan)) {
8359 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8366 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8367 if (! (to_complement
8368 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
8377 goto found_above_latin1;
8384 /* For these character classes, the knowledge of how to handle
8385 * every code point is compiled in to Perl via a macro. This
8386 * code is written for making the loops as tight as possible.
8387 * It could be refactored to save space instead */
8389 case _CC_ENUM_SPACE:
8390 while (hardcount < max
8392 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8394 scan += UTF8SKIP(scan);
8398 case _CC_ENUM_BLANK:
8399 while (hardcount < max
8401 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8403 scan += UTF8SKIP(scan);
8407 case _CC_ENUM_XDIGIT:
8408 while (hardcount < max
8410 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8412 scan += UTF8SKIP(scan);
8416 case _CC_ENUM_VERTSPACE:
8417 while (hardcount < max
8419 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8421 scan += UTF8SKIP(scan);
8425 case _CC_ENUM_CNTRL:
8426 while (hardcount < max
8428 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8430 scan += UTF8SKIP(scan);
8435 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8441 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
8443 /* Load the swash if not already present */
8444 if (! PL_utf8_swash_ptrs[classnum]) {
8445 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8446 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8450 PL_XPosix_ptrs[classnum], &flags);
8453 while (hardcount < max && scan < loceol
8454 && to_complement ^ cBOOL(_generic_utf8(
8457 swash_fetch(PL_utf8_swash_ptrs[classnum],
8461 scan += UTF8SKIP(scan);
8468 while (hardcount < max && scan < loceol &&
8469 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8474 /* LNBREAK can match one or two latin chars, which is ok, but we
8475 * have to use hardcount in this situation, and throw away the
8476 * adjustment to <loceol> done before the switch statement */
8477 loceol = reginfo->strend;
8478 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8487 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8501 /* These are all 0 width, so match right here or not at all. */
8505 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8507 NOT_REACHED; /* NOTREACHED */
8514 c = scan - *startposp;
8518 GET_RE_DEBUG_FLAGS_DECL;
8520 SV * const prop = sv_newmortal();
8521 regprop(prog, prop, p, reginfo, NULL);
8522 PerlIO_printf(Perl_debug_log,
8523 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
8524 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8532 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8534 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
8535 create a copy so that changes the caller makes won't change the shared one.
8536 If <altsvp> is non-null, will return NULL in it, for back-compat.
8539 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8541 PERL_ARGS_ASSERT_REGCLASS_SWASH;
8547 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8550 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8553 - reginclass - determine if a character falls into a character class
8555 n is the ANYOF-type regnode
8556 p is the target string
8557 p_end points to one byte beyond the end of the target string
8558 utf8_target tells whether p is in UTF-8.
8560 Returns true if matched; false otherwise.
8562 Note that this can be a synthetic start class, a combination of various
8563 nodes, so things you think might be mutually exclusive, such as locale,
8564 aren't. It can match both locale and non-locale
8569 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8572 const char flags = ANYOF_FLAGS(n);
8576 PERL_ARGS_ASSERT_REGINCLASS;
8578 /* If c is not already the code point, get it. Note that
8579 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8580 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8582 c = utf8n_to_uvchr(p, p_end - p, &c_len,
8583 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8584 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8585 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8586 * UTF8_ALLOW_FFFF */
8587 if (c_len == (STRLEN)-1)
8588 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8589 if (c > 255 && OP(n) == ANYOFL && ! is_ANYOF_SYNTHETIC(n)) {
8590 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8594 /* If this character is potentially in the bitmap, check it */
8595 if (c < NUM_ANYOF_CODE_POINTS) {
8596 if (ANYOF_BITMAP_TEST(n, c))
8598 else if ((flags & ANYOF_MATCHES_ALL_NON_UTF8_NON_ASCII)
8604 else if (flags & ANYOF_LOCALE_FLAGS) {
8605 if ((flags & ANYOF_LOC_FOLD)
8607 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
8611 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
8615 /* The data structure is arranged so bits 0, 2, 4, ... are set
8616 * if the class includes the Posix character class given by
8617 * bit/2; and 1, 3, 5, ... are set if the class includes the
8618 * complemented Posix class given by int(bit/2). So we loop
8619 * through the bits, each time changing whether we complement
8620 * the result or not. Suppose for the sake of illustration
8621 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
8622 * is set, it means there is a match for this ANYOF node if the
8623 * character is in the class given by the expression (0 / 2 = 0
8624 * = \w). If it is in that class, isFOO_lc() will return 1,
8625 * and since 'to_complement' is 0, the result will stay TRUE,
8626 * and we exit the loop. Suppose instead that bit 0 is 0, but
8627 * bit 1 is 1. That means there is a match if the character
8628 * matches \W. We won't bother to call isFOO_lc() on bit 0,
8629 * but will on bit 1. On the second iteration 'to_complement'
8630 * will be 1, so the exclusive or will reverse things, so we
8631 * are testing for \W. On the third iteration, 'to_complement'
8632 * will be 0, and we would be testing for \s; the fourth
8633 * iteration would test for \S, etc.
8635 * Note that this code assumes that all the classes are closed
8636 * under folding. For example, if a character matches \w, then
8637 * its fold does too; and vice versa. This should be true for
8638 * any well-behaved locale for all the currently defined Posix
8639 * classes, except for :lower: and :upper:, which are handled
8640 * by the pseudo-class :cased: which matches if either of the
8641 * other two does. To get rid of this assumption, an outer
8642 * loop could be used below to iterate over both the source
8643 * character, and its fold (if different) */
8646 int to_complement = 0;
8648 while (count < ANYOF_MAX) {
8649 if (ANYOF_POSIXL_TEST(n, count)
8650 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
8663 /* If the bitmap didn't (or couldn't) match, and something outside the
8664 * bitmap could match, try that. */
8666 if (c >= NUM_ANYOF_CODE_POINTS
8667 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
8669 match = TRUE; /* Everything above the bitmap matches */
8671 else if ((flags & ANYOF_HAS_NONBITMAP_NON_UTF8_MATCHES)
8672 || (utf8_target && (flags & ANYOF_HAS_UTF8_NONBITMAP_MATCHES))
8673 || ((flags & ANYOF_LOC_FOLD)
8674 && IN_UTF8_CTYPE_LOCALE
8675 && ARG(n) != ANYOF_ONLY_HAS_BITMAP))
8677 SV* only_utf8_locale = NULL;
8678 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
8679 &only_utf8_locale, NULL);
8685 } else { /* Convert to utf8 */
8686 utf8_p = utf8_buffer;
8687 append_utf8_from_native_byte(*p, &utf8_p);
8688 utf8_p = utf8_buffer;
8691 if (swash_fetch(sw, utf8_p, TRUE)) {
8695 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
8696 match = _invlist_contains_cp(only_utf8_locale, c);
8700 if (UNICODE_IS_SUPER(c)
8701 && (flags & ANYOF_WARN_SUPER)
8702 && ckWARN_d(WARN_NON_UNICODE))
8704 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
8705 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
8709 #if ANYOF_INVERT != 1
8710 /* Depending on compiler optimization cBOOL takes time, so if don't have to
8712 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
8715 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
8716 return (flags & ANYOF_INVERT) ^ match;
8720 S_reghop3(U8 *s, SSize_t off, const U8* lim)
8722 /* return the position 'off' UTF-8 characters away from 's', forward if
8723 * 'off' >= 0, backwards if negative. But don't go outside of position
8724 * 'lim', which better be < s if off < 0 */
8726 PERL_ARGS_ASSERT_REGHOP3;
8729 while (off-- && s < lim) {
8730 /* XXX could check well-formedness here */
8735 while (off++ && s > lim) {
8737 if (UTF8_IS_CONTINUED(*s)) {
8738 while (s > lim && UTF8_IS_CONTINUATION(*s))
8741 /* XXX could check well-formedness here */
8748 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
8750 PERL_ARGS_ASSERT_REGHOP4;
8753 while (off-- && s < rlim) {
8754 /* XXX could check well-formedness here */
8759 while (off++ && s > llim) {
8761 if (UTF8_IS_CONTINUED(*s)) {
8762 while (s > llim && UTF8_IS_CONTINUATION(*s))
8765 /* XXX could check well-formedness here */
8771 /* like reghop3, but returns NULL on overrun, rather than returning last
8775 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
8777 PERL_ARGS_ASSERT_REGHOPMAYBE3;
8780 while (off-- && s < lim) {
8781 /* XXX could check well-formedness here */
8788 while (off++ && s > lim) {
8790 if (UTF8_IS_CONTINUED(*s)) {
8791 while (s > lim && UTF8_IS_CONTINUATION(*s))
8794 /* XXX could check well-formedness here */
8803 /* when executing a regex that may have (?{}), extra stuff needs setting
8804 up that will be visible to the called code, even before the current
8805 match has finished. In particular:
8807 * $_ is localised to the SV currently being matched;
8808 * pos($_) is created if necessary, ready to be updated on each call-out
8810 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
8811 isn't set until the current pattern is successfully finished), so that
8812 $1 etc of the match-so-far can be seen;
8813 * save the old values of subbeg etc of the current regex, and set then
8814 to the current string (again, this is normally only done at the end
8819 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
8822 regexp *const rex = ReANY(reginfo->prog);
8823 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
8825 eval_state->rex = rex;
8828 /* Make $_ available to executed code. */
8829 if (reginfo->sv != DEFSV) {
8831 DEFSV_set(reginfo->sv);
8834 if (!(mg = mg_find_mglob(reginfo->sv))) {
8835 /* prepare for quick setting of pos */
8836 mg = sv_magicext_mglob(reginfo->sv);
8839 eval_state->pos_magic = mg;
8840 eval_state->pos = mg->mg_len;
8841 eval_state->pos_flags = mg->mg_flags;
8844 eval_state->pos_magic = NULL;
8846 if (!PL_reg_curpm) {
8847 /* PL_reg_curpm is a fake PMOP that we can attach the current
8848 * regex to and point PL_curpm at, so that $1 et al are visible
8849 * within a /(?{})/. It's just allocated once per interpreter the
8850 * first time its needed */
8851 Newxz(PL_reg_curpm, 1, PMOP);
8854 SV* const repointer = &PL_sv_undef;
8855 /* this regexp is also owned by the new PL_reg_curpm, which
8856 will try to free it. */
8857 av_push(PL_regex_padav, repointer);
8858 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
8859 PL_regex_pad = AvARRAY(PL_regex_padav);
8863 SET_reg_curpm(reginfo->prog);
8864 eval_state->curpm = PL_curpm;
8865 PL_curpm = PL_reg_curpm;
8866 if (RXp_MATCH_COPIED(rex)) {
8867 /* Here is a serious problem: we cannot rewrite subbeg,
8868 since it may be needed if this match fails. Thus
8869 $` inside (?{}) could fail... */
8870 eval_state->subbeg = rex->subbeg;
8871 eval_state->sublen = rex->sublen;
8872 eval_state->suboffset = rex->suboffset;
8873 eval_state->subcoffset = rex->subcoffset;
8875 eval_state->saved_copy = rex->saved_copy;
8877 RXp_MATCH_COPIED_off(rex);
8880 eval_state->subbeg = NULL;
8881 rex->subbeg = (char *)reginfo->strbeg;
8883 rex->subcoffset = 0;
8884 rex->sublen = reginfo->strend - reginfo->strbeg;
8888 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8891 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8893 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8894 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8897 Safefree(aux->poscache);
8901 /* undo the effects of S_setup_eval_state() */
8903 if (eval_state->subbeg) {
8904 regexp * const rex = eval_state->rex;
8905 rex->subbeg = eval_state->subbeg;
8906 rex->sublen = eval_state->sublen;
8907 rex->suboffset = eval_state->suboffset;
8908 rex->subcoffset = eval_state->subcoffset;
8910 rex->saved_copy = eval_state->saved_copy;
8912 RXp_MATCH_COPIED_on(rex);
8914 if (eval_state->pos_magic)
8916 eval_state->pos_magic->mg_len = eval_state->pos;
8917 eval_state->pos_magic->mg_flags =
8918 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8919 | (eval_state->pos_flags & MGf_BYTES);
8922 PL_curpm = eval_state->curpm;
8925 PL_regmatch_state = aux->old_regmatch_state;
8926 PL_regmatch_slab = aux->old_regmatch_slab;
8928 /* free all slabs above current one - this must be the last action
8929 * of this function, as aux and eval_state are allocated within
8930 * slabs and may be freed here */
8932 s = PL_regmatch_slab->next;
8934 PL_regmatch_slab->next = NULL;
8936 regmatch_slab * const osl = s;
8945 S_to_utf8_substr(pTHX_ regexp *prog)
8947 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8948 * on the converted value */
8952 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8955 if (prog->substrs->data[i].substr
8956 && !prog->substrs->data[i].utf8_substr) {
8957 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8958 prog->substrs->data[i].utf8_substr = sv;
8959 sv_utf8_upgrade(sv);
8960 if (SvVALID(prog->substrs->data[i].substr)) {
8961 if (SvTAIL(prog->substrs->data[i].substr)) {
8962 /* Trim the trailing \n that fbm_compile added last
8964 SvCUR_set(sv, SvCUR(sv) - 1);
8965 /* Whilst this makes the SV technically "invalid" (as its
8966 buffer is no longer followed by "\0") when fbm_compile()
8967 adds the "\n" back, a "\0" is restored. */
8968 fbm_compile(sv, FBMcf_TAIL);
8972 if (prog->substrs->data[i].substr == prog->check_substr)
8973 prog->check_utf8 = sv;
8979 S_to_byte_substr(pTHX_ regexp *prog)
8981 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8982 * on the converted value; returns FALSE if can't be converted. */
8986 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8989 if (prog->substrs->data[i].utf8_substr
8990 && !prog->substrs->data[i].substr) {
8991 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
8992 if (! sv_utf8_downgrade(sv, TRUE)) {
8995 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
8996 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
8997 /* Trim the trailing \n that fbm_compile added last
8999 SvCUR_set(sv, SvCUR(sv) - 1);
9000 fbm_compile(sv, FBMcf_TAIL);
9004 prog->substrs->data[i].substr = sv;
9005 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9006 prog->check_substr = sv;
9014 * ex: set ts=8 sts=4 sw=4 et: