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
78 #undef PERL_IN_XSUB_RE
79 #define PERL_IN_XSUB_RE 1
82 #undef PERL_IN_XSUB_RE
84 #ifdef PERL_IN_XSUB_RE
90 #include "inline_invlist.c"
91 #include "unicode_constants.h"
94 /* At least one required character in the target string is expressible only in
96 static const char* const non_utf8_target_but_utf8_required
97 = "Can't match, because target string needs to be in UTF-8\n";
100 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
101 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
105 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
108 #define STATIC static
111 /* Valid only for non-utf8 strings: avoids the reginclass
112 * call if there are no complications: i.e., if everything matchable is
113 * straight forward in the bitmap */
114 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
115 : ANYOF_BITMAP_TEST(p,*(c)))
121 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
122 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
124 #define HOPc(pos,off) \
125 (char *)(reginfo->is_utf8_target \
126 ? reghop3((U8*)pos, off, \
127 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
130 #define HOPBACKc(pos, off) \
131 (char*)(reginfo->is_utf8_target \
132 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
133 : (pos - off >= reginfo->strbeg) \
137 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
138 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
140 /* lim must be +ve. Returns NULL on overshoot */
141 #define HOPMAYBE3(pos,off,lim) \
142 (reginfo->is_utf8_target \
143 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
144 : ((U8*)pos + off <= lim) \
148 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
149 * off must be >=0; args should be vars rather than expressions */
150 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
151 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
152 : (U8*)((pos + off) > lim ? lim : (pos + off)))
154 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
155 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
157 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
159 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
160 #define NEXTCHR_IS_EOS (nextchr < 0)
162 #define SET_nextchr \
163 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
165 #define SET_locinput(p) \
170 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
172 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
173 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
174 1, 0, invlist, &flags); \
179 /* If in debug mode, we test that a known character properly matches */
181 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
184 utf8_char_in_property) \
185 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
186 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
188 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
191 utf8_char_in_property) \
192 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
195 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
196 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
198 PL_XPosix_ptrs[_CC_WORDCHAR], \
199 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
201 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
202 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
204 /* for use after a quantifier and before an EXACT-like node -- japhy */
205 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
207 * NOTE that *nothing* that affects backtracking should be in here, specifically
208 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
209 * node that is in between two EXACT like nodes when ascertaining what the required
210 * "follow" character is. This should probably be moved to regex compile time
211 * although it may be done at run time beause of the REF possibility - more
212 * investigation required. -- demerphq
214 #define JUMPABLE(rn) ( \
216 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
218 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
219 OP(rn) == PLUS || OP(rn) == MINMOD || \
221 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
223 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
225 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
228 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
229 we don't need this definition. XXX These are now out-of-sync*/
230 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
231 #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 )
232 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
235 /* ... so we use this as its faster. */
236 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
237 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
238 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
239 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
244 Search for mandatory following text node; for lookahead, the text must
245 follow but for lookbehind (rn->flags != 0) we skip to the next step.
247 #define FIND_NEXT_IMPT(rn) STMT_START { \
248 while (JUMPABLE(rn)) { \
249 const OPCODE type = OP(rn); \
250 if (type == SUSPEND || PL_regkind[type] == CURLY) \
251 rn = NEXTOPER(NEXTOPER(rn)); \
252 else if (type == PLUS) \
254 else if (type == IFMATCH) \
255 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
256 else rn += NEXT_OFF(rn); \
260 #define SLAB_FIRST(s) (&(s)->states[0])
261 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
263 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
264 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
265 static regmatch_state * S_push_slab(pTHX);
267 #define REGCP_PAREN_ELEMS 3
268 #define REGCP_OTHER_ELEMS 3
269 #define REGCP_FRAME_ELEMS 1
270 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
271 * are needed for the regexp context stack bookkeeping. */
274 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
276 const int retval = PL_savestack_ix;
277 const int paren_elems_to_push =
278 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
279 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
280 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
282 GET_RE_DEBUG_FLAGS_DECL;
284 PERL_ARGS_ASSERT_REGCPPUSH;
286 if (paren_elems_to_push < 0)
287 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
288 (int)paren_elems_to_push, (int)maxopenparen,
289 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
291 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
292 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
293 " out of range (%lu-%ld)",
295 (unsigned long)maxopenparen,
298 SSGROW(total_elems + REGCP_FRAME_ELEMS);
301 if ((int)maxopenparen > (int)parenfloor)
302 PerlIO_printf(Perl_debug_log,
303 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
308 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
309 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
310 SSPUSHIV(rex->offs[p].end);
311 SSPUSHIV(rex->offs[p].start);
312 SSPUSHINT(rex->offs[p].start_tmp);
313 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
314 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
316 (IV)rex->offs[p].start,
317 (IV)rex->offs[p].start_tmp,
321 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
322 SSPUSHINT(maxopenparen);
323 SSPUSHINT(rex->lastparen);
324 SSPUSHINT(rex->lastcloseparen);
325 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
330 /* These are needed since we do not localize EVAL nodes: */
331 #define REGCP_SET(cp) \
333 PerlIO_printf(Perl_debug_log, \
334 " Setting an EVAL scope, savestack=%"IVdf"\n", \
335 (IV)PL_savestack_ix)); \
338 #define REGCP_UNWIND(cp) \
340 if (cp != PL_savestack_ix) \
341 PerlIO_printf(Perl_debug_log, \
342 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
343 (IV)(cp), (IV)PL_savestack_ix)); \
346 #define UNWIND_PAREN(lp, lcp) \
347 for (n = rex->lastparen; n > lp; n--) \
348 rex->offs[n].end = -1; \
349 rex->lastparen = n; \
350 rex->lastcloseparen = lcp;
354 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
358 GET_RE_DEBUG_FLAGS_DECL;
360 PERL_ARGS_ASSERT_REGCPPOP;
362 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
364 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
365 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
366 rex->lastcloseparen = SSPOPINT;
367 rex->lastparen = SSPOPINT;
368 *maxopenparen_p = SSPOPINT;
370 i -= REGCP_OTHER_ELEMS;
371 /* Now restore the parentheses context. */
373 if (i || rex->lastparen + 1 <= rex->nparens)
374 PerlIO_printf(Perl_debug_log,
375 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
380 paren = *maxopenparen_p;
381 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
383 rex->offs[paren].start_tmp = SSPOPINT;
384 rex->offs[paren].start = SSPOPIV;
386 if (paren <= rex->lastparen)
387 rex->offs[paren].end = tmps;
388 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
389 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
391 (IV)rex->offs[paren].start,
392 (IV)rex->offs[paren].start_tmp,
393 (IV)rex->offs[paren].end,
394 (paren > rex->lastparen ? "(skipped)" : ""));
399 /* It would seem that the similar code in regtry()
400 * already takes care of this, and in fact it is in
401 * a better location to since this code can #if 0-ed out
402 * but the code in regtry() is needed or otherwise tests
403 * requiring null fields (pat.t#187 and split.t#{13,14}
404 * (as of patchlevel 7877) will fail. Then again,
405 * this code seems to be necessary or otherwise
406 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
407 * --jhi updated by dapm */
408 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
409 if (i > *maxopenparen_p)
410 rex->offs[i].start = -1;
411 rex->offs[i].end = -1;
412 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
413 " \\%"UVuf": %s ..-1 undeffing\n",
415 (i > *maxopenparen_p) ? "-1" : " "
421 /* restore the parens and associated vars at savestack position ix,
422 * but without popping the stack */
425 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
427 I32 tmpix = PL_savestack_ix;
428 PL_savestack_ix = ix;
429 regcppop(rex, maxopenparen_p);
430 PL_savestack_ix = tmpix;
433 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
436 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
438 /* Returns a boolean as to whether or not 'character' is a member of the
439 * Posix character class given by 'classnum' that should be equivalent to a
440 * value in the typedef '_char_class_number'.
442 * Ideally this could be replaced by a just an array of function pointers
443 * to the C library functions that implement the macros this calls.
444 * However, to compile, the precise function signatures are required, and
445 * these may vary from platform to to platform. To avoid having to figure
446 * out what those all are on each platform, I (khw) am using this method,
447 * which adds an extra layer of function call overhead (unless the C
448 * optimizer strips it away). But we don't particularly care about
449 * performance with locales anyway. */
451 switch ((_char_class_number) classnum) {
452 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
453 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
454 case _CC_ENUM_ASCII: return isASCII_LC(character);
455 case _CC_ENUM_BLANK: return isBLANK_LC(character);
456 case _CC_ENUM_CASED: return isLOWER_LC(character)
457 || isUPPER_LC(character);
458 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
459 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
460 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
461 case _CC_ENUM_LOWER: return isLOWER_LC(character);
462 case _CC_ENUM_PRINT: return isPRINT_LC(character);
463 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
464 case _CC_ENUM_SPACE: return isSPACE_LC(character);
465 case _CC_ENUM_UPPER: return isUPPER_LC(character);
466 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
467 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
468 default: /* VERTSPACE should never occur in locales */
469 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
472 NOT_REACHED; /* NOTREACHED */
477 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
479 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
480 * 'character' is a member of the Posix character class given by 'classnum'
481 * that should be equivalent to a value in the typedef
482 * '_char_class_number'.
484 * This just calls isFOO_lc on the code point for the character if it is in
485 * the range 0-255. Outside that range, all characters use Unicode
486 * rules, ignoring any locale. So use the Unicode function if this class
487 * requires a swash, and use the Unicode macro otherwise. */
489 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
491 if (UTF8_IS_INVARIANT(*character)) {
492 return isFOO_lc(classnum, *character);
494 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
495 return isFOO_lc(classnum,
496 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
499 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
501 if (classnum < _FIRST_NON_SWASH_CC) {
503 /* Initialize the swash unless done already */
504 if (! PL_utf8_swash_ptrs[classnum]) {
505 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
506 PL_utf8_swash_ptrs[classnum] =
507 _core_swash_init("utf8",
510 PL_XPosix_ptrs[classnum], &flags);
513 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
515 TRUE /* is UTF */ ));
518 switch ((_char_class_number) classnum) {
519 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
520 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
521 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
522 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
526 return FALSE; /* Things like CNTRL are always below 256 */
530 * pregexec and friends
533 #ifndef PERL_IN_XSUB_RE
535 - pregexec - match a regexp against a string
538 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
539 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
540 /* stringarg: the point in the string at which to begin matching */
541 /* strend: pointer to null at end of string */
542 /* strbeg: real beginning of string */
543 /* minend: end of match must be >= minend bytes after stringarg. */
544 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
545 * itself is accessed via the pointers above */
546 /* nosave: For optimizations. */
548 PERL_ARGS_ASSERT_PREGEXEC;
551 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
552 nosave ? 0 : REXEC_COPY_STR);
558 /* re_intuit_start():
560 * Based on some optimiser hints, try to find the earliest position in the
561 * string where the regex could match.
563 * rx: the regex to match against
564 * sv: the SV being matched: only used for utf8 flag; the string
565 * itself is accessed via the pointers below. Note that on
566 * something like an overloaded SV, SvPOK(sv) may be false
567 * and the string pointers may point to something unrelated to
569 * strbeg: real beginning of string
570 * strpos: the point in the string at which to begin matching
571 * strend: pointer to the byte following the last char of the string
572 * flags currently unused; set to 0
573 * data: currently unused; set to NULL
575 * The basic idea of re_intuit_start() is to use some known information
576 * about the pattern, namely:
578 * a) the longest known anchored substring (i.e. one that's at a
579 * constant offset from the beginning of the pattern; but not
580 * necessarily at a fixed offset from the beginning of the
582 * b) the longest floating substring (i.e. one that's not at a constant
583 * offset from the beginning of the pattern);
584 * c) Whether the pattern is anchored to the string; either
585 * an absolute anchor: /^../, or anchored to \n: /^.../m,
586 * or anchored to pos(): /\G/;
587 * d) A start class: a real or synthetic character class which
588 * represents which characters are legal at the start of the pattern;
590 * to either quickly reject the match, or to find the earliest position
591 * within the string at which the pattern might match, thus avoiding
592 * running the full NFA engine at those earlier locations, only to
593 * eventually fail and retry further along.
595 * Returns NULL if the pattern can't match, or returns the address within
596 * the string which is the earliest place the match could occur.
598 * The longest of the anchored and floating substrings is called 'check'
599 * and is checked first. The other is called 'other' and is checked
600 * second. The 'other' substring may not be present. For example,
602 * /(abc|xyz)ABC\d{0,3}DEFG/
606 * check substr (float) = "DEFG", offset 6..9 chars
607 * other substr (anchored) = "ABC", offset 3..3 chars
610 * Be aware that during the course of this function, sometimes 'anchored'
611 * refers to a substring being anchored relative to the start of the
612 * pattern, and sometimes to the pattern itself being anchored relative to
613 * the string. For example:
615 * /\dabc/: "abc" is anchored to the pattern;
616 * /^\dabc/: "abc" is anchored to the pattern and the string;
617 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
618 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
619 * but the pattern is anchored to the string.
623 Perl_re_intuit_start(pTHX_
626 const char * const strbeg,
630 re_scream_pos_data *data)
632 struct regexp *const prog = ReANY(rx);
633 SSize_t start_shift = prog->check_offset_min;
634 /* Should be nonnegative! */
635 SSize_t end_shift = 0;
636 /* current lowest pos in string where the regex can start matching */
637 char *rx_origin = strpos;
639 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
640 U8 other_ix = 1 - prog->substrs->check_ix;
642 char *other_last = strpos;/* latest pos 'other' substr already checked to */
643 char *check_at = NULL; /* check substr found at this pos */
644 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
645 RXi_GET_DECL(prog,progi);
646 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
647 regmatch_info *const reginfo = ®info_buf;
648 GET_RE_DEBUG_FLAGS_DECL;
650 PERL_ARGS_ASSERT_RE_INTUIT_START;
651 PERL_UNUSED_ARG(flags);
652 PERL_UNUSED_ARG(data);
654 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
655 "Intuit: trying to determine minimum start position...\n"));
657 /* for now, assume that all substr offsets are positive. If at some point
658 * in the future someone wants to do clever things with look-behind and
659 * -ve offsets, they'll need to fix up any code in this function
660 * which uses these offsets. See the thread beginning
661 * <20140113145929.GF27210@iabyn.com>
663 assert(prog->substrs->data[0].min_offset >= 0);
664 assert(prog->substrs->data[0].max_offset >= 0);
665 assert(prog->substrs->data[1].min_offset >= 0);
666 assert(prog->substrs->data[1].max_offset >= 0);
667 assert(prog->substrs->data[2].min_offset >= 0);
668 assert(prog->substrs->data[2].max_offset >= 0);
670 /* for now, assume that if both present, that the floating substring
671 * doesn't start before the anchored substring.
672 * If you break this assumption (e.g. doing better optimisations
673 * with lookahead/behind), then you'll need to audit the code in this
674 * function carefully first
677 ! ( (prog->anchored_utf8 || prog->anchored_substr)
678 && (prog->float_utf8 || prog->float_substr))
679 || (prog->float_min_offset >= prog->anchored_offset));
681 /* byte rather than char calculation for efficiency. It fails
682 * to quickly reject some cases that can't match, but will reject
683 * them later after doing full char arithmetic */
684 if (prog->minlen > strend - strpos) {
685 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
686 " String too short...\n"));
690 RX_MATCH_UTF8_set(rx,utf8_target);
691 reginfo->is_utf8_target = cBOOL(utf8_target);
692 reginfo->info_aux = NULL;
693 reginfo->strbeg = strbeg;
694 reginfo->strend = strend;
695 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
697 /* not actually used within intuit, but zero for safety anyway */
698 reginfo->poscache_maxiter = 0;
701 if (!prog->check_utf8 && prog->check_substr)
702 to_utf8_substr(prog);
703 check = prog->check_utf8;
705 if (!prog->check_substr && prog->check_utf8) {
706 if (! to_byte_substr(prog)) {
707 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
710 check = prog->check_substr;
713 /* dump the various substring data */
714 DEBUG_OPTIMISE_MORE_r({
716 for (i=0; i<=2; i++) {
717 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
718 : prog->substrs->data[i].substr);
722 PerlIO_printf(Perl_debug_log,
723 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
724 " useful=%"IVdf" utf8=%d [%s]\n",
726 (IV)prog->substrs->data[i].min_offset,
727 (IV)prog->substrs->data[i].max_offset,
728 (IV)prog->substrs->data[i].end_shift,
735 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
737 /* ml_anch: check after \n?
739 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
740 * with /.*.../, these flags will have been added by the
742 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
743 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
745 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
746 && !(prog->intflags & PREGf_IMPLICIT);
748 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
749 /* we are only allowed to match at BOS or \G */
751 /* trivially reject if there's a BOS anchor and we're not at BOS.
753 * Note that we don't try to do a similar quick reject for
754 * \G, since generally the caller will have calculated strpos
755 * based on pos() and gofs, so the string is already correctly
756 * anchored by definition; and handling the exceptions would
757 * be too fiddly (e.g. REXEC_IGNOREPOS).
759 if ( strpos != strbeg
760 && (prog->intflags & PREGf_ANCH_SBOL))
762 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
763 " Not at start...\n"));
767 /* in the presence of an anchor, the anchored (relative to the
768 * start of the regex) substr must also be anchored relative
769 * to strpos. So quickly reject if substr isn't found there.
770 * This works for \G too, because the caller will already have
771 * subtracted gofs from pos, and gofs is the offset from the
772 * \G to the start of the regex. For example, in /.abc\Gdef/,
773 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
774 * caller will have set strpos=pos()-4; we look for the substr
775 * at position pos()-4+1, which lines up with the "a" */
777 if (prog->check_offset_min == prog->check_offset_max) {
778 /* Substring at constant offset from beg-of-str... */
779 SSize_t slen = SvCUR(check);
780 char *s = HOP3c(strpos, prog->check_offset_min, strend);
782 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
783 " Looking for check substr at fixed offset %"IVdf"...\n",
784 (IV)prog->check_offset_min));
787 /* In this case, the regex is anchored at the end too.
788 * Unless it's a multiline match, the lengths must match
789 * exactly, give or take a \n. NB: slen >= 1 since
790 * the last char of check is \n */
792 && ( strend - s > slen
793 || strend - s < slen - 1
794 || (strend - s == slen && strend[-1] != '\n')))
796 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
797 " String too long...\n"));
800 /* Now should match s[0..slen-2] */
803 if (slen && (*SvPVX_const(check) != *s
804 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
806 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
807 " String not equal...\n"));
812 goto success_at_start;
817 end_shift = prog->check_end_shift;
819 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
821 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
822 (IV)end_shift, RX_PRECOMP(prog));
827 /* This is the (re)entry point of the main loop in this function.
828 * The goal of this loop is to:
829 * 1) find the "check" substring in the region rx_origin..strend
830 * (adjusted by start_shift / end_shift). If not found, reject
832 * 2) If it exists, look for the "other" substr too if defined; for
833 * example, if the check substr maps to the anchored substr, then
834 * check the floating substr, and vice-versa. If not found, go
835 * back to (1) with rx_origin suitably incremented.
836 * 3) If we find an rx_origin position that doesn't contradict
837 * either of the substrings, then check the possible additional
838 * constraints on rx_origin of /^.../m or a known start class.
839 * If these fail, then depending on which constraints fail, jump
840 * back to here, or to various other re-entry points further along
841 * that skip some of the first steps.
842 * 4) If we pass all those tests, update the BmUSEFUL() count on the
843 * substring. If the start position was determined to be at the
844 * beginning of the string - so, not rejected, but not optimised,
845 * since we have to run regmatch from position 0 - decrement the
846 * BmUSEFUL() count. Otherwise increment it.
850 /* first, look for the 'check' substring */
856 DEBUG_OPTIMISE_MORE_r({
857 PerlIO_printf(Perl_debug_log,
858 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
859 " Start shift: %"IVdf" End shift %"IVdf
860 " Real end Shift: %"IVdf"\n",
861 (IV)(rx_origin - strbeg),
862 (IV)prog->check_offset_min,
865 (IV)prog->check_end_shift);
868 end_point = HOP3(strend, -end_shift, strbeg);
869 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
874 /* If the regex is absolutely anchored to either the start of the
875 * string (SBOL) or to pos() (ANCH_GPOS), then
876 * check_offset_max represents an upper bound on the string where
877 * the substr could start. For the ANCH_GPOS case, we assume that
878 * the caller of intuit will have already set strpos to
879 * pos()-gofs, so in this case strpos + offset_max will still be
880 * an upper bound on the substr.
883 && prog->intflags & PREGf_ANCH
884 && prog->check_offset_max != SSize_t_MAX)
886 SSize_t len = SvCUR(check) - !!SvTAIL(check);
887 const char * const anchor =
888 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
890 /* do a bytes rather than chars comparison. It's conservative;
891 * so it skips doing the HOP if the result can't possibly end
892 * up earlier than the old value of end_point.
894 if ((char*)end_point - anchor > prog->check_offset_max) {
895 end_point = HOP3lim((U8*)anchor,
896 prog->check_offset_max,
902 check_at = fbm_instr( start_point, end_point,
903 check, multiline ? FBMrf_MULTILINE : 0);
905 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
906 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
907 (IV)((char*)start_point - strbeg),
908 (IV)((char*)end_point - strbeg),
909 (IV)(check_at ? check_at - strbeg : -1)
912 /* Update the count-of-usability, remove useless subpatterns,
916 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
917 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
918 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
919 (check_at ? "Found" : "Did not find"),
920 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
921 ? "anchored" : "floating"),
924 (check_at ? " at offset " : "...\n") );
929 /* set rx_origin to the minimum position where the regex could start
930 * matching, given the constraint of the just-matched check substring.
931 * But don't set it lower than previously.
934 if (check_at - rx_origin > prog->check_offset_max)
935 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
936 /* Finish the diagnostic message */
937 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
938 "%ld (rx_origin now %"IVdf")...\n",
939 (long)(check_at - strbeg),
940 (IV)(rx_origin - strbeg)
945 /* now look for the 'other' substring if defined */
947 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
948 : prog->substrs->data[other_ix].substr)
950 /* Take into account the "other" substring. */
954 struct reg_substr_datum *other;
957 other = &prog->substrs->data[other_ix];
959 /* if "other" is anchored:
960 * we've previously found a floating substr starting at check_at.
961 * This means that the regex origin must lie somewhere
962 * between min (rx_origin): HOP3(check_at, -check_offset_max)
963 * and max: HOP3(check_at, -check_offset_min)
964 * (except that min will be >= strpos)
965 * So the fixed substr must lie somewhere between
966 * HOP3(min, anchored_offset)
967 * HOP3(max, anchored_offset) + SvCUR(substr)
970 /* if "other" is floating
971 * Calculate last1, the absolute latest point where the
972 * floating substr could start in the string, ignoring any
973 * constraints from the earlier fixed match. It is calculated
976 * strend - prog->minlen (in chars) is the absolute latest
977 * position within the string where the origin of the regex
978 * could appear. The latest start point for the floating
979 * substr is float_min_offset(*) on from the start of the
980 * regex. last1 simply combines thee two offsets.
982 * (*) You might think the latest start point should be
983 * float_max_offset from the regex origin, and technically
984 * you'd be correct. However, consider
986 * Here, float min, max are 3,5 and minlen is 7.
987 * This can match either
991 * In the first case, the regex matches minlen chars; in the
992 * second, minlen+1, in the third, minlen+2.
993 * In the first case, the floating offset is 3 (which equals
994 * float_min), in the second, 4, and in the third, 5 (which
995 * equals float_max). In all cases, the floating string bcd
996 * can never start more than 4 chars from the end of the
997 * string, which equals minlen - float_min. As the substring
998 * starts to match more than float_min from the start of the
999 * regex, it makes the regex match more than minlen chars,
1000 * and the two cancel each other out. So we can always use
1001 * float_min - minlen, rather than float_max - minlen for the
1002 * latest position in the string.
1004 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1005 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1008 assert(prog->minlen >= other->min_offset);
1009 last1 = HOP3c(strend,
1010 other->min_offset - prog->minlen, strbeg);
1012 if (other_ix) {/* i.e. if (other-is-float) */
1013 /* last is the latest point where the floating substr could
1014 * start, *given* any constraints from the earlier fixed
1015 * match. This constraint is that the floating string starts
1016 * <= float_max_offset chars from the regex origin (rx_origin).
1017 * If this value is less than last1, use it instead.
1019 assert(rx_origin <= last1);
1021 /* this condition handles the offset==infinity case, and
1022 * is a short-cut otherwise. Although it's comparing a
1023 * byte offset to a char length, it does so in a safe way,
1024 * since 1 char always occupies 1 or more bytes,
1025 * so if a string range is (last1 - rx_origin) bytes,
1026 * it will be less than or equal to (last1 - rx_origin)
1027 * chars; meaning it errs towards doing the accurate HOP3
1028 * rather than just using last1 as a short-cut */
1029 (last1 - rx_origin) < other->max_offset
1031 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1034 assert(strpos + start_shift <= check_at);
1035 last = HOP4c(check_at, other->min_offset - start_shift,
1039 s = HOP3c(rx_origin, other->min_offset, strend);
1040 if (s < other_last) /* These positions already checked */
1043 must = utf8_target ? other->utf8_substr : other->substr;
1044 assert(SvPOK(must));
1047 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1051 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1052 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1053 (IV)(from - strbeg),
1059 (unsigned char*)from,
1062 multiline ? FBMrf_MULTILINE : 0
1064 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1065 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1066 (IV)(from - strbeg),
1068 (IV)(s ? s - strbeg : -1)
1074 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1075 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1076 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1077 s ? "Found" : "Contradicts",
1078 other_ix ? "floating" : "anchored",
1079 quoted, RE_SV_TAIL(must));
1084 /* last1 is latest possible substr location. If we didn't
1085 * find it before there, we never will */
1086 if (last >= last1) {
1087 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1088 "; giving up...\n"));
1092 /* try to find the check substr again at a later
1093 * position. Maybe next time we'll find the "other" substr
1095 other_last = HOP3c(last, 1, strend) /* highest failure */;
1097 other_ix /* i.e. if other-is-float */
1098 ? HOP3c(rx_origin, 1, strend)
1099 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1100 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1101 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1102 (other_ix ? "floating" : "anchored"),
1103 (long)(HOP3c(check_at, 1, strend) - strbeg),
1104 (IV)(rx_origin - strbeg)
1109 if (other_ix) { /* if (other-is-float) */
1110 /* other_last is set to s, not s+1, since its possible for
1111 * a floating substr to fail first time, then succeed
1112 * second time at the same floating position; e.g.:
1113 * "-AB--AABZ" =~ /\wAB\d*Z/
1114 * The first time round, anchored and float match at
1115 * "-(AB)--AAB(Z)" then fail on the initial \w character
1116 * class. Second time round, they match at "-AB--A(AB)(Z)".
1121 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1122 other_last = HOP3c(s, 1, strend);
1124 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1125 " at offset %ld (rx_origin now %"IVdf")...\n",
1127 (IV)(rx_origin - strbeg)
1133 DEBUG_OPTIMISE_MORE_r(
1134 PerlIO_printf(Perl_debug_log,
1135 " Check-only match: offset min:%"IVdf" max:%"IVdf
1136 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1137 " strend:%"IVdf"\n",
1138 (IV)prog->check_offset_min,
1139 (IV)prog->check_offset_max,
1140 (IV)(check_at-strbeg),
1141 (IV)(rx_origin-strbeg),
1142 (IV)(rx_origin-check_at),
1148 postprocess_substr_matches:
1150 /* handle the extra constraint of /^.../m if present */
1152 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1155 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1156 " looking for /^/m anchor"));
1158 /* we have failed the constraint of a \n before rx_origin.
1159 * Find the next \n, if any, even if it's beyond the current
1160 * anchored and/or floating substrings. Whether we should be
1161 * scanning ahead for the next \n or the next substr is debatable.
1162 * On the one hand you'd expect rare substrings to appear less
1163 * often than \n's. On the other hand, searching for \n means
1164 * we're effectively flipping between check_substr and "\n" on each
1165 * iteration as the current "rarest" string candidate, which
1166 * means for example that we'll quickly reject the whole string if
1167 * hasn't got a \n, rather than trying every substr position
1171 s = HOP3c(strend, - prog->minlen, strpos);
1172 if (s <= rx_origin ||
1173 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1175 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1176 " Did not find /%s^%s/m...\n",
1177 PL_colors[0], PL_colors[1]));
1181 /* earliest possible origin is 1 char after the \n.
1182 * (since *rx_origin == '\n', it's safe to ++ here rather than
1183 * HOP(rx_origin, 1)) */
1186 if (prog->substrs->check_ix == 0 /* check is anchored */
1187 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1189 /* Position contradicts check-string; either because
1190 * check was anchored (and thus has no wiggle room),
1191 * or check was float and rx_origin is above the float range */
1192 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1193 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1194 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1198 /* if we get here, the check substr must have been float,
1199 * is in range, and we may or may not have had an anchored
1200 * "other" substr which still contradicts */
1201 assert(prog->substrs->check_ix); /* check is float */
1203 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1204 /* whoops, the anchored "other" substr exists, so we still
1205 * contradict. On the other hand, the float "check" substr
1206 * didn't contradict, so just retry the anchored "other"
1208 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1209 " Found /%s^%s/m, rescanning for anchored from offset %ld (rx_origin now %"IVdf")...\n",
1210 PL_colors[0], PL_colors[1],
1211 (long)(rx_origin - strbeg + prog->anchored_offset),
1212 (long)(rx_origin - strbeg)
1214 goto do_other_substr;
1217 /* success: we don't contradict the found floating substring
1218 * (and there's no anchored substr). */
1219 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1220 " Found /%s^%s/m with rx_origin %ld...\n",
1221 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1224 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1225 " (multiline anchor test skipped)\n"));
1231 /* if we have a starting character class, then test that extra constraint.
1232 * (trie stclasses are too expensive to use here, we are better off to
1233 * leave it to regmatch itself) */
1235 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1236 const U8* const str = (U8*)STRING(progi->regstclass);
1238 /* XXX this value could be pre-computed */
1239 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1240 ? (reginfo->is_utf8_pat
1241 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1242 : STR_LEN(progi->regstclass))
1246 /* latest pos that a matching float substr constrains rx start to */
1247 char *rx_max_float = NULL;
1249 /* if the current rx_origin is anchored, either by satisfying an
1250 * anchored substring constraint, or a /^.../m constraint, then we
1251 * can reject the current origin if the start class isn't found
1252 * at the current position. If we have a float-only match, then
1253 * rx_origin is constrained to a range; so look for the start class
1254 * in that range. if neither, then look for the start class in the
1255 * whole rest of the string */
1257 /* XXX DAPM it's not clear what the minlen test is for, and why
1258 * it's not used in the floating case. Nothing in the test suite
1259 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1260 * Here are some old comments, which may or may not be correct:
1262 * minlen == 0 is possible if regstclass is \b or \B,
1263 * and the fixed substr is ''$.
1264 * Since minlen is already taken into account, rx_origin+1 is
1265 * before strend; accidentally, minlen >= 1 guaranties no false
1266 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1267 * 0) below assumes that regstclass does not come from lookahead...
1268 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1269 * This leaves EXACTF-ish only, which are dealt with in
1273 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1274 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1275 else if (prog->float_substr || prog->float_utf8) {
1276 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1277 endpos= HOP3c(rx_max_float, cl_l, strend);
1282 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1283 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1284 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1285 (IV)start_shift, (IV)(check_at - strbeg),
1286 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1288 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1291 if (endpos == strend) {
1292 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1293 " Could not match STCLASS...\n") );
1296 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1297 " This position contradicts STCLASS...\n") );
1298 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1299 && !(prog->intflags & PREGf_IMPLICIT))
1302 /* Contradict one of substrings */
1303 if (prog->anchored_substr || prog->anchored_utf8) {
1304 if (prog->substrs->check_ix == 1) { /* check is float */
1305 /* Have both, check_string is floating */
1306 assert(rx_origin + start_shift <= check_at);
1307 if (rx_origin + start_shift != check_at) {
1308 /* not at latest position float substr could match:
1309 * Recheck anchored substring, but not floating.
1310 * The condition above is in bytes rather than
1311 * chars for efficiency. It's conservative, in
1312 * that it errs on the side of doing 'goto
1313 * do_other_substr'. In this case, at worst,
1314 * an extra anchored search may get done, but in
1315 * practice the extra fbm_instr() is likely to
1316 * get skipped anyway. */
1317 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1318 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1319 (long)(other_last - strbeg),
1320 (IV)(rx_origin - strbeg)
1322 goto do_other_substr;
1330 /* In the presence of ml_anch, we might be able to
1331 * find another \n without breaking the current float
1334 /* strictly speaking this should be HOP3c(..., 1, ...),
1335 * but since we goto a block of code that's going to
1336 * search for the next \n if any, its safe here */
1338 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1339 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1340 PL_colors[0], PL_colors[1],
1341 (long)(rx_origin - strbeg)) );
1342 goto postprocess_substr_matches;
1345 /* strictly speaking this can never be true; but might
1346 * be if we ever allow intuit without substrings */
1347 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1350 rx_origin = rx_max_float;
1353 /* at this point, any matching substrings have been
1354 * contradicted. Start again... */
1356 rx_origin = HOP3c(rx_origin, 1, strend);
1358 /* uses bytes rather than char calculations for efficiency.
1359 * It's conservative: it errs on the side of doing 'goto restart',
1360 * where there is code that does a proper char-based test */
1361 if (rx_origin + start_shift + end_shift > strend) {
1362 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1363 " Could not match STCLASS...\n") );
1366 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1367 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1368 (prog->substrs->check_ix ? "floating" : "anchored"),
1369 (long)(rx_origin + start_shift - strbeg),
1370 (IV)(rx_origin - strbeg)
1377 if (rx_origin != s) {
1378 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1379 " By STCLASS: moving %ld --> %ld\n",
1380 (long)(rx_origin - strbeg), (long)(s - strbeg))
1384 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1385 " Does not contradict STCLASS...\n");
1390 /* Decide whether using the substrings helped */
1392 if (rx_origin != strpos) {
1393 /* Fixed substring is found far enough so that the match
1394 cannot start at strpos. */
1396 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1397 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1400 /* The found rx_origin position does not prohibit matching at
1401 * strpos, so calling intuit didn't gain us anything. Decrement
1402 * the BmUSEFUL() count on the check substring, and if we reach
1404 if (!(prog->intflags & PREGf_NAUGHTY)
1406 prog->check_utf8 /* Could be deleted already */
1407 && --BmUSEFUL(prog->check_utf8) < 0
1408 && (prog->check_utf8 == prog->float_utf8)
1410 prog->check_substr /* Could be deleted already */
1411 && --BmUSEFUL(prog->check_substr) < 0
1412 && (prog->check_substr == prog->float_substr)
1415 /* If flags & SOMETHING - do not do it many times on the same match */
1416 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1417 /* XXX Does the destruction order has to change with utf8_target? */
1418 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1419 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1420 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1421 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1422 check = NULL; /* abort */
1423 /* XXXX This is a remnant of the old implementation. It
1424 looks wasteful, since now INTUIT can use many
1425 other heuristics. */
1426 prog->extflags &= ~RXf_USE_INTUIT;
1430 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1431 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1432 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1436 fail_finish: /* Substring not found */
1437 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1438 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1440 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1441 PL_colors[4], PL_colors[5]));
1446 #define DECL_TRIE_TYPE(scan) \
1447 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1448 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1449 trie_utf8l, trie_flu8 } \
1450 trie_type = ((scan->flags == EXACT) \
1451 ? (utf8_target ? trie_utf8 : trie_plain) \
1452 : (scan->flags == EXACTL) \
1453 ? (utf8_target ? trie_utf8l : trie_plain) \
1454 : (scan->flags == EXACTFA) \
1456 ? trie_utf8_exactfa_fold \
1457 : trie_latin_utf8_exactfa_fold) \
1458 : (scan->flags == EXACTFLU8 \
1462 : trie_latin_utf8_fold)))
1464 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1467 U8 flags = FOLD_FLAGS_FULL; \
1468 switch (trie_type) { \
1470 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1471 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1472 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1474 goto do_trie_utf8_fold; \
1475 case trie_utf8_exactfa_fold: \
1476 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1478 case trie_utf8_fold: \
1479 do_trie_utf8_fold: \
1480 if ( foldlen>0 ) { \
1481 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1486 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1487 len = UTF8SKIP(uc); \
1488 skiplen = UNISKIP( uvc ); \
1489 foldlen -= skiplen; \
1490 uscan = foldbuf + skiplen; \
1493 case trie_latin_utf8_exactfa_fold: \
1494 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1496 case trie_latin_utf8_fold: \
1497 if ( foldlen>0 ) { \
1498 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1504 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1505 skiplen = UNISKIP( uvc ); \
1506 foldlen -= skiplen; \
1507 uscan = foldbuf + skiplen; \
1511 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1512 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1513 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1517 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1524 charid = trie->charmap[ uvc ]; \
1528 if (widecharmap) { \
1529 SV** const svpp = hv_fetch(widecharmap, \
1530 (char*)&uvc, sizeof(UV), 0); \
1532 charid = (U16)SvIV(*svpp); \
1537 #define DUMP_EXEC_POS(li,s,doutf8) \
1538 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1541 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1545 && (ln == 1 || folder(s, pat_string, ln)) \
1546 && (reginfo->intuit || regtry(reginfo, &s)) )\
1552 #define REXEC_FBC_UTF8_SCAN(CODE) \
1554 while (s < strend) { \
1560 #define REXEC_FBC_SCAN(CODE) \
1562 while (s < strend) { \
1568 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1569 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1571 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1580 #define REXEC_FBC_CLASS_SCAN(COND) \
1581 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1583 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1592 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1593 if (utf8_target) { \
1594 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1597 REXEC_FBC_CLASS_SCAN(COND); \
1600 /* The three macros below are slightly different versions of the same logic.
1602 * The first is for /a and /aa when the target string is UTF-8. This can only
1603 * match ascii, but it must advance based on UTF-8. The other two handle the
1604 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1605 * for the boundary (or non-boundary) between a word and non-word character.
1606 * The utf8 and non-utf8 cases have the same logic, but the details must be
1607 * different. Find the "wordness" of the character just prior to this one, and
1608 * compare it with the wordness of this one. If they differ, we have a
1609 * boundary. At the beginning of the string, pretend that the previous
1610 * character was a new-line.
1612 * All these macros uncleanly have side-effects with each other and outside
1613 * variables. So far it's been too much trouble to clean-up
1615 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1616 * a word character or not.
1617 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1619 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1621 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1622 * are looking for a boundary or for a non-boundary. If we are looking for a
1623 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1624 * see if this tentative match actually works, and if so, to quit the loop
1625 * here. And vice-versa if we are looking for a non-boundary.
1627 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1628 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1629 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1630 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1631 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1632 * complement. But in that branch we complement tmp, meaning that at the
1633 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1634 * which means at the top of the loop in the next iteration, it is
1635 * TEST_NON_UTF8(s-1) */
1636 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1637 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1638 tmp = TEST_NON_UTF8(tmp); \
1639 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1640 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1642 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1649 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1650 * TEST_UTF8 is a macro that for the same input code points returns identically
1651 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1652 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1653 if (s == reginfo->strbeg) { \
1656 else { /* Back-up to the start of the previous character */ \
1657 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1658 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1659 0, UTF8_ALLOW_DEFAULT); \
1661 tmp = TEST_UV(tmp); \
1662 LOAD_UTF8_CHARCLASS_ALNUM(); \
1663 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1664 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1673 /* Like the above two macros. UTF8_CODE is the complete code for handling
1674 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1676 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1677 if (utf8_target) { \
1680 else { /* Not utf8 */ \
1681 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1682 tmp = TEST_NON_UTF8(tmp); \
1683 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1684 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1693 /* Here, things have been set up by the previous code so that tmp is the \
1694 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1695 * utf8ness of the target). We also have to check if this matches against \
1696 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1697 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1699 if (tmp == ! TEST_NON_UTF8('\n')) { \
1706 /* This is the macro to use when we want to see if something that looks like it
1707 * could match, actually does, and if so exits the loop */
1708 #define REXEC_FBC_TRYIT \
1709 if ((reginfo->intuit || regtry(reginfo, &s))) \
1712 /* The only difference between the BOUND and NBOUND cases is that
1713 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1714 * NBOUND. This is accomplished by passing it as either the if or else clause,
1715 * with the other one being empty (PLACEHOLDER is defined as empty).
1717 * The TEST_FOO parameters are for operating on different forms of input, but
1718 * all should be ones that return identically for the same underlying code
1720 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1722 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1723 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1725 #define FBC_BOUND_A(TEST_NON_UTF8) \
1727 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1728 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1730 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1732 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1733 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1735 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1737 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1738 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1740 /* Takes a pointer to an inversion list, a pointer to its corresponding
1741 * inversion map, and a code point, and returns the code point's value
1742 * according to the two arrays. It assumes that all code points have a value.
1743 * This is used as the base macro for macros for particular properties */
1744 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1745 invmap[_invlist_search(invlist, cp)]
1747 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1748 * of a code point, returning the value for the first code point in the string.
1749 * And it takes the particular macro name that finds the desired value given a
1750 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1751 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1752 (__ASSERT_(pos < strend) \
1753 /* Note assumes is valid UTF-8 */ \
1754 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1756 /* Returns the GCB value for the input code point */
1757 #define getGCB_VAL_CP(cp) \
1758 _generic_GET_BREAK_VAL_CP( \
1760 Grapheme_Cluster_Break_invmap, \
1763 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1764 * bounded by pos and strend */
1765 #define getGCB_VAL_UTF8(pos, strend) \
1766 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1769 /* Returns the SB value for the input code point */
1770 #define getSB_VAL_CP(cp) \
1771 _generic_GET_BREAK_VAL_CP( \
1773 Sentence_Break_invmap, \
1776 /* Returns the SB value for the first code point in the UTF-8 encoded string
1777 * bounded by pos and strend */
1778 #define getSB_VAL_UTF8(pos, strend) \
1779 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1781 /* Returns the WB value for the input code point */
1782 #define getWB_VAL_CP(cp) \
1783 _generic_GET_BREAK_VAL_CP( \
1785 Word_Break_invmap, \
1788 /* Returns the WB value for the first code point in the UTF-8 encoded string
1789 * bounded by pos and strend */
1790 #define getWB_VAL_UTF8(pos, strend) \
1791 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1793 /* We know what class REx starts with. Try to find this position... */
1794 /* if reginfo->intuit, its a dryrun */
1795 /* annoyingly all the vars in this routine have different names from their counterparts
1796 in regmatch. /grrr */
1798 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1799 const char *strend, regmatch_info *reginfo)
1802 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1803 char *pat_string; /* The pattern's exactish string */
1804 char *pat_end; /* ptr to end char of pat_string */
1805 re_fold_t folder; /* Function for computing non-utf8 folds */
1806 const U8 *fold_array; /* array for folding ords < 256 */
1812 I32 tmp = 1; /* Scratch variable? */
1813 const bool utf8_target = reginfo->is_utf8_target;
1814 UV utf8_fold_flags = 0;
1815 const bool is_utf8_pat = reginfo->is_utf8_pat;
1816 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1817 with a result inverts that result, as 0^1 =
1819 _char_class_number classnum;
1821 RXi_GET_DECL(prog,progi);
1823 PERL_ARGS_ASSERT_FIND_BYCLASS;
1825 /* We know what class it must start with. */
1828 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1832 REXEC_FBC_UTF8_CLASS_SCAN(
1833 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1836 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1840 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1841 assert(! is_utf8_pat);
1844 if (is_utf8_pat || utf8_target) {
1845 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1846 goto do_exactf_utf8;
1848 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1849 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1850 goto do_exactf_non_utf8; /* isn't dealt with by these */
1852 case EXACTF: /* This node only generated for non-utf8 patterns */
1853 assert(! is_utf8_pat);
1855 utf8_fold_flags = 0;
1856 goto do_exactf_utf8;
1858 fold_array = PL_fold;
1860 goto do_exactf_non_utf8;
1863 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1864 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1865 utf8_fold_flags = FOLDEQ_LOCALE;
1866 goto do_exactf_utf8;
1868 fold_array = PL_fold_locale;
1869 folder = foldEQ_locale;
1870 goto do_exactf_non_utf8;
1874 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1876 goto do_exactf_utf8;
1879 if (! utf8_target) { /* All code points in this node require
1880 UTF-8 to express. */
1883 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1884 | FOLDEQ_S2_FOLDS_SANE;
1885 goto do_exactf_utf8;
1888 if (is_utf8_pat || utf8_target) {
1889 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1890 goto do_exactf_utf8;
1893 /* Any 'ss' in the pattern should have been replaced by regcomp,
1894 * so we don't have to worry here about this single special case
1895 * in the Latin1 range */
1896 fold_array = PL_fold_latin1;
1897 folder = foldEQ_latin1;
1901 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1902 are no glitches with fold-length differences
1903 between the target string and pattern */
1905 /* The idea in the non-utf8 EXACTF* cases is to first find the
1906 * first character of the EXACTF* node and then, if necessary,
1907 * case-insensitively compare the full text of the node. c1 is the
1908 * first character. c2 is its fold. This logic will not work for
1909 * Unicode semantics and the german sharp ss, which hence should
1910 * not be compiled into a node that gets here. */
1911 pat_string = STRING(c);
1912 ln = STR_LEN(c); /* length to match in octets/bytes */
1914 /* We know that we have to match at least 'ln' bytes (which is the
1915 * same as characters, since not utf8). If we have to match 3
1916 * characters, and there are only 2 availabe, we know without
1917 * trying that it will fail; so don't start a match past the
1918 * required minimum number from the far end */
1919 e = HOP3c(strend, -((SSize_t)ln), s);
1921 if (reginfo->intuit && e < s) {
1922 e = s; /* Due to minlen logic of intuit() */
1926 c2 = fold_array[c1];
1927 if (c1 == c2) { /* If char and fold are the same */
1928 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1931 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1939 /* If one of the operands is in utf8, we can't use the simpler folding
1940 * above, due to the fact that many different characters can have the
1941 * same fold, or portion of a fold, or different- length fold */
1942 pat_string = STRING(c);
1943 ln = STR_LEN(c); /* length to match in octets/bytes */
1944 pat_end = pat_string + ln;
1945 lnc = is_utf8_pat /* length to match in characters */
1946 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1949 /* We have 'lnc' characters to match in the pattern, but because of
1950 * multi-character folding, each character in the target can match
1951 * up to 3 characters (Unicode guarantees it will never exceed
1952 * this) if it is utf8-encoded; and up to 2 if not (based on the
1953 * fact that the Latin 1 folds are already determined, and the
1954 * only multi-char fold in that range is the sharp-s folding to
1955 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1956 * string character. Adjust lnc accordingly, rounding up, so that
1957 * if we need to match at least 4+1/3 chars, that really is 5. */
1958 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1959 lnc = (lnc + expansion - 1) / expansion;
1961 /* As in the non-UTF8 case, if we have to match 3 characters, and
1962 * only 2 are left, it's guaranteed to fail, so don't start a
1963 * match that would require us to go beyond the end of the string
1965 e = HOP3c(strend, -((SSize_t)lnc), s);
1967 if (reginfo->intuit && e < s) {
1968 e = s; /* Due to minlen logic of intuit() */
1971 /* XXX Note that we could recalculate e to stop the loop earlier,
1972 * as the worst case expansion above will rarely be met, and as we
1973 * go along we would usually find that e moves further to the left.
1974 * This would happen only after we reached the point in the loop
1975 * where if there were no expansion we should fail. Unclear if
1976 * worth the expense */
1979 char *my_strend= (char *)strend;
1980 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1981 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1982 && (reginfo->intuit || regtry(reginfo, &s)) )
1986 s += (utf8_target) ? UTF8SKIP(s) : 1;
1992 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1993 if (FLAGS(c) != TRADITIONAL_BOUND) {
1994 if (! IN_UTF8_CTYPE_LOCALE) {
1995 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
1996 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2001 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2005 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2006 if (FLAGS(c) != TRADITIONAL_BOUND) {
2007 if (! IN_UTF8_CTYPE_LOCALE) {
2008 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2009 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2014 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2017 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2019 assert(FLAGS(c) == TRADITIONAL_BOUND);
2021 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2024 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2026 assert(FLAGS(c) == TRADITIONAL_BOUND);
2028 FBC_BOUND_A(isWORDCHAR_A);
2031 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2033 assert(FLAGS(c) == TRADITIONAL_BOUND);
2035 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2038 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2040 assert(FLAGS(c) == TRADITIONAL_BOUND);
2042 FBC_NBOUND_A(isWORDCHAR_A);
2046 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2047 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2058 switch((bound_type) FLAGS(c)) {
2059 case TRADITIONAL_BOUND:
2060 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2063 if (s == reginfo->strbeg) { /* GCB always matches at begin and
2065 if (to_complement ^ cBOOL(reginfo->intuit
2066 || regtry(reginfo, &s)))
2070 s += (utf8_target) ? UTF8SKIP(s) : 1;
2074 GCB_enum before = getGCB_VAL_UTF8(
2076 (U8*)(reginfo->strbeg)),
2077 (U8*) reginfo->strend);
2078 while (s < strend) {
2079 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2080 (U8*) reginfo->strend);
2081 if (to_complement ^ isGCB(before, after)) {
2082 if (reginfo->intuit || regtry(reginfo, &s)) {
2090 else { /* Not utf8. Everything is a GCB except between CR and
2092 while (s < strend) {
2093 if (to_complement ^ (UCHARAT(s - 1) != '\r'
2094 || UCHARAT(s) != '\n'))
2096 if (reginfo->intuit || regtry(reginfo, &s)) {
2104 if (to_complement ^ cBOOL(reginfo->intuit || regtry(reginfo, &s))) {
2110 if (s == reginfo->strbeg) { /* SB always matches at beginning */
2112 ^ cBOOL(reginfo->intuit || regtry(reginfo, &s)))
2117 /* Didn't match. Go try at the next position */
2118 s += (utf8_target) ? UTF8SKIP(s) : 1;
2122 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2124 (U8*)(reginfo->strbeg)),
2125 (U8*) reginfo->strend);
2126 while (s < strend) {
2127 SB_enum after = getSB_VAL_UTF8((U8*) s,
2128 (U8*) reginfo->strend);
2129 if (to_complement ^ isSB(before,
2131 (U8*) reginfo->strbeg,
2133 (U8*) reginfo->strend,
2136 if (reginfo->intuit || regtry(reginfo, &s)) {
2144 else { /* Not utf8. */
2145 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2146 while (s < strend) {
2147 SB_enum after = getSB_VAL_CP((U8) *s);
2148 if (to_complement ^ isSB(before,
2150 (U8*) reginfo->strbeg,
2152 (U8*) reginfo->strend,
2155 if (reginfo->intuit || regtry(reginfo, &s)) {
2164 /* Here are at the final position in the target string. The SB
2165 * value is always true here, so matches, depending on other
2167 if (to_complement ^ cBOOL(reginfo->intuit
2168 || regtry(reginfo, &s)))
2176 if (s == reginfo->strbeg) {
2177 if (to_complement ^ cBOOL(reginfo->intuit
2178 || regtry(reginfo, &s)))
2182 s += (utf8_target) ? UTF8SKIP(s) : 1;
2186 /* We are at a boundary between char_sub_0 and char_sub_1.
2187 * We also keep track of the value for char_sub_-1 as we
2188 * loop through the line. Context may be needed to make a
2189 * determination, and if so, this can save having to
2191 WB_enum previous = WB_UNKNOWN;
2192 WB_enum before = getWB_VAL_UTF8(
2195 (U8*)(reginfo->strbeg)),
2196 (U8*) reginfo->strend);
2197 while (s < strend) {
2198 WB_enum after = getWB_VAL_UTF8((U8*) s,
2199 (U8*) reginfo->strend);
2200 if (to_complement ^ isWB(previous,
2203 (U8*) reginfo->strbeg,
2205 (U8*) reginfo->strend,
2208 if (reginfo->intuit || regtry(reginfo, &s)) {
2217 else { /* Not utf8. */
2218 WB_enum previous = WB_UNKNOWN;
2219 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2220 while (s < strend) {
2221 WB_enum after = getWB_VAL_CP((U8) *s);
2222 if (to_complement ^ isWB(previous,
2225 (U8*) reginfo->strbeg,
2227 (U8*) reginfo->strend,
2230 if (reginfo->intuit || regtry(reginfo, &s)) {
2240 if (to_complement ^ cBOOL(reginfo->intuit
2241 || regtry(reginfo, &s)))
2251 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2252 is_LNBREAK_latin1_safe(s, strend)
2256 /* The argument to all the POSIX node types is the class number to pass to
2257 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2264 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2265 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2266 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2281 /* The complement of something that matches only ASCII matches all
2282 * non-ASCII, plus everything in ASCII that isn't in the class. */
2283 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2284 || ! _generic_isCC_A(*s, FLAGS(c)));
2293 /* Don't need to worry about utf8, as it can match only a single
2294 * byte invariant character. */
2295 REXEC_FBC_CLASS_SCAN(
2296 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2304 if (! utf8_target) {
2305 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2311 classnum = (_char_class_number) FLAGS(c);
2312 if (classnum < _FIRST_NON_SWASH_CC) {
2313 while (s < strend) {
2315 /* We avoid loading in the swash as long as possible, but
2316 * should we have to, we jump to a separate loop. This
2317 * extra 'if' statement is what keeps this code from being
2318 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2319 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2320 goto found_above_latin1;
2322 if ((UTF8_IS_INVARIANT(*s)
2323 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2325 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2326 && to_complement ^ cBOOL(
2327 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2331 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2343 else switch (classnum) { /* These classes are implemented as
2345 case _CC_ENUM_SPACE:
2346 REXEC_FBC_UTF8_CLASS_SCAN(
2347 to_complement ^ cBOOL(isSPACE_utf8(s)));
2350 case _CC_ENUM_BLANK:
2351 REXEC_FBC_UTF8_CLASS_SCAN(
2352 to_complement ^ cBOOL(isBLANK_utf8(s)));
2355 case _CC_ENUM_XDIGIT:
2356 REXEC_FBC_UTF8_CLASS_SCAN(
2357 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2360 case _CC_ENUM_VERTSPACE:
2361 REXEC_FBC_UTF8_CLASS_SCAN(
2362 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2365 case _CC_ENUM_CNTRL:
2366 REXEC_FBC_UTF8_CLASS_SCAN(
2367 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2371 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2372 NOT_REACHED; /* NOTREACHED */
2377 found_above_latin1: /* Here we have to load a swash to get the result
2378 for the current code point */
2379 if (! PL_utf8_swash_ptrs[classnum]) {
2380 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2381 PL_utf8_swash_ptrs[classnum] =
2382 _core_swash_init("utf8",
2385 PL_XPosix_ptrs[classnum], &flags);
2388 /* This is a copy of the loop above for swash classes, though using the
2389 * FBC macro instead of being expanded out. Since we've loaded the
2390 * swash, we don't have to check for that each time through the loop */
2391 REXEC_FBC_UTF8_CLASS_SCAN(
2392 to_complement ^ cBOOL(_generic_utf8(
2395 swash_fetch(PL_utf8_swash_ptrs[classnum],
2403 /* what trie are we using right now */
2404 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2405 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2406 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2408 const char *last_start = strend - trie->minlen;
2410 const char *real_start = s;
2412 STRLEN maxlen = trie->maxlen;
2414 U8 **points; /* map of where we were in the input string
2415 when reading a given char. For ASCII this
2416 is unnecessary overhead as the relationship
2417 is always 1:1, but for Unicode, especially
2418 case folded Unicode this is not true. */
2419 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2423 GET_RE_DEBUG_FLAGS_DECL;
2425 /* We can't just allocate points here. We need to wrap it in
2426 * an SV so it gets freed properly if there is a croak while
2427 * running the match */
2430 sv_points=newSV(maxlen * sizeof(U8 *));
2431 SvCUR_set(sv_points,
2432 maxlen * sizeof(U8 *));
2433 SvPOK_on(sv_points);
2434 sv_2mortal(sv_points);
2435 points=(U8**)SvPV_nolen(sv_points );
2436 if ( trie_type != trie_utf8_fold
2437 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2440 bitmap=(U8*)trie->bitmap;
2442 bitmap=(U8*)ANYOF_BITMAP(c);
2444 /* this is the Aho-Corasick algorithm modified a touch
2445 to include special handling for long "unknown char" sequences.
2446 The basic idea being that we use AC as long as we are dealing
2447 with a possible matching char, when we encounter an unknown char
2448 (and we have not encountered an accepting state) we scan forward
2449 until we find a legal starting char.
2450 AC matching is basically that of trie matching, except that when
2451 we encounter a failing transition, we fall back to the current
2452 states "fail state", and try the current char again, a process
2453 we repeat until we reach the root state, state 1, or a legal
2454 transition. If we fail on the root state then we can either
2455 terminate if we have reached an accepting state previously, or
2456 restart the entire process from the beginning if we have not.
2459 while (s <= last_start) {
2460 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2468 U8 *uscan = (U8*)NULL;
2469 U8 *leftmost = NULL;
2471 U32 accepted_word= 0;
2475 while ( state && uc <= (U8*)strend ) {
2477 U32 word = aho->states[ state ].wordnum;
2481 DEBUG_TRIE_EXECUTE_r(
2482 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2483 dump_exec_pos( (char *)uc, c, strend, real_start,
2484 (char *)uc, utf8_target );
2485 PerlIO_printf( Perl_debug_log,
2486 " Scanning for legal start char...\n");
2490 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2494 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2500 if (uc >(U8*)last_start) break;
2504 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2505 if (!leftmost || lpos < leftmost) {
2506 DEBUG_r(accepted_word=word);
2512 points[pointpos++ % maxlen]= uc;
2513 if (foldlen || uc < (U8*)strend) {
2514 REXEC_TRIE_READ_CHAR(trie_type, trie,
2516 uscan, len, uvc, charid, foldlen,
2518 DEBUG_TRIE_EXECUTE_r({
2519 dump_exec_pos( (char *)uc, c, strend,
2520 real_start, s, utf8_target);
2521 PerlIO_printf(Perl_debug_log,
2522 " Charid:%3u CP:%4"UVxf" ",
2534 word = aho->states[ state ].wordnum;
2536 base = aho->states[ state ].trans.base;
2538 DEBUG_TRIE_EXECUTE_r({
2540 dump_exec_pos( (char *)uc, c, strend, real_start,
2542 PerlIO_printf( Perl_debug_log,
2543 "%sState: %4"UVxf", word=%"UVxf,
2544 failed ? " Fail transition to " : "",
2545 (UV)state, (UV)word);
2551 ( ((offset = base + charid
2552 - 1 - trie->uniquecharcount)) >= 0)
2553 && ((U32)offset < trie->lasttrans)
2554 && trie->trans[offset].check == state
2555 && (tmp=trie->trans[offset].next))
2557 DEBUG_TRIE_EXECUTE_r(
2558 PerlIO_printf( Perl_debug_log," - legal\n"));
2563 DEBUG_TRIE_EXECUTE_r(
2564 PerlIO_printf( Perl_debug_log," - fail\n"));
2566 state = aho->fail[state];
2570 /* we must be accepting here */
2571 DEBUG_TRIE_EXECUTE_r(
2572 PerlIO_printf( Perl_debug_log," - accepting\n"));
2581 if (!state) state = 1;
2584 if ( aho->states[ state ].wordnum ) {
2585 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2586 if (!leftmost || lpos < leftmost) {
2587 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2592 s = (char*)leftmost;
2593 DEBUG_TRIE_EXECUTE_r({
2595 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2596 (UV)accepted_word, (IV)(s - real_start)
2599 if (reginfo->intuit || regtry(reginfo, &s)) {
2605 DEBUG_TRIE_EXECUTE_r({
2606 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2609 DEBUG_TRIE_EXECUTE_r(
2610 PerlIO_printf( Perl_debug_log,"No match.\n"));
2619 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2626 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2627 * flags have same meanings as with regexec_flags() */
2630 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2637 struct regexp *const prog = ReANY(rx);
2639 if (flags & REXEC_COPY_STR) {
2643 PerlIO_printf(Perl_debug_log,
2644 "Copy on write: regexp capture, type %d\n",
2647 /* Create a new COW SV to share the match string and store
2648 * in saved_copy, unless the current COW SV in saved_copy
2649 * is valid and suitable for our purpose */
2650 if (( prog->saved_copy
2651 && SvIsCOW(prog->saved_copy)
2652 && SvPOKp(prog->saved_copy)
2655 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2657 /* just reuse saved_copy SV */
2658 if (RXp_MATCH_COPIED(prog)) {
2659 Safefree(prog->subbeg);
2660 RXp_MATCH_COPIED_off(prog);
2664 /* create new COW SV to share string */
2665 RX_MATCH_COPY_FREE(rx);
2666 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2668 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2669 assert (SvPOKp(prog->saved_copy));
2670 prog->sublen = strend - strbeg;
2671 prog->suboffset = 0;
2672 prog->subcoffset = 0;
2677 SSize_t max = strend - strbeg;
2680 if ( (flags & REXEC_COPY_SKIP_POST)
2681 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2682 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2683 ) { /* don't copy $' part of string */
2686 /* calculate the right-most part of the string covered
2687 * by a capture. Due to look-ahead, this may be to
2688 * the right of $&, so we have to scan all captures */
2689 while (n <= prog->lastparen) {
2690 if (prog->offs[n].end > max)
2691 max = prog->offs[n].end;
2695 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2696 ? prog->offs[0].start
2698 assert(max >= 0 && max <= strend - strbeg);
2701 if ( (flags & REXEC_COPY_SKIP_PRE)
2702 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2703 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2704 ) { /* don't copy $` part of string */
2707 /* calculate the left-most part of the string covered
2708 * by a capture. Due to look-behind, this may be to
2709 * the left of $&, so we have to scan all captures */
2710 while (min && n <= prog->lastparen) {
2711 if ( prog->offs[n].start != -1
2712 && prog->offs[n].start < min)
2714 min = prog->offs[n].start;
2718 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2719 && min > prog->offs[0].end
2721 min = prog->offs[0].end;
2725 assert(min >= 0 && min <= max && min <= strend - strbeg);
2728 if (RX_MATCH_COPIED(rx)) {
2729 if (sublen > prog->sublen)
2731 (char*)saferealloc(prog->subbeg, sublen+1);
2734 prog->subbeg = (char*)safemalloc(sublen+1);
2735 Copy(strbeg + min, prog->subbeg, sublen, char);
2736 prog->subbeg[sublen] = '\0';
2737 prog->suboffset = min;
2738 prog->sublen = sublen;
2739 RX_MATCH_COPIED_on(rx);
2741 prog->subcoffset = prog->suboffset;
2742 if (prog->suboffset && utf8_target) {
2743 /* Convert byte offset to chars.
2744 * XXX ideally should only compute this if @-/@+
2745 * has been seen, a la PL_sawampersand ??? */
2747 /* If there's a direct correspondence between the
2748 * string which we're matching and the original SV,
2749 * then we can use the utf8 len cache associated with
2750 * the SV. In particular, it means that under //g,
2751 * sv_pos_b2u() will use the previously cached
2752 * position to speed up working out the new length of
2753 * subcoffset, rather than counting from the start of
2754 * the string each time. This stops
2755 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2756 * from going quadratic */
2757 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2758 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2759 SV_GMAGIC|SV_CONST_RETURN);
2761 prog->subcoffset = utf8_length((U8*)strbeg,
2762 (U8*)(strbeg+prog->suboffset));
2766 RX_MATCH_COPY_FREE(rx);
2767 prog->subbeg = strbeg;
2768 prog->suboffset = 0;
2769 prog->subcoffset = 0;
2770 prog->sublen = strend - strbeg;
2778 - regexec_flags - match a regexp against a string
2781 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2782 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2783 /* stringarg: the point in the string at which to begin matching */
2784 /* strend: pointer to null at end of string */
2785 /* strbeg: real beginning of string */
2786 /* minend: end of match must be >= minend bytes after stringarg. */
2787 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2788 * itself is accessed via the pointers above */
2789 /* data: May be used for some additional optimizations.
2790 Currently unused. */
2791 /* flags: For optimizations. See REXEC_* in regexp.h */
2794 struct regexp *const prog = ReANY(rx);
2798 SSize_t minlen; /* must match at least this many chars */
2799 SSize_t dontbother = 0; /* how many characters not to try at end */
2800 const bool utf8_target = cBOOL(DO_UTF8(sv));
2802 RXi_GET_DECL(prog,progi);
2803 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2804 regmatch_info *const reginfo = ®info_buf;
2805 regexp_paren_pair *swap = NULL;
2807 GET_RE_DEBUG_FLAGS_DECL;
2809 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2810 PERL_UNUSED_ARG(data);
2812 /* Be paranoid... */
2814 Perl_croak(aTHX_ "NULL regexp parameter");
2818 debug_start_match(rx, utf8_target, stringarg, strend,
2822 startpos = stringarg;
2824 if (prog->intflags & PREGf_GPOS_SEEN) {
2827 /* set reginfo->ganch, the position where \G can match */
2830 (flags & REXEC_IGNOREPOS)
2831 ? stringarg /* use start pos rather than pos() */
2832 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2833 /* Defined pos(): */
2834 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2835 : strbeg; /* pos() not defined; use start of string */
2837 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2838 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2840 /* in the presence of \G, we may need to start looking earlier in
2841 * the string than the suggested start point of stringarg:
2842 * if prog->gofs is set, then that's a known, fixed minimum
2845 * /ab|c\G/: gofs = 1
2846 * or if the minimum offset isn't known, then we have to go back
2847 * to the start of the string, e.g. /w+\G/
2850 if (prog->intflags & PREGf_ANCH_GPOS) {
2851 startpos = reginfo->ganch - prog->gofs;
2853 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2855 DEBUG_r(PerlIO_printf(Perl_debug_log,
2856 "fail: ganch-gofs before earliest possible start\n"));
2860 else if (prog->gofs) {
2861 if (startpos - prog->gofs < strbeg)
2864 startpos -= prog->gofs;
2866 else if (prog->intflags & PREGf_GPOS_FLOAT)
2870 minlen = prog->minlen;
2871 if ((startpos + minlen) > strend || startpos < strbeg) {
2872 DEBUG_r(PerlIO_printf(Perl_debug_log,
2873 "Regex match can't succeed, so not even tried\n"));
2877 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2878 * which will call destuctors to reset PL_regmatch_state, free higher
2879 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2880 * regmatch_info_aux_eval */
2882 oldsave = PL_savestack_ix;
2886 if ((prog->extflags & RXf_USE_INTUIT)
2887 && !(flags & REXEC_CHECKED))
2889 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2894 if (prog->extflags & RXf_CHECK_ALL) {
2895 /* we can match based purely on the result of INTUIT.
2896 * Set up captures etc just for $& and $-[0]
2897 * (an intuit-only match wont have $1,$2,..) */
2898 assert(!prog->nparens);
2900 /* s/// doesn't like it if $& is earlier than where we asked it to
2901 * start searching (which can happen on something like /.\G/) */
2902 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2905 /* this should only be possible under \G */
2906 assert(prog->intflags & PREGf_GPOS_SEEN);
2907 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2908 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2912 /* match via INTUIT shouldn't have any captures.
2913 * Let @-, @+, $^N know */
2914 prog->lastparen = prog->lastcloseparen = 0;
2915 RX_MATCH_UTF8_set(rx, utf8_target);
2916 prog->offs[0].start = s - strbeg;
2917 prog->offs[0].end = utf8_target
2918 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2919 : s - strbeg + prog->minlenret;
2920 if ( !(flags & REXEC_NOT_FIRST) )
2921 S_reg_set_capture_string(aTHX_ rx,
2923 sv, flags, utf8_target);
2929 multiline = prog->extflags & RXf_PMf_MULTILINE;
2931 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2932 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2933 "String too short [regexec_flags]...\n"));
2937 /* Check validity of program. */
2938 if (UCHARAT(progi->program) != REG_MAGIC) {
2939 Perl_croak(aTHX_ "corrupted regexp program");
2942 RX_MATCH_TAINTED_off(rx);
2943 RX_MATCH_UTF8_set(rx, utf8_target);
2945 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2946 reginfo->intuit = 0;
2947 reginfo->is_utf8_target = cBOOL(utf8_target);
2948 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2949 reginfo->warned = FALSE;
2950 reginfo->strbeg = strbeg;
2952 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2953 reginfo->strend = strend;
2954 /* see how far we have to get to not match where we matched before */
2955 reginfo->till = stringarg + minend;
2957 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2958 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2959 S_cleanup_regmatch_info_aux has executed (registered by
2960 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2961 magic belonging to this SV.
2962 Not newSVsv, either, as it does not COW.
2964 reginfo->sv = newSV(0);
2965 SvSetSV_nosteal(reginfo->sv, sv);
2966 SAVEFREESV(reginfo->sv);
2969 /* reserve next 2 or 3 slots in PL_regmatch_state:
2970 * slot N+0: may currently be in use: skip it
2971 * slot N+1: use for regmatch_info_aux struct
2972 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2973 * slot N+3: ready for use by regmatch()
2977 regmatch_state *old_regmatch_state;
2978 regmatch_slab *old_regmatch_slab;
2979 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2981 /* on first ever match, allocate first slab */
2982 if (!PL_regmatch_slab) {
2983 Newx(PL_regmatch_slab, 1, regmatch_slab);
2984 PL_regmatch_slab->prev = NULL;
2985 PL_regmatch_slab->next = NULL;
2986 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2989 old_regmatch_state = PL_regmatch_state;
2990 old_regmatch_slab = PL_regmatch_slab;
2992 for (i=0; i <= max; i++) {
2994 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2996 reginfo->info_aux_eval =
2997 reginfo->info_aux->info_aux_eval =
2998 &(PL_regmatch_state->u.info_aux_eval);
3000 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3001 PL_regmatch_state = S_push_slab(aTHX);
3004 /* note initial PL_regmatch_state position; at end of match we'll
3005 * pop back to there and free any higher slabs */
3007 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3008 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3009 reginfo->info_aux->poscache = NULL;
3011 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3013 if ((prog->extflags & RXf_EVAL_SEEN))
3014 S_setup_eval_state(aTHX_ reginfo);
3016 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3019 /* If there is a "must appear" string, look for it. */
3021 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3022 /* We have to be careful. If the previous successful match
3023 was from this regex we don't want a subsequent partially
3024 successful match to clobber the old results.
3025 So when we detect this possibility we add a swap buffer
3026 to the re, and switch the buffer each match. If we fail,
3027 we switch it back; otherwise we leave it swapped.
3030 /* do we need a save destructor here for eval dies? */
3031 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3032 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3033 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3040 /* Simplest case: anchored match need be tried only once, or with
3041 * MBOL, only at the beginning of each line.
3043 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3044 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3045 * match at the start of the string then it won't match anywhere else
3046 * either; while with /.*.../, if it doesn't match at the beginning,
3047 * the earliest it could match is at the start of the next line */
3049 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3052 if (regtry(reginfo, &s))
3055 if (!(prog->intflags & PREGf_ANCH_MBOL))
3058 /* didn't match at start, try at other newline positions */
3061 dontbother = minlen - 1;
3062 end = HOP3c(strend, -dontbother, strbeg) - 1;
3064 /* skip to next newline */
3066 while (s <= end) { /* note it could be possible to match at the end of the string */
3067 /* NB: newlines are the same in unicode as they are in latin */
3070 if (prog->check_substr || prog->check_utf8) {
3071 /* note that with PREGf_IMPLICIT, intuit can only fail
3072 * or return the start position, so it's of limited utility.
3073 * Nevertheless, I made the decision that the potential for
3074 * quick fail was still worth it - DAPM */
3075 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3079 if (regtry(reginfo, &s))
3083 } /* end anchored search */
3085 if (prog->intflags & PREGf_ANCH_GPOS)
3087 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3088 assert(prog->intflags & PREGf_GPOS_SEEN);
3089 /* For anchored \G, the only position it can match from is
3090 * (ganch-gofs); we already set startpos to this above; if intuit
3091 * moved us on from there, we can't possibly succeed */
3092 assert(startpos == reginfo->ganch - prog->gofs);
3093 if (s == startpos && regtry(reginfo, &s))
3098 /* Messy cases: unanchored match. */
3099 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3100 /* we have /x+whatever/ */
3101 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3107 if (! prog->anchored_utf8) {
3108 to_utf8_substr(prog);
3110 ch = SvPVX_const(prog->anchored_utf8)[0];
3113 DEBUG_EXECUTE_r( did_match = 1 );
3114 if (regtry(reginfo, &s)) goto got_it;
3116 while (s < strend && *s == ch)
3123 if (! prog->anchored_substr) {
3124 if (! to_byte_substr(prog)) {
3125 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3128 ch = SvPVX_const(prog->anchored_substr)[0];
3131 DEBUG_EXECUTE_r( did_match = 1 );
3132 if (regtry(reginfo, &s)) goto got_it;
3134 while (s < strend && *s == ch)
3139 DEBUG_EXECUTE_r(if (!did_match)
3140 PerlIO_printf(Perl_debug_log,
3141 "Did not find anchored character...\n")
3144 else if (prog->anchored_substr != NULL
3145 || prog->anchored_utf8 != NULL
3146 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3147 && prog->float_max_offset < strend - s)) {
3152 char *last1; /* Last position checked before */
3156 if (prog->anchored_substr || prog->anchored_utf8) {
3158 if (! prog->anchored_utf8) {
3159 to_utf8_substr(prog);
3161 must = prog->anchored_utf8;
3164 if (! prog->anchored_substr) {
3165 if (! to_byte_substr(prog)) {
3166 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3169 must = prog->anchored_substr;
3171 back_max = back_min = prog->anchored_offset;
3174 if (! prog->float_utf8) {
3175 to_utf8_substr(prog);
3177 must = prog->float_utf8;
3180 if (! prog->float_substr) {
3181 if (! to_byte_substr(prog)) {
3182 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3185 must = prog->float_substr;
3187 back_max = prog->float_max_offset;
3188 back_min = prog->float_min_offset;
3194 last = HOP3c(strend, /* Cannot start after this */
3195 -(SSize_t)(CHR_SVLEN(must)
3196 - (SvTAIL(must) != 0) + back_min), strbeg);
3198 if (s > reginfo->strbeg)
3199 last1 = HOPc(s, -1);
3201 last1 = s - 1; /* bogus */
3203 /* XXXX check_substr already used to find "s", can optimize if
3204 check_substr==must. */
3206 strend = HOPc(strend, -dontbother);
3207 while ( (s <= last) &&
3208 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3209 (unsigned char*)strend, must,
3210 multiline ? FBMrf_MULTILINE : 0)) ) {
3211 DEBUG_EXECUTE_r( did_match = 1 );
3212 if (HOPc(s, -back_max) > last1) {
3213 last1 = HOPc(s, -back_min);
3214 s = HOPc(s, -back_max);
3217 char * const t = (last1 >= reginfo->strbeg)
3218 ? HOPc(last1, 1) : last1 + 1;
3220 last1 = HOPc(s, -back_min);
3224 while (s <= last1) {
3225 if (regtry(reginfo, &s))
3228 s++; /* to break out of outer loop */
3235 while (s <= last1) {
3236 if (regtry(reginfo, &s))
3242 DEBUG_EXECUTE_r(if (!did_match) {
3243 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3244 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3245 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3246 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3247 ? "anchored" : "floating"),
3248 quoted, RE_SV_TAIL(must));
3252 else if ( (c = progi->regstclass) ) {
3254 const OPCODE op = OP(progi->regstclass);
3255 /* don't bother with what can't match */
3256 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3257 strend = HOPc(strend, -(minlen - 1));
3260 SV * const prop = sv_newmortal();
3261 regprop(prog, prop, c, reginfo, NULL);
3263 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3265 PerlIO_printf(Perl_debug_log,
3266 "Matching stclass %.*s against %s (%d bytes)\n",
3267 (int)SvCUR(prop), SvPVX_const(prop),
3268 quoted, (int)(strend - s));
3271 if (find_byclass(prog, c, s, strend, reginfo))
3273 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3277 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3285 if (! prog->float_utf8) {
3286 to_utf8_substr(prog);
3288 float_real = prog->float_utf8;
3291 if (! prog->float_substr) {
3292 if (! to_byte_substr(prog)) {
3293 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3296 float_real = prog->float_substr;
3299 little = SvPV_const(float_real, len);
3300 if (SvTAIL(float_real)) {
3301 /* This means that float_real contains an artificial \n on
3302 * the end due to the presence of something like this:
3303 * /foo$/ where we can match both "foo" and "foo\n" at the
3304 * end of the string. So we have to compare the end of the
3305 * string first against the float_real without the \n and
3306 * then against the full float_real with the string. We
3307 * have to watch out for cases where the string might be
3308 * smaller than the float_real or the float_real without
3310 char *checkpos= strend - len;
3312 PerlIO_printf(Perl_debug_log,
3313 "%sChecking for float_real.%s\n",
3314 PL_colors[4], PL_colors[5]));
3315 if (checkpos + 1 < strbeg) {
3316 /* can't match, even if we remove the trailing \n
3317 * string is too short to match */
3319 PerlIO_printf(Perl_debug_log,
3320 "%sString shorter than required trailing substring, cannot match.%s\n",
3321 PL_colors[4], PL_colors[5]));
3323 } else if (memEQ(checkpos + 1, little, len - 1)) {
3324 /* can match, the end of the string matches without the
3326 last = checkpos + 1;
3327 } else if (checkpos < strbeg) {
3328 /* cant match, string is too short when the "\n" is
3331 PerlIO_printf(Perl_debug_log,
3332 "%sString does not contain required trailing substring, cannot match.%s\n",
3333 PL_colors[4], PL_colors[5]));
3335 } else if (!multiline) {
3336 /* non multiline match, so compare with the "\n" at the
3337 * end of the string */
3338 if (memEQ(checkpos, little, len)) {
3342 PerlIO_printf(Perl_debug_log,
3343 "%sString does not contain required trailing substring, cannot match.%s\n",
3344 PL_colors[4], PL_colors[5]));
3348 /* multiline match, so we have to search for a place
3349 * where the full string is located */
3355 last = rninstr(s, strend, little, little + len);
3357 last = strend; /* matching "$" */
3360 /* at one point this block contained a comment which was
3361 * probably incorrect, which said that this was a "should not
3362 * happen" case. Even if it was true when it was written I am
3363 * pretty sure it is not anymore, so I have removed the comment
3364 * and replaced it with this one. Yves */
3366 PerlIO_printf(Perl_debug_log,
3367 "%sString does not contain required substring, cannot match.%s\n",
3368 PL_colors[4], PL_colors[5]
3372 dontbother = strend - last + prog->float_min_offset;
3374 if (minlen && (dontbother < minlen))
3375 dontbother = minlen - 1;
3376 strend -= dontbother; /* this one's always in bytes! */
3377 /* We don't know much -- general case. */
3380 if (regtry(reginfo, &s))
3389 if (regtry(reginfo, &s))
3391 } while (s++ < strend);
3399 /* s/// doesn't like it if $& is earlier than where we asked it to
3400 * start searching (which can happen on something like /.\G/) */
3401 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3402 && (prog->offs[0].start < stringarg - strbeg))
3404 /* this should only be possible under \G */
3405 assert(prog->intflags & PREGf_GPOS_SEEN);
3406 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3407 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3413 PerlIO_printf(Perl_debug_log,
3414 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3421 /* clean up; this will trigger destructors that will free all slabs
3422 * above the current one, and cleanup the regmatch_info_aux
3423 * and regmatch_info_aux_eval sructs */
3425 LEAVE_SCOPE(oldsave);
3427 if (RXp_PAREN_NAMES(prog))
3428 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3430 /* make sure $`, $&, $', and $digit will work later */
3431 if ( !(flags & REXEC_NOT_FIRST) )
3432 S_reg_set_capture_string(aTHX_ rx,
3433 strbeg, reginfo->strend,
3434 sv, flags, utf8_target);
3439 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3440 PL_colors[4], PL_colors[5]));
3442 /* clean up; this will trigger destructors that will free all slabs
3443 * above the current one, and cleanup the regmatch_info_aux
3444 * and regmatch_info_aux_eval sructs */
3446 LEAVE_SCOPE(oldsave);
3449 /* we failed :-( roll it back */
3450 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3451 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3456 Safefree(prog->offs);
3463 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3464 * Do inc before dec, in case old and new rex are the same */
3465 #define SET_reg_curpm(Re2) \
3466 if (reginfo->info_aux_eval) { \
3467 (void)ReREFCNT_inc(Re2); \
3468 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3469 PM_SETRE((PL_reg_curpm), (Re2)); \
3474 - regtry - try match at specific point
3476 STATIC I32 /* 0 failure, 1 success */
3477 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3480 REGEXP *const rx = reginfo->prog;
3481 regexp *const prog = ReANY(rx);
3483 RXi_GET_DECL(prog,progi);
3484 GET_RE_DEBUG_FLAGS_DECL;
3486 PERL_ARGS_ASSERT_REGTRY;
3488 reginfo->cutpoint=NULL;
3490 prog->offs[0].start = *startposp - reginfo->strbeg;
3491 prog->lastparen = 0;
3492 prog->lastcloseparen = 0;
3494 /* XXXX What this code is doing here?!!! There should be no need
3495 to do this again and again, prog->lastparen should take care of
3498 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3499 * Actually, the code in regcppop() (which Ilya may be meaning by
3500 * prog->lastparen), is not needed at all by the test suite
3501 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3502 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3503 * Meanwhile, this code *is* needed for the
3504 * above-mentioned test suite tests to succeed. The common theme
3505 * on those tests seems to be returning null fields from matches.
3506 * --jhi updated by dapm */
3508 if (prog->nparens) {
3509 regexp_paren_pair *pp = prog->offs;
3511 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3519 result = regmatch(reginfo, *startposp, progi->program + 1);
3521 prog->offs[0].end = result;
3524 if (reginfo->cutpoint)
3525 *startposp= reginfo->cutpoint;
3526 REGCP_UNWIND(lastcp);
3531 #define sayYES goto yes
3532 #define sayNO goto no
3533 #define sayNO_SILENT goto no_silent
3535 /* we dont use STMT_START/END here because it leads to
3536 "unreachable code" warnings, which are bogus, but distracting. */
3537 #define CACHEsayNO \
3538 if (ST.cache_mask) \
3539 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3542 /* this is used to determine how far from the left messages like
3543 'failed...' are printed. It should be set such that messages
3544 are inline with the regop output that created them.
3546 #define REPORT_CODE_OFF 32
3549 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3550 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3551 #define CHRTEST_NOT_A_CP_1 -999
3552 #define CHRTEST_NOT_A_CP_2 -998
3554 /* grab a new slab and return the first slot in it */
3556 STATIC regmatch_state *
3559 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3562 regmatch_slab *s = PL_regmatch_slab->next;
3564 Newx(s, 1, regmatch_slab);
3565 s->prev = PL_regmatch_slab;
3567 PL_regmatch_slab->next = s;
3569 PL_regmatch_slab = s;
3570 return SLAB_FIRST(s);
3574 /* push a new state then goto it */
3576 #define PUSH_STATE_GOTO(state, node, input) \
3577 pushinput = input; \
3579 st->resume_state = state; \
3582 /* push a new state with success backtracking, then goto it */
3584 #define PUSH_YES_STATE_GOTO(state, node, input) \
3585 pushinput = input; \
3587 st->resume_state = state; \
3588 goto push_yes_state;
3595 regmatch() - main matching routine
3597 This is basically one big switch statement in a loop. We execute an op,
3598 set 'next' to point the next op, and continue. If we come to a point which
3599 we may need to backtrack to on failure such as (A|B|C), we push a
3600 backtrack state onto the backtrack stack. On failure, we pop the top
3601 state, and re-enter the loop at the state indicated. If there are no more
3602 states to pop, we return failure.
3604 Sometimes we also need to backtrack on success; for example /A+/, where
3605 after successfully matching one A, we need to go back and try to
3606 match another one; similarly for lookahead assertions: if the assertion
3607 completes successfully, we backtrack to the state just before the assertion
3608 and then carry on. In these cases, the pushed state is marked as
3609 'backtrack on success too'. This marking is in fact done by a chain of
3610 pointers, each pointing to the previous 'yes' state. On success, we pop to
3611 the nearest yes state, discarding any intermediate failure-only states.
3612 Sometimes a yes state is pushed just to force some cleanup code to be
3613 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3614 it to free the inner regex.
3616 Note that failure backtracking rewinds the cursor position, while
3617 success backtracking leaves it alone.
3619 A pattern is complete when the END op is executed, while a subpattern
3620 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3621 ops trigger the "pop to last yes state if any, otherwise return true"
3624 A common convention in this function is to use A and B to refer to the two
3625 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3626 the subpattern to be matched possibly multiple times, while B is the entire
3627 rest of the pattern. Variable and state names reflect this convention.
3629 The states in the main switch are the union of ops and failure/success of
3630 substates associated with with that op. For example, IFMATCH is the op
3631 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3632 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3633 successfully matched A and IFMATCH_A_fail is a state saying that we have
3634 just failed to match A. Resume states always come in pairs. The backtrack
3635 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3636 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3637 on success or failure.
3639 The struct that holds a backtracking state is actually a big union, with
3640 one variant for each major type of op. The variable st points to the
3641 top-most backtrack struct. To make the code clearer, within each
3642 block of code we #define ST to alias the relevant union.
3644 Here's a concrete example of a (vastly oversimplified) IFMATCH
3650 #define ST st->u.ifmatch
3652 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3653 ST.foo = ...; // some state we wish to save
3655 // push a yes backtrack state with a resume value of
3656 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3658 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3661 case IFMATCH_A: // we have successfully executed A; now continue with B
3663 bar = ST.foo; // do something with the preserved value
3666 case IFMATCH_A_fail: // A failed, so the assertion failed
3667 ...; // do some housekeeping, then ...
3668 sayNO; // propagate the failure
3675 For any old-timers reading this who are familiar with the old recursive
3676 approach, the code above is equivalent to:
3678 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3687 ...; // do some housekeeping, then ...
3688 sayNO; // propagate the failure
3691 The topmost backtrack state, pointed to by st, is usually free. If you
3692 want to claim it, populate any ST.foo fields in it with values you wish to
3693 save, then do one of
3695 PUSH_STATE_GOTO(resume_state, node, newinput);
3696 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3698 which sets that backtrack state's resume value to 'resume_state', pushes a
3699 new free entry to the top of the backtrack stack, then goes to 'node'.
3700 On backtracking, the free slot is popped, and the saved state becomes the
3701 new free state. An ST.foo field in this new top state can be temporarily
3702 accessed to retrieve values, but once the main loop is re-entered, it
3703 becomes available for reuse.
3705 Note that the depth of the backtrack stack constantly increases during the
3706 left-to-right execution of the pattern, rather than going up and down with
3707 the pattern nesting. For example the stack is at its maximum at Z at the
3708 end of the pattern, rather than at X in the following:
3710 /(((X)+)+)+....(Y)+....Z/
3712 The only exceptions to this are lookahead/behind assertions and the cut,
3713 (?>A), which pop all the backtrack states associated with A before
3716 Backtrack state structs are allocated in slabs of about 4K in size.
3717 PL_regmatch_state and st always point to the currently active state,
3718 and PL_regmatch_slab points to the slab currently containing
3719 PL_regmatch_state. The first time regmatch() is called, the first slab is
3720 allocated, and is never freed until interpreter destruction. When the slab
3721 is full, a new one is allocated and chained to the end. At exit from
3722 regmatch(), slabs allocated since entry are freed.
3727 #define DEBUG_STATE_pp(pp) \
3729 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3730 PerlIO_printf(Perl_debug_log, \
3731 " %*s"pp" %s%s%s%s%s\n", \
3733 PL_reg_name[st->resume_state], \
3734 ((st==yes_state||st==mark_state) ? "[" : ""), \
3735 ((st==yes_state) ? "Y" : ""), \
3736 ((st==mark_state) ? "M" : ""), \
3737 ((st==yes_state||st==mark_state) ? "]" : "") \
3742 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3747 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3748 const char *start, const char *end, const char *blurb)
3750 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3752 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3757 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3758 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3760 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3761 start, end - start, 60);
3763 PerlIO_printf(Perl_debug_log,
3764 "%s%s REx%s %s against %s\n",
3765 PL_colors[4], blurb, PL_colors[5], s0, s1);
3767 if (utf8_target||utf8_pat)
3768 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3769 utf8_pat ? "pattern" : "",
3770 utf8_pat && utf8_target ? " and " : "",
3771 utf8_target ? "string" : ""
3777 S_dump_exec_pos(pTHX_ const char *locinput,
3778 const regnode *scan,
3779 const char *loc_regeol,
3780 const char *loc_bostr,
3781 const char *loc_reg_starttry,
3782 const bool utf8_target)
3784 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3785 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3786 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3787 /* The part of the string before starttry has one color
3788 (pref0_len chars), between starttry and current
3789 position another one (pref_len - pref0_len chars),
3790 after the current position the third one.
3791 We assume that pref0_len <= pref_len, otherwise we
3792 decrease pref0_len. */
3793 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3794 ? (5 + taill) - l : locinput - loc_bostr;
3797 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3799 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3801 pref0_len = pref_len - (locinput - loc_reg_starttry);
3802 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3803 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3804 ? (5 + taill) - pref_len : loc_regeol - locinput);
3805 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3809 if (pref0_len > pref_len)
3810 pref0_len = pref_len;
3812 const int is_uni = utf8_target ? 1 : 0;
3814 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3815 (locinput - pref_len),pref0_len, 60, 4, 5);
3817 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3818 (locinput - pref_len + pref0_len),
3819 pref_len - pref0_len, 60, 2, 3);
3821 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3822 locinput, loc_regeol - locinput, 10, 0, 1);
3824 const STRLEN tlen=len0+len1+len2;
3825 PerlIO_printf(Perl_debug_log,
3826 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3827 (IV)(locinput - loc_bostr),
3830 (docolor ? "" : "> <"),
3832 (int)(tlen > 19 ? 0 : 19 - tlen),
3839 /* reg_check_named_buff_matched()
3840 * Checks to see if a named buffer has matched. The data array of
3841 * buffer numbers corresponding to the buffer is expected to reside
3842 * in the regexp->data->data array in the slot stored in the ARG() of
3843 * node involved. Note that this routine doesn't actually care about the
3844 * name, that information is not preserved from compilation to execution.
3845 * Returns the index of the leftmost defined buffer with the given name
3846 * or 0 if non of the buffers matched.
3849 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3852 RXi_GET_DECL(rex,rexi);
3853 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3854 I32 *nums=(I32*)SvPVX(sv_dat);
3856 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3858 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3859 if ((I32)rex->lastparen >= nums[n] &&
3860 rex->offs[nums[n]].end != -1)
3870 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3871 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3873 /* This function determines if there are one or two characters that match
3874 * the first character of the passed-in EXACTish node <text_node>, and if
3875 * so, returns them in the passed-in pointers.
3877 * If it determines that no possible character in the target string can
3878 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3879 * the first character in <text_node> requires UTF-8 to represent, and the
3880 * target string isn't in UTF-8.)
3882 * If there are more than two characters that could match the beginning of
3883 * <text_node>, or if more context is required to determine a match or not,
3884 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3886 * The motiviation behind this function is to allow the caller to set up
3887 * tight loops for matching. If <text_node> is of type EXACT, there is
3888 * only one possible character that can match its first character, and so
3889 * the situation is quite simple. But things get much more complicated if
3890 * folding is involved. It may be that the first character of an EXACTFish
3891 * node doesn't participate in any possible fold, e.g., punctuation, so it
3892 * can be matched only by itself. The vast majority of characters that are
3893 * in folds match just two things, their lower and upper-case equivalents.
3894 * But not all are like that; some have multiple possible matches, or match
3895 * sequences of more than one character. This function sorts all that out.
3897 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3898 * loop of trying to match A*, we know we can't exit where the thing
3899 * following it isn't a B. And something can't be a B unless it is the
3900 * beginning of B. By putting a quick test for that beginning in a tight
3901 * loop, we can rule out things that can't possibly be B without having to
3902 * break out of the loop, thus avoiding work. Similarly, if A is a single
3903 * character, we can make a tight loop matching A*, using the outputs of
3906 * If the target string to match isn't in UTF-8, and there aren't
3907 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3908 * the one or two possible octets (which are characters in this situation)
3909 * that can match. In all cases, if there is only one character that can
3910 * match, *<c1p> and *<c2p> will be identical.
3912 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3913 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3914 * can match the beginning of <text_node>. They should be declared with at
3915 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3916 * undefined what these contain.) If one or both of the buffers are
3917 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3918 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3919 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3920 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3921 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3923 const bool utf8_target = reginfo->is_utf8_target;
3925 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
3926 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
3927 bool use_chrtest_void = FALSE;
3928 const bool is_utf8_pat = reginfo->is_utf8_pat;
3930 /* Used when we have both utf8 input and utf8 output, to avoid converting
3931 * to/from code points */
3932 bool utf8_has_been_setup = FALSE;
3936 U8 *pat = (U8*)STRING(text_node);
3937 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3939 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
3941 /* In an exact node, only one thing can be matched, that first
3942 * character. If both the pat and the target are UTF-8, we can just
3943 * copy the input to the output, avoiding finding the code point of
3948 else if (utf8_target) {
3949 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3950 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3951 utf8_has_been_setup = TRUE;
3954 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3957 else { /* an EXACTFish node */
3958 U8 *pat_end = pat + STR_LEN(text_node);
3960 /* An EXACTFL node has at least some characters unfolded, because what
3961 * they match is not known until now. So, now is the time to fold
3962 * the first few of them, as many as are needed to determine 'c1' and
3963 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3964 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3965 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3966 * need to fold as many characters as a single character can fold to,
3967 * so that later we can check if the first ones are such a multi-char
3968 * fold. But, in such a pattern only locale-problematic characters
3969 * aren't folded, so we can skip this completely if the first character
3970 * in the node isn't one of the tricky ones */
3971 if (OP(text_node) == EXACTFL) {
3973 if (! is_utf8_pat) {
3974 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3976 folded[0] = folded[1] = 's';
3978 pat_end = folded + 2;
3981 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3986 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3988 *(d++) = (U8) toFOLD_LC(*s);
3993 _to_utf8_fold_flags(s,
3996 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4007 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4008 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4010 /* Multi-character folds require more context to sort out. Also
4011 * PL_utf8_foldclosures used below doesn't handle them, so have to
4012 * be handled outside this routine */
4013 use_chrtest_void = TRUE;
4015 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4016 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4018 /* Load the folds hash, if not already done */
4020 if (! PL_utf8_foldclosures) {
4021 _load_PL_utf8_foldclosures();
4024 /* The fold closures data structure is a hash with the keys
4025 * being the UTF-8 of every character that is folded to, like
4026 * 'k', and the values each an array of all code points that
4027 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4028 * Multi-character folds are not included */
4029 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4034 /* Not found in the hash, therefore there are no folds
4035 * containing it, so there is only a single character that
4039 else { /* Does participate in folds */
4040 AV* list = (AV*) *listp;
4041 if (av_tindex(list) != 1) {
4043 /* If there aren't exactly two folds to this, it is
4044 * outside the scope of this function */
4045 use_chrtest_void = TRUE;
4047 else { /* There are two. Get them */
4048 SV** c_p = av_fetch(list, 0, FALSE);
4050 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4054 c_p = av_fetch(list, 1, FALSE);
4056 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4060 /* Folds that cross the 255/256 boundary are forbidden
4061 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4062 * one is ASCIII. Since the pattern character is above
4063 * 255, and its only other match is below 256, the only
4064 * legal match will be to itself. We have thrown away
4065 * the original, so have to compute which is the one
4067 if ((c1 < 256) != (c2 < 256)) {
4068 if ((OP(text_node) == EXACTFL
4069 && ! IN_UTF8_CTYPE_LOCALE)
4070 || ((OP(text_node) == EXACTFA
4071 || OP(text_node) == EXACTFA_NO_TRIE)
4072 && (isASCII(c1) || isASCII(c2))))
4085 else /* Here, c1 is <= 255 */
4087 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4088 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4089 && ((OP(text_node) != EXACTFA
4090 && OP(text_node) != EXACTFA_NO_TRIE)
4093 /* Here, there could be something above Latin1 in the target
4094 * which folds to this character in the pattern. All such
4095 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4096 * than two characters involved in their folds, so are outside
4097 * the scope of this function */
4098 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4099 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4102 use_chrtest_void = TRUE;
4105 else { /* Here nothing above Latin1 can fold to the pattern
4107 switch (OP(text_node)) {
4109 case EXACTFL: /* /l rules */
4110 c2 = PL_fold_locale[c1];
4113 case EXACTF: /* This node only generated for non-utf8
4115 assert(! is_utf8_pat);
4116 if (! utf8_target) { /* /d rules */
4121 /* /u rules for all these. This happens to work for
4122 * EXACTFA as nothing in Latin1 folds to ASCII */
4123 case EXACTFA_NO_TRIE: /* This node only generated for
4124 non-utf8 patterns */
4125 assert(! is_utf8_pat);
4130 c2 = PL_fold_latin1[c1];
4134 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4135 NOT_REACHED; /* NOTREACHED */
4141 /* Here have figured things out. Set up the returns */
4142 if (use_chrtest_void) {
4143 *c2p = *c1p = CHRTEST_VOID;
4145 else if (utf8_target) {
4146 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4147 uvchr_to_utf8(c1_utf8, c1);
4148 uvchr_to_utf8(c2_utf8, c2);
4151 /* Invariants are stored in both the utf8 and byte outputs; Use
4152 * negative numbers otherwise for the byte ones. Make sure that the
4153 * byte ones are the same iff the utf8 ones are the same */
4154 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4155 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4158 ? CHRTEST_NOT_A_CP_1
4159 : CHRTEST_NOT_A_CP_2;
4161 else if (c1 > 255) {
4162 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4167 *c1p = *c2p = c2; /* c2 is the only representable value */
4169 else { /* c1 is representable; see about c2 */
4171 *c2p = (c2 < 256) ? c2 : c1;
4177 /* This creates a single number by combining two, with 'before' being like the
4178 * 10's digit, but this isn't necessarily base 10; it is base however many
4179 * elements of the enum there are */
4180 #define GCBcase(before, after) ((GCB_ENUM_COUNT * before) + after)
4183 S_isGCB(const GCB_enum before, const GCB_enum after)
4185 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4186 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4188 switch (GCBcase(before, after)) {
4190 /* Break at the start and end of text.
4194 Break before and after controls except between CR and LF
4195 GB4. ( Control | CR | LF ) ÷
4196 GB5. ÷ ( Control | CR | LF )
4198 Otherwise, break everywhere.
4203 /* Do not break between a CR and LF.
4205 case GCBcase(GCB_CR, GCB_LF):
4208 /* Do not break Hangul syllable sequences.
4209 GB6. L × ( L | V | LV | LVT ) */
4210 case GCBcase(GCB_L, GCB_L):
4211 case GCBcase(GCB_L, GCB_V):
4212 case GCBcase(GCB_L, GCB_LV):
4213 case GCBcase(GCB_L, GCB_LVT):
4216 /* GB7. ( LV | V ) × ( V | T ) */
4217 case GCBcase(GCB_LV, GCB_V):
4218 case GCBcase(GCB_LV, GCB_T):
4219 case GCBcase(GCB_V, GCB_V):
4220 case GCBcase(GCB_V, GCB_T):
4223 /* GB8. ( LVT | T) × T */
4224 case GCBcase(GCB_LVT, GCB_T):
4225 case GCBcase(GCB_T, GCB_T):
4228 /* Do not break between regional indicator symbols.
4229 GB8a. Regional_Indicator × Regional_Indicator */
4230 case GCBcase(GCB_Regional_Indicator, GCB_Regional_Indicator):
4233 /* Do not break before extending characters.
4235 case GCBcase(GCB_Other, GCB_Extend):
4236 case GCBcase(GCB_Extend, GCB_Extend):
4237 case GCBcase(GCB_L, GCB_Extend):
4238 case GCBcase(GCB_LV, GCB_Extend):
4239 case GCBcase(GCB_LVT, GCB_Extend):
4240 case GCBcase(GCB_Prepend, GCB_Extend):
4241 case GCBcase(GCB_Regional_Indicator, GCB_Extend):
4242 case GCBcase(GCB_SpacingMark, GCB_Extend):
4243 case GCBcase(GCB_T, GCB_Extend):
4244 case GCBcase(GCB_V, GCB_Extend):
4247 /* Do not break before SpacingMarks, or after Prepend characters.
4248 GB9a. × SpacingMark */
4249 case GCBcase(GCB_Other, GCB_SpacingMark):
4250 case GCBcase(GCB_Extend, GCB_SpacingMark):
4251 case GCBcase(GCB_L, GCB_SpacingMark):
4252 case GCBcase(GCB_LV, GCB_SpacingMark):
4253 case GCBcase(GCB_LVT, GCB_SpacingMark):
4254 case GCBcase(GCB_Prepend, GCB_SpacingMark):
4255 case GCBcase(GCB_Regional_Indicator, GCB_SpacingMark):
4256 case GCBcase(GCB_SpacingMark, GCB_SpacingMark):
4257 case GCBcase(GCB_T, GCB_SpacingMark):
4258 case GCBcase(GCB_V, GCB_SpacingMark):
4261 /* GB9b. Prepend × */
4262 case GCBcase(GCB_Prepend, GCB_Other):
4263 case GCBcase(GCB_Prepend, GCB_L):
4264 case GCBcase(GCB_Prepend, GCB_LV):
4265 case GCBcase(GCB_Prepend, GCB_LVT):
4266 case GCBcase(GCB_Prepend, GCB_Prepend):
4267 case GCBcase(GCB_Prepend, GCB_Regional_Indicator):
4268 case GCBcase(GCB_Prepend, GCB_T):
4269 case GCBcase(GCB_Prepend, GCB_V):
4273 NOT_REACHED; /* NOTREACHED */
4276 #define SBcase(before, after) ((SB_ENUM_COUNT * before) + after)
4279 S_isSB(pTHX_ SB_enum before,
4281 const U8 * const strbeg,
4282 const U8 * const curpos,
4283 const U8 * const strend,
4284 const bool utf8_target)
4286 /* returns a boolean indicating if there is a Sentence Boundary Break
4287 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4289 U8 * lpos = (U8 *) curpos;
4293 PERL_ARGS_ASSERT_ISSB;
4295 /* Break at the start and end of text.
4298 if (before == SB_EDGE || after == SB_EDGE) {
4302 /* SB 3: Do not break within CRLF. */
4303 if (before == SB_CR && after == SB_LF) {
4307 /* Break after paragraph separators. (though why CR and LF are considered
4308 * so is beyond me (khw)
4309 SB4. Sep | CR | LF ÷ */
4310 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4314 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4315 * (See Section 6.2, Replacing Ignore Rules.)
4316 SB5. X (Extend | Format)* → X */
4317 if (after == SB_Extend || after == SB_Format) {
4321 if (before == SB_Extend || before == SB_Format) {
4322 before = backup_one_SB(strbeg, &lpos, utf8_target);
4325 /* Do not break after ambiguous terminators like period, if they are
4326 * immediately followed by a number or lowercase letter, if they are
4327 * between uppercase letters, if the first following letter (optionally
4328 * after certain punctuation) is lowercase, or if they are followed by
4329 * "continuation" punctuation such as comma, colon, or semicolon. For
4330 * example, a period may be an abbreviation or numeric period, and thus may
4331 * not mark the end of a sentence.
4333 * SB6. ATerm × Numeric */
4334 if (before == SB_ATerm && after == SB_Numeric) {
4338 /* SB7. (Upper | Lower) ATerm × Upper */
4339 if (before == SB_ATerm && after == SB_Upper) {
4341 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4342 if (backup == SB_Upper || backup == SB_Lower) {
4347 /* SB8a. (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4348 * SB10. (STerm | ATerm) Close* Sp* × ( Sp | Sep | CR | LF ) */
4351 while (backup == SB_Sp) {
4352 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4354 while (backup == SB_Close) {
4355 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4357 if ((backup == SB_STerm || backup == SB_ATerm)
4358 && ( after == SB_SContinue
4359 || after == SB_STerm
4360 || after == SB_ATerm
4369 /* SB8. ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR | LF |
4370 * STerm | ATerm) )* Lower */
4371 if (backup == SB_ATerm) {
4372 U8 * rpos = (U8 *) curpos;
4373 SB_enum later = after;
4375 while ( later != SB_OLetter
4376 && later != SB_Upper
4377 && later != SB_Lower
4381 && later != SB_STerm
4382 && later != SB_ATerm
4383 && later != SB_EDGE)
4385 later = advance_one_SB(&rpos, strend, utf8_target);
4387 if (later == SB_Lower) {
4392 /* Break after sentence terminators, but include closing punctuation,
4393 * trailing spaces, and a paragraph separator (if present). [See note
4395 * SB9. ( STerm | ATerm ) Close* × ( Close | Sp | Sep | CR | LF ) */
4398 while (backup == SB_Close) {
4399 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4401 if ((backup == SB_STerm || backup == SB_ATerm)
4402 && ( after == SB_Close
4412 /* SB11. ( STerm | ATerm ) Close* Sp* ( Sep | CR | LF )? ÷ */
4414 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4415 if ( backup == SB_Sep
4424 while (backup == SB_Sp) {
4425 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4427 while (backup == SB_Close) {
4428 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4430 if (backup == SB_STerm || backup == SB_ATerm) {
4434 /* Otherwise, do not break.
4441 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4445 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4447 if (*curpos >= strend) {
4453 *curpos += UTF8SKIP(*curpos);
4454 if (*curpos >= strend) {
4457 sb = getSB_VAL_UTF8(*curpos, strend);
4458 } while (sb == SB_Extend || sb == SB_Format);
4463 if (*curpos >= strend) {
4466 sb = getSB_VAL_CP(**curpos);
4467 } while (sb == SB_Extend || sb == SB_Format);
4474 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4478 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4480 if (*curpos < strbeg) {
4485 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4486 if (! prev_char_pos) {
4490 /* Back up over Extend and Format. curpos is always just to the right
4491 * of the characater whose value we are getting */
4493 U8 * prev_prev_char_pos;
4494 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4497 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4498 *curpos = prev_char_pos;
4499 prev_char_pos = prev_prev_char_pos;
4502 *curpos = (U8 *) strbeg;
4505 } while (sb == SB_Extend || sb == SB_Format);
4509 if (*curpos - 2 < strbeg) {
4510 *curpos = (U8 *) strbeg;
4514 sb = getSB_VAL_CP(*(*curpos - 1));
4515 } while (sb == SB_Extend || sb == SB_Format);
4521 #define WBcase(before, after) ((WB_ENUM_COUNT * before) + after)
4524 S_isWB(pTHX_ WB_enum previous,
4527 const U8 * const strbeg,
4528 const U8 * const curpos,
4529 const U8 * const strend,
4530 const bool utf8_target)
4532 /* Return a boolean as to if the boundary between 'before' and 'after' is
4533 * a Unicode word break, using their published algorithm. Context may be
4534 * needed to make this determination. If the value for the character
4535 * before 'before' is known, it is passed as 'previous'; otherwise that
4536 * should be set to WB_UNKNOWN. The other input parameters give the
4537 * boundaries and current position in the matching of the string. That
4538 * is, 'curpos' marks the position where the character whose wb value is
4539 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
4541 U8 * before_pos = (U8 *) curpos;
4542 U8 * after_pos = (U8 *) curpos;
4544 PERL_ARGS_ASSERT_ISWB;
4546 /* WB1 and WB2: Break at the start and end of text. */
4547 if (before == WB_EDGE || after == WB_EDGE) {
4551 /* WB 3: Do not break within CRLF. */
4552 if (before == WB_CR && after == WB_LF) {
4556 /* WB 3a and WB 3b: Otherwise break before and after Newlines (including CR
4558 if ( before == WB_CR || before == WB_LF || before == WB_Newline
4559 || after == WB_CR || after == WB_LF || after == WB_Newline)
4564 /* Ignore Format and Extend characters, except when they appear at the
4565 * beginning of a region of text.
4566 * WB4. X (Extend | Format)* → X. */
4568 if (after == WB_Extend || after == WB_Format) {
4572 if (before == WB_Extend || before == WB_Format) {
4573 before = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4576 switch (WBcase(before, after)) {
4577 /* Otherwise, break everywhere (including around ideographs).
4582 /* Do not break between most letters.
4583 WB5. (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) */
4584 case WBcase(WB_ALetter, WB_ALetter):
4585 case WBcase(WB_ALetter, WB_Hebrew_Letter):
4586 case WBcase(WB_Hebrew_Letter, WB_ALetter):
4587 case WBcase(WB_Hebrew_Letter, WB_Hebrew_Letter):
4590 /* Do not break letters across certain punctuation.
4591 WB6. (ALetter | Hebrew_Letter)
4592 × (MidLetter | MidNumLet | Single_Quote) (ALetter
4594 case WBcase(WB_ALetter, WB_MidLetter):
4595 case WBcase(WB_ALetter, WB_MidNumLet):
4596 case WBcase(WB_ALetter, WB_Single_Quote):
4597 case WBcase(WB_Hebrew_Letter, WB_MidLetter):
4598 case WBcase(WB_Hebrew_Letter, WB_MidNumLet):
4599 /*case WBcase(WB_Hebrew_Letter, WB_Single_Quote):*/
4600 after = advance_one_WB(&after_pos, strend, utf8_target);
4601 return after != WB_ALetter && after != WB_Hebrew_Letter;
4603 /* WB7. (ALetter | Hebrew_Letter) (MidLetter | MidNumLet |
4604 * Single_Quote) × (ALetter | Hebrew_Letter) */
4605 case WBcase(WB_MidLetter, WB_ALetter):
4606 case WBcase(WB_MidLetter, WB_Hebrew_Letter):
4607 case WBcase(WB_MidNumLet, WB_ALetter):
4608 case WBcase(WB_MidNumLet, WB_Hebrew_Letter):
4609 case WBcase(WB_Single_Quote, WB_ALetter):
4610 case WBcase(WB_Single_Quote, WB_Hebrew_Letter):
4612 = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4613 return before != WB_ALetter && before != WB_Hebrew_Letter;
4615 /* WB7a. Hebrew_Letter × Single_Quote */
4616 case WBcase(WB_Hebrew_Letter, WB_Single_Quote):
4619 /* WB7b. Hebrew_Letter × Double_Quote Hebrew_Letter */
4620 case WBcase(WB_Hebrew_Letter, WB_Double_Quote):
4621 return advance_one_WB(&after_pos, strend, utf8_target)
4622 != WB_Hebrew_Letter;
4624 /* WB7c. Hebrew_Letter Double_Quote × Hebrew_Letter */
4625 case WBcase(WB_Double_Quote, WB_Hebrew_Letter):
4626 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4627 != WB_Hebrew_Letter;
4629 /* Do not break within sequences of digits, or digits adjacent to
4630 * letters (“3a”, or “A3”).
4631 WB8. Numeric × Numeric */
4632 case WBcase(WB_Numeric, WB_Numeric):
4635 /* WB9. (ALetter | Hebrew_Letter) × Numeric */
4636 case WBcase(WB_ALetter, WB_Numeric):
4637 case WBcase(WB_Hebrew_Letter, WB_Numeric):
4640 /* WB10. Numeric × (ALetter | Hebrew_Letter) */
4641 case WBcase(WB_Numeric, WB_ALetter):
4642 case WBcase(WB_Numeric, WB_Hebrew_Letter):
4645 /* Do not break within sequences, such as “3.2” or “3,456.789”.
4646 WB11. Numeric (MidNum | MidNumLet | Single_Quote) × Numeric
4648 case WBcase(WB_MidNum, WB_Numeric):
4649 case WBcase(WB_MidNumLet, WB_Numeric):
4650 case WBcase(WB_Single_Quote, WB_Numeric):
4651 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4654 /* WB12. Numeric × (MidNum | MidNumLet | Single_Quote) Numeric
4656 case WBcase(WB_Numeric, WB_MidNum):
4657 case WBcase(WB_Numeric, WB_MidNumLet):
4658 case WBcase(WB_Numeric, WB_Single_Quote):
4659 return advance_one_WB(&after_pos, strend, utf8_target)
4662 /* Do not break between Katakana.
4663 WB13. Katakana × Katakana */
4664 case WBcase(WB_Katakana, WB_Katakana):
4667 /* Do not break from extenders.
4668 WB13a. (ALetter | Hebrew_Letter | Numeric | Katakana |
4669 ExtendNumLet) × ExtendNumLet */
4670 case WBcase(WB_ALetter, WB_ExtendNumLet):
4671 case WBcase(WB_Hebrew_Letter, WB_ExtendNumLet):
4672 case WBcase(WB_Numeric, WB_ExtendNumLet):
4673 case WBcase(WB_Katakana, WB_ExtendNumLet):
4674 case WBcase(WB_ExtendNumLet, WB_ExtendNumLet):
4677 /* WB13b. ExtendNumLet × (ALetter | Hebrew_Letter | Numeric
4679 case WBcase(WB_ExtendNumLet, WB_ALetter):
4680 case WBcase(WB_ExtendNumLet, WB_Hebrew_Letter):
4681 case WBcase(WB_ExtendNumLet, WB_Numeric):
4682 case WBcase(WB_ExtendNumLet, WB_Katakana):
4685 /* Do not break between regional indicator symbols.
4686 WB13c. Regional_Indicator × Regional_Indicator */
4687 case WBcase(WB_Regional_Indicator, WB_Regional_Indicator):
4692 NOT_REACHED; /* NOTREACHED */
4696 S_advance_one_WB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4700 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
4702 if (*curpos >= strend) {
4708 /* Advance over Extend and Format */
4710 *curpos += UTF8SKIP(*curpos);
4711 if (*curpos >= strend) {
4714 wb = getWB_VAL_UTF8(*curpos, strend);
4715 } while (wb == WB_Extend || wb == WB_Format);
4720 if (*curpos >= strend) {
4723 wb = getWB_VAL_CP(**curpos);
4724 } while (wb == WB_Extend || wb == WB_Format);
4731 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4735 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
4737 /* If we know what the previous character's break value is, don't have
4739 if (*previous != WB_UNKNOWN) {
4741 *previous = WB_UNKNOWN;
4742 /* XXX Note that doesn't change curpos, and maybe should */
4744 /* But we always back up over these two types */
4745 if (wb != WB_Extend && wb != WB_Format) {
4750 if (*curpos < strbeg) {
4755 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4756 if (! prev_char_pos) {
4760 /* Back up over Extend and Format. curpos is always just to the right
4761 * of the characater whose value we are getting */
4763 U8 * prev_prev_char_pos;
4764 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
4768 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4769 *curpos = prev_char_pos;
4770 prev_char_pos = prev_prev_char_pos;
4773 *curpos = (U8 *) strbeg;
4776 } while (wb == WB_Extend || wb == WB_Format);
4780 if (*curpos - 2 < strbeg) {
4781 *curpos = (U8 *) strbeg;
4785 wb = getWB_VAL_CP(*(*curpos - 1));
4786 } while (wb == WB_Extend || wb == WB_Format);
4792 /* returns -1 on failure, $+[0] on success */
4794 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
4796 #if PERL_VERSION < 9 && !defined(PERL_CORE)
4800 const bool utf8_target = reginfo->is_utf8_target;
4801 const U32 uniflags = UTF8_ALLOW_DEFAULT;
4802 REGEXP *rex_sv = reginfo->prog;
4803 regexp *rex = ReANY(rex_sv);
4804 RXi_GET_DECL(rex,rexi);
4805 /* the current state. This is a cached copy of PL_regmatch_state */
4807 /* cache heavy used fields of st in registers */
4810 U32 n = 0; /* general value; init to avoid compiler warning */
4811 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
4812 char *locinput = startpos;
4813 char *pushinput; /* where to continue after a PUSH */
4814 I32 nextchr; /* is always set to UCHARAT(locinput) */
4816 bool result = 0; /* return value of S_regmatch */
4817 int depth = 0; /* depth of backtrack stack */
4818 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
4819 const U32 max_nochange_depth =
4820 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
4821 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
4822 regmatch_state *yes_state = NULL; /* state to pop to on success of
4824 /* mark_state piggy backs on the yes_state logic so that when we unwind
4825 the stack on success we can update the mark_state as we go */
4826 regmatch_state *mark_state = NULL; /* last mark state we have seen */
4827 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
4828 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
4830 bool no_final = 0; /* prevent failure from backtracking? */
4831 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
4832 char *startpoint = locinput;
4833 SV *popmark = NULL; /* are we looking for a mark? */
4834 SV *sv_commit = NULL; /* last mark name seen in failure */
4835 SV *sv_yes_mark = NULL; /* last mark name we have seen
4836 during a successful match */
4837 U32 lastopen = 0; /* last open we saw */
4838 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
4839 SV* const oreplsv = GvSVn(PL_replgv);
4840 /* these three flags are set by various ops to signal information to
4841 * the very next op. They have a useful lifetime of exactly one loop
4842 * iteration, and are not preserved or restored by state pushes/pops
4844 bool sw = 0; /* the condition value in (?(cond)a|b) */
4845 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
4846 int logical = 0; /* the following EVAL is:
4850 or the following IFMATCH/UNLESSM is:
4851 false: plain (?=foo)
4852 true: used as a condition: (?(?=foo))
4854 PAD* last_pad = NULL;
4856 I32 gimme = G_SCALAR;
4857 CV *caller_cv = NULL; /* who called us */
4858 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
4859 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
4860 U32 maxopenparen = 0; /* max '(' index seen so far */
4861 int to_complement; /* Invert the result? */
4862 _char_class_number classnum;
4863 bool is_utf8_pat = reginfo->is_utf8_pat;
4868 GET_RE_DEBUG_FLAGS_DECL;
4871 /* protect against undef(*^R) */
4872 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
4874 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
4875 multicall_oldcatch = 0;
4876 multicall_cv = NULL;
4878 PERL_UNUSED_VAR(multicall_cop);
4879 PERL_UNUSED_VAR(newsp);
4882 PERL_ARGS_ASSERT_REGMATCH;
4884 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
4885 PerlIO_printf(Perl_debug_log,"regmatch start\n");
4888 st = PL_regmatch_state;
4890 /* Note that nextchr is a byte even in UTF */
4893 while (scan != NULL) {
4896 SV * const prop = sv_newmortal();
4897 regnode *rnext=regnext(scan);
4898 DUMP_EXEC_POS( locinput, scan, utf8_target );
4899 regprop(rex, prop, scan, reginfo, NULL);
4901 PerlIO_printf(Perl_debug_log,
4902 "%3"IVdf":%*s%s(%"IVdf")\n",
4903 (IV)(scan - rexi->program), depth*2, "",
4905 (PL_regkind[OP(scan)] == END || !rnext) ?
4906 0 : (IV)(rnext - rexi->program));
4909 next = scan + NEXT_OFF(scan);
4912 state_num = OP(scan);
4914 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
4919 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
4921 switch (state_num) {
4922 case SBOL: /* /^../ and /\A../ */
4923 if (locinput == reginfo->strbeg)
4927 case MBOL: /* /^../m */
4928 if (locinput == reginfo->strbeg ||
4929 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4936 if (locinput == reginfo->ganch)
4940 case KEEPS: /* \K */
4941 /* update the startpoint */
4942 st->u.keeper.val = rex->offs[0].start;
4943 rex->offs[0].start = locinput - reginfo->strbeg;
4944 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4946 NOT_REACHED; /* NOTREACHED */
4948 case KEEPS_next_fail:
4949 /* rollback the start point change */
4950 rex->offs[0].start = st->u.keeper.val;
4953 NOT_REACHED; /* NOTREACHED */
4955 case MEOL: /* /..$/m */
4956 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4960 case SEOL: /* /..$/ */
4961 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4963 if (reginfo->strend - locinput > 1)
4968 if (!NEXTCHR_IS_EOS)
4972 case SANY: /* /./s */
4975 goto increment_locinput;
4977 case REG_ANY: /* /./ */
4978 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4980 goto increment_locinput;
4984 #define ST st->u.trie
4985 case TRIEC: /* (ab|cd) with known charclass */
4986 /* In this case the charclass data is available inline so
4987 we can fail fast without a lot of extra overhead.
4989 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
4991 PerlIO_printf(Perl_debug_log,
4992 "%*s %sfailed to match trie start class...%s\n",
4993 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4997 NOT_REACHED; /* NOTREACHED */
5000 case TRIE: /* (ab|cd) */
5001 /* the basic plan of execution of the trie is:
5002 * At the beginning, run though all the states, and
5003 * find the longest-matching word. Also remember the position
5004 * of the shortest matching word. For example, this pattern:
5007 * when matched against the string "abcde", will generate
5008 * accept states for all words except 3, with the longest
5009 * matching word being 4, and the shortest being 2 (with
5010 * the position being after char 1 of the string).
5012 * Then for each matching word, in word order (i.e. 1,2,4,5),
5013 * we run the remainder of the pattern; on each try setting
5014 * the current position to the character following the word,
5015 * returning to try the next word on failure.
5017 * We avoid having to build a list of words at runtime by
5018 * using a compile-time structure, wordinfo[].prev, which
5019 * gives, for each word, the previous accepting word (if any).
5020 * In the case above it would contain the mappings 1->2, 2->0,
5021 * 3->0, 4->5, 5->1. We can use this table to generate, from
5022 * the longest word (4 above), a list of all words, by
5023 * following the list of prev pointers; this gives us the
5024 * unordered list 4,5,1,2. Then given the current word we have
5025 * just tried, we can go through the list and find the
5026 * next-biggest word to try (so if we just failed on word 2,
5027 * the next in the list is 4).
5029 * Since at runtime we don't record the matching position in
5030 * the string for each word, we have to work that out for
5031 * each word we're about to process. The wordinfo table holds
5032 * the character length of each word; given that we recorded
5033 * at the start: the position of the shortest word and its
5034 * length in chars, we just need to move the pointer the
5035 * difference between the two char lengths. Depending on
5036 * Unicode status and folding, that's cheap or expensive.
5038 * This algorithm is optimised for the case where are only a
5039 * small number of accept states, i.e. 0,1, or maybe 2.
5040 * With lots of accepts states, and having to try all of them,
5041 * it becomes quadratic on number of accept states to find all
5046 /* what type of TRIE am I? (utf8 makes this contextual) */
5047 DECL_TRIE_TYPE(scan);
5049 /* what trie are we using right now */
5050 reg_trie_data * const trie
5051 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5052 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5053 U32 state = trie->startstate;
5055 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5056 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5058 && UTF8_IS_ABOVE_LATIN1(nextchr)
5059 && scan->flags == EXACTL)
5061 /* We only output for EXACTL, as we let the folder
5062 * output this message for EXACTFLU8 to avoid
5064 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5069 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5071 if (trie->states[ state ].wordnum) {
5073 PerlIO_printf(Perl_debug_log,
5074 "%*s %smatched empty string...%s\n",
5075 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5081 PerlIO_printf(Perl_debug_log,
5082 "%*s %sfailed to match trie start class...%s\n",
5083 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5090 U8 *uc = ( U8* )locinput;
5094 U8 *uscan = (U8*)NULL;
5095 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5096 U32 charcount = 0; /* how many input chars we have matched */
5097 U32 accepted = 0; /* have we seen any accepting states? */
5099 ST.jump = trie->jump;
5102 ST.longfold = FALSE; /* char longer if folded => it's harder */
5105 /* fully traverse the TRIE; note the position of the
5106 shortest accept state and the wordnum of the longest
5109 while ( state && uc <= (U8*)(reginfo->strend) ) {
5110 U32 base = trie->states[ state ].trans.base;
5114 wordnum = trie->states[ state ].wordnum;
5116 if (wordnum) { /* it's an accept state */
5119 /* record first match position */
5121 ST.firstpos = (U8*)locinput;
5126 ST.firstchars = charcount;
5129 if (!ST.nextword || wordnum < ST.nextword)
5130 ST.nextword = wordnum;
5131 ST.topword = wordnum;
5134 DEBUG_TRIE_EXECUTE_r({
5135 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5136 PerlIO_printf( Perl_debug_log,
5137 "%*s %sState: %4"UVxf" Accepted: %c ",
5138 2+depth * 2, "", PL_colors[4],
5139 (UV)state, (accepted ? 'Y' : 'N'));
5142 /* read a char and goto next state */
5143 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5145 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5146 uscan, len, uvc, charid, foldlen,
5153 base + charid - 1 - trie->uniquecharcount)) >= 0)
5155 && ((U32)offset < trie->lasttrans)
5156 && trie->trans[offset].check == state)
5158 state = trie->trans[offset].next;
5169 DEBUG_TRIE_EXECUTE_r(
5170 PerlIO_printf( Perl_debug_log,
5171 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5172 charid, uvc, (UV)state, PL_colors[5] );
5178 /* calculate total number of accept states */
5183 w = trie->wordinfo[w].prev;
5186 ST.accepted = accepted;
5190 PerlIO_printf( Perl_debug_log,
5191 "%*s %sgot %"IVdf" possible matches%s\n",
5192 REPORT_CODE_OFF + depth * 2, "",
5193 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5195 goto trie_first_try; /* jump into the fail handler */
5198 NOT_REACHED; /* NOTREACHED */
5200 case TRIE_next_fail: /* we failed - try next alternative */
5204 REGCP_UNWIND(ST.cp);
5205 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5207 if (!--ST.accepted) {
5209 PerlIO_printf( Perl_debug_log,
5210 "%*s %sTRIE failed...%s\n",
5211 REPORT_CODE_OFF+depth*2, "",
5218 /* Find next-highest word to process. Note that this code
5219 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5222 U16 const nextword = ST.nextword;
5223 reg_trie_wordinfo * const wordinfo
5224 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5225 for (word=ST.topword; word; word=wordinfo[word].prev) {
5226 if (word > nextword && (!min || word < min))
5239 ST.lastparen = rex->lastparen;
5240 ST.lastcloseparen = rex->lastcloseparen;
5244 /* find start char of end of current word */
5246 U32 chars; /* how many chars to skip */
5247 reg_trie_data * const trie
5248 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5250 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5252 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5257 /* the hard option - fold each char in turn and find
5258 * its folded length (which may be different */
5259 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5267 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5275 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5280 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5296 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5297 ? ST.jump[ST.nextword]
5301 PerlIO_printf( Perl_debug_log,
5302 "%*s %sTRIE matched word #%d, continuing%s\n",
5303 REPORT_CODE_OFF+depth*2, "",
5310 if (ST.accepted > 1 || has_cutgroup) {
5311 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5313 NOT_REACHED; /* NOTREACHED */
5315 /* only one choice left - just continue */
5317 AV *const trie_words
5318 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5319 SV ** const tmp = trie_words
5320 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5321 SV *sv= tmp ? sv_newmortal() : NULL;
5323 PerlIO_printf( Perl_debug_log,
5324 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
5325 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5327 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5328 PL_colors[0], PL_colors[1],
5329 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5331 : "not compiled under -Dr",
5335 locinput = (char*)uc;
5336 continue; /* execute rest of RE */
5341 case EXACTL: /* /abc/l */
5342 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5344 /* Complete checking would involve going through every character
5345 * matched by the string to see if any is above latin1. But the
5346 * comparision otherwise might very well be a fast assembly
5347 * language routine, and I (khw) don't think slowing things down
5348 * just to check for this warning is worth it. So this just checks
5349 * the first character */
5350 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5351 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5354 case EXACT: { /* /abc/ */
5355 char *s = STRING(scan);
5357 if (utf8_target != is_utf8_pat) {
5358 /* The target and the pattern have differing utf8ness. */
5360 const char * const e = s + ln;
5363 /* The target is utf8, the pattern is not utf8.
5364 * Above-Latin1 code points can't match the pattern;
5365 * invariants match exactly, and the other Latin1 ones need
5366 * to be downgraded to a single byte in order to do the
5367 * comparison. (If we could be confident that the target
5368 * is not malformed, this could be refactored to have fewer
5369 * tests by just assuming that if the first bytes match, it
5370 * is an invariant, but there are tests in the test suite
5371 * dealing with (??{...}) which violate this) */
5373 if (l >= reginfo->strend
5374 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5378 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5385 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5395 /* The target is not utf8, the pattern is utf8. */
5397 if (l >= reginfo->strend
5398 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5402 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5409 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5421 /* The target and the pattern have the same utf8ness. */
5422 /* Inline the first character, for speed. */
5423 if (reginfo->strend - locinput < ln
5424 || UCHARAT(s) != nextchr
5425 || (ln > 1 && memNE(s, locinput, ln)))
5434 case EXACTFL: { /* /abc/il */
5436 const U8 * fold_array;
5438 U32 fold_utf8_flags;
5440 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5441 folder = foldEQ_locale;
5442 fold_array = PL_fold_locale;
5443 fold_utf8_flags = FOLDEQ_LOCALE;
5446 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5447 is effectively /u; hence to match, target
5449 if (! utf8_target) {
5452 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5453 | FOLDEQ_S1_FOLDS_SANE;
5454 folder = foldEQ_latin1;
5455 fold_array = PL_fold_latin1;
5458 case EXACTFU_SS: /* /\x{df}/iu */
5459 case EXACTFU: /* /abc/iu */
5460 folder = foldEQ_latin1;
5461 fold_array = PL_fold_latin1;
5462 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5465 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5467 assert(! is_utf8_pat);
5469 case EXACTFA: /* /abc/iaa */
5470 folder = foldEQ_latin1;
5471 fold_array = PL_fold_latin1;
5472 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5475 case EXACTF: /* /abc/i This node only generated for
5476 non-utf8 patterns */
5477 assert(! is_utf8_pat);
5479 fold_array = PL_fold;
5480 fold_utf8_flags = 0;
5488 || state_num == EXACTFU_SS
5489 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5491 /* Either target or the pattern are utf8, or has the issue where
5492 * the fold lengths may differ. */
5493 const char * const l = locinput;
5494 char *e = reginfo->strend;
5496 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
5497 l, &e, 0, utf8_target, fold_utf8_flags))
5505 /* Neither the target nor the pattern are utf8 */
5506 if (UCHARAT(s) != nextchr
5508 && UCHARAT(s) != fold_array[nextchr])
5512 if (reginfo->strend - locinput < ln)
5514 if (ln > 1 && ! folder(s, locinput, ln))
5520 case NBOUNDL: /* /\B/l */
5524 case BOUNDL: /* /\b/l */
5525 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5527 if (FLAGS(scan) != TRADITIONAL_BOUND) {
5528 if (! IN_UTF8_CTYPE_LOCALE) {
5529 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5530 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5536 if (locinput == reginfo->strbeg)
5537 ln = isWORDCHAR_LC('\n');
5539 ln = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5540 (U8*)(reginfo->strbeg)));
5542 n = (NEXTCHR_IS_EOS)
5543 ? isWORDCHAR_LC('\n')
5544 : isWORDCHAR_LC_utf8((U8*)locinput);
5546 else { /* Here the string isn't utf8 */
5547 ln = (locinput == reginfo->strbeg)
5548 ? isWORDCHAR_LC('\n')
5549 : isWORDCHAR_LC(UCHARAT(locinput - 1));
5550 n = (NEXTCHR_IS_EOS)
5551 ? isWORDCHAR_LC('\n')
5552 : isWORDCHAR_LC(nextchr);
5554 if (to_complement ^ (ln == n)) {
5559 case NBOUND: /* /\B/ */
5563 case BOUND: /* /\b/ */
5567 goto bound_ascii_match_only;
5569 case NBOUNDA: /* /\B/a */
5573 case BOUNDA: /* /\b/a */
5575 bound_ascii_match_only:
5576 /* Here the string isn't utf8, or is utf8 and only ascii characters
5577 * are to match \w. In the latter case looking at the byte just
5578 * prior to the current one may be just the final byte of a
5579 * multi-byte character. This is ok. There are two cases:
5580 * 1) it is a single byte character, and then the test is doing
5581 * just what it's supposed to.
5582 * 2) it is a multi-byte character, in which case the final byte is
5583 * never mistakable for ASCII, and so the test will say it is
5584 * not a word character, which is the correct answer. */
5585 ln = (locinput == reginfo->strbeg)
5586 ? isWORDCHAR_A('\n')
5587 : isWORDCHAR_A(UCHARAT(locinput - 1));
5588 n = (NEXTCHR_IS_EOS)
5589 ? isWORDCHAR_A('\n')
5590 : isWORDCHAR_A(nextchr);
5591 if (to_complement ^ (ln == n)) {
5596 case NBOUNDU: /* /\B/u */
5600 case BOUNDU: /* /\b/u */
5606 switch((bound_type) FLAGS(scan)) {
5607 case TRADITIONAL_BOUND:
5608 ln = (locinput == reginfo->strbeg)
5609 ? 0 /* isWORDCHAR_L1('\n') */
5610 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5611 (U8*)(reginfo->strbeg)));
5612 n = (NEXTCHR_IS_EOS)
5613 ? 0 /* isWORDCHAR_L1('\n') */
5614 : isWORDCHAR_utf8((U8*)locinput);
5615 match = cBOOL(ln != n);
5618 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5619 match = TRUE; /* GCB always matches at begin and
5623 /* Find the gcb values of previous and current
5624 * chars, then see if is a break point */
5625 match = isGCB(getGCB_VAL_UTF8(
5626 reghop3((U8*)locinput,
5628 (U8*)(reginfo->strbeg)),
5629 (U8*) reginfo->strend),
5630 getGCB_VAL_UTF8((U8*) locinput,
5631 (U8*) reginfo->strend));
5635 case SB_BOUND: /* Always matches at begin and end */
5636 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5640 match = isSB(getSB_VAL_UTF8(
5641 reghop3((U8*)locinput,
5643 (U8*)(reginfo->strbeg)),
5644 (U8*) reginfo->strend),
5645 getSB_VAL_UTF8((U8*) locinput,
5646 (U8*) reginfo->strend),
5647 (U8*) reginfo->strbeg,
5649 (U8*) reginfo->strend,
5655 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5659 match = isWB(WB_UNKNOWN,
5661 reghop3((U8*)locinput,
5663 (U8*)(reginfo->strbeg)),
5664 (U8*) reginfo->strend),
5665 getWB_VAL_UTF8((U8*) locinput,
5666 (U8*) reginfo->strend),
5667 (U8*) reginfo->strbeg,
5669 (U8*) reginfo->strend,
5675 else { /* Not utf8 target */
5676 switch((bound_type) FLAGS(scan)) {
5677 case TRADITIONAL_BOUND:
5678 ln = (locinput == reginfo->strbeg)
5679 ? 0 /* isWORDCHAR_L1('\n') */
5680 : isWORDCHAR_L1(UCHARAT(locinput - 1));
5681 n = (NEXTCHR_IS_EOS)
5682 ? 0 /* isWORDCHAR_L1('\n') */
5683 : isWORDCHAR_L1(nextchr);
5684 match = cBOOL(ln != n);
5688 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5689 match = TRUE; /* GCB always matches at begin and
5692 else { /* Only CR-LF combo isn't a GCB in 0-255
5694 match = UCHARAT(locinput - 1) != '\r'
5695 || UCHARAT(locinput) != '\n';
5699 case SB_BOUND: /* Always matches at begin and end */
5700 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5704 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
5705 getSB_VAL_CP(UCHARAT(locinput)),
5706 (U8*) reginfo->strbeg,
5708 (U8*) reginfo->strend,
5714 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5718 match = isWB(WB_UNKNOWN,
5719 getWB_VAL_CP(UCHARAT(locinput -1)),
5720 getWB_VAL_CP(UCHARAT(locinput)),
5721 (U8*) reginfo->strbeg,
5723 (U8*) reginfo->strend,
5730 if (to_complement ^ ! match) {
5735 case ANYOFL: /* /[abc]/l */
5736 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5738 case ANYOF: /* /[abc]/ */
5742 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
5745 locinput += UTF8SKIP(locinput);
5748 if (!REGINCLASS(rex, scan, (U8*)locinput))
5754 /* The argument (FLAGS) to all the POSIX node types is the class number
5757 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
5761 case POSIXL: /* \w or [:punct:] etc. under /l */
5762 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5766 /* Use isFOO_lc() for characters within Latin1. (Note that
5767 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5768 * wouldn't be invariant) */
5769 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5770 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
5774 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5775 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
5776 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
5777 *(locinput + 1))))))
5782 else { /* Here, must be an above Latin-1 code point */
5783 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5784 goto utf8_posix_above_latin1;
5787 /* Here, must be utf8 */
5788 locinput += UTF8SKIP(locinput);
5791 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
5795 case POSIXD: /* \w or [:punct:] etc. under /d */
5801 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
5803 if (NEXTCHR_IS_EOS) {
5807 /* All UTF-8 variants match */
5808 if (! UTF8_IS_INVARIANT(nextchr)) {
5809 goto increment_locinput;
5815 case POSIXA: /* \w or [:punct:] etc. under /a */
5818 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
5819 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
5820 * character is a single byte */
5823 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
5829 /* Here we are either not in utf8, or we matched a utf8-invariant,
5830 * so the next char is the next byte */
5834 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
5838 case POSIXU: /* \w or [:punct:] etc. under /u */
5840 if (NEXTCHR_IS_EOS) {
5844 /* Use _generic_isCC() for characters within Latin1. (Note that
5845 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5846 * wouldn't be invariant) */
5847 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5848 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
5855 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5856 if (! (to_complement
5857 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
5865 else { /* Handle above Latin-1 code points */
5866 utf8_posix_above_latin1:
5867 classnum = (_char_class_number) FLAGS(scan);
5868 if (classnum < _FIRST_NON_SWASH_CC) {
5870 /* Here, uses a swash to find such code points. Load if if
5871 * not done already */
5872 if (! PL_utf8_swash_ptrs[classnum]) {
5873 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
5874 PL_utf8_swash_ptrs[classnum]
5875 = _core_swash_init("utf8",
5878 PL_XPosix_ptrs[classnum], &flags);
5880 if (! (to_complement
5881 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
5882 (U8 *) locinput, TRUE))))
5887 else { /* Here, uses macros to find above Latin-1 code points */
5889 case _CC_ENUM_SPACE:
5890 if (! (to_complement
5891 ^ cBOOL(is_XPERLSPACE_high(locinput))))
5896 case _CC_ENUM_BLANK:
5897 if (! (to_complement
5898 ^ cBOOL(is_HORIZWS_high(locinput))))
5903 case _CC_ENUM_XDIGIT:
5904 if (! (to_complement
5905 ^ cBOOL(is_XDIGIT_high(locinput))))
5910 case _CC_ENUM_VERTSPACE:
5911 if (! (to_complement
5912 ^ cBOOL(is_VERTWS_high(locinput))))
5917 default: /* The rest, e.g. [:cntrl:], can't match
5919 if (! to_complement) {
5925 locinput += UTF8SKIP(locinput);
5929 case CLUMP: /* Match \X: logical Unicode character. This is defined as
5930 a Unicode extended Grapheme Cluster */
5933 if (! utf8_target) {
5935 /* Match either CR LF or '.', as all the other possibilities
5937 locinput++; /* Match the . or CR */
5938 if (nextchr == '\r' /* And if it was CR, and the next is LF,
5940 && locinput < reginfo->strend
5941 && UCHARAT(locinput) == '\n')
5948 /* Get the gcb type for the current character */
5949 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
5950 (U8*) reginfo->strend);
5952 /* Then scan through the input until we get to the first
5953 * character whose type is supposed to be a gcb with the
5954 * current character. (There is always a break at the
5956 locinput += UTF8SKIP(locinput);
5957 while (locinput < reginfo->strend) {
5958 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
5959 (U8*) reginfo->strend);
5960 if (isGCB(prev_gcb, cur_gcb)) {
5965 locinput += UTF8SKIP(locinput);
5972 case NREFFL: /* /\g{name}/il */
5973 { /* The capture buffer cases. The ones beginning with N for the
5974 named buffers just convert to the equivalent numbered and
5975 pretend they were called as the corresponding numbered buffer
5977 /* don't initialize these in the declaration, it makes C++
5982 const U8 *fold_array;
5985 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5986 folder = foldEQ_locale;
5987 fold_array = PL_fold_locale;
5989 utf8_fold_flags = FOLDEQ_LOCALE;
5992 case NREFFA: /* /\g{name}/iaa */
5993 folder = foldEQ_latin1;
5994 fold_array = PL_fold_latin1;
5996 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5999 case NREFFU: /* /\g{name}/iu */
6000 folder = foldEQ_latin1;
6001 fold_array = PL_fold_latin1;
6003 utf8_fold_flags = 0;
6006 case NREFF: /* /\g{name}/i */
6008 fold_array = PL_fold;
6010 utf8_fold_flags = 0;
6013 case NREF: /* /\g{name}/ */
6017 utf8_fold_flags = 0;
6020 /* For the named back references, find the corresponding buffer
6022 n = reg_check_named_buff_matched(rex,scan);
6027 goto do_nref_ref_common;
6029 case REFFL: /* /\1/il */
6030 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6031 folder = foldEQ_locale;
6032 fold_array = PL_fold_locale;
6033 utf8_fold_flags = FOLDEQ_LOCALE;
6036 case REFFA: /* /\1/iaa */
6037 folder = foldEQ_latin1;
6038 fold_array = PL_fold_latin1;
6039 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6042 case REFFU: /* /\1/iu */
6043 folder = foldEQ_latin1;
6044 fold_array = PL_fold_latin1;
6045 utf8_fold_flags = 0;
6048 case REFF: /* /\1/i */
6050 fold_array = PL_fold;
6051 utf8_fold_flags = 0;
6054 case REF: /* /\1/ */
6057 utf8_fold_flags = 0;
6061 n = ARG(scan); /* which paren pair */
6064 ln = rex->offs[n].start;
6065 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6066 if (rex->lastparen < n || ln == -1)
6067 sayNO; /* Do not match unless seen CLOSEn. */
6068 if (ln == rex->offs[n].end)
6071 s = reginfo->strbeg + ln;
6072 if (type != REF /* REF can do byte comparison */
6073 && (utf8_target || type == REFFU || type == REFFL))
6075 char * limit = reginfo->strend;
6077 /* This call case insensitively compares the entire buffer
6078 * at s, with the current input starting at locinput, but
6079 * not going off the end given by reginfo->strend, and
6080 * returns in <limit> upon success, how much of the
6081 * current input was matched */
6082 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6083 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6091 /* Not utf8: Inline the first character, for speed. */
6092 if (!NEXTCHR_IS_EOS &&
6093 UCHARAT(s) != nextchr &&
6095 UCHARAT(s) != fold_array[nextchr]))
6097 ln = rex->offs[n].end - ln;
6098 if (locinput + ln > reginfo->strend)
6100 if (ln > 1 && (type == REF
6101 ? memNE(s, locinput, ln)
6102 : ! folder(s, locinput, ln)))
6108 case NOTHING: /* null op; e.g. the 'nothing' following
6109 * the '*' in m{(a+|b)*}' */
6111 case TAIL: /* placeholder while compiling (A|B|C) */
6115 #define ST st->u.eval
6120 regexp_internal *rei;
6121 regnode *startpoint;
6123 case GOSTART: /* (?R) */
6124 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6125 if (cur_eval && cur_eval->locinput==locinput) {
6126 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
6127 Perl_croak(aTHX_ "Infinite recursion in regex");
6128 if ( ++nochange_depth > max_nochange_depth )
6130 "Pattern subroutine nesting without pos change"
6131 " exceeded limit in regex");
6138 if (OP(scan)==GOSUB) {
6139 startpoint = scan + ARG2L(scan);
6140 ST.close_paren = ARG(scan);
6142 startpoint = rei->program+1;
6146 /* Save all the positions seen so far. */
6147 ST.cp = regcppush(rex, 0, maxopenparen);
6148 REGCP_SET(ST.lastcp);
6150 /* and then jump to the code we share with EVAL */
6151 goto eval_recurse_doit;
6154 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6155 if (cur_eval && cur_eval->locinput==locinput) {
6156 if ( ++nochange_depth > max_nochange_depth )
6157 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6162 /* execute the code in the {...} */
6166 OP * const oop = PL_op;
6167 COP * const ocurcop = PL_curcop;
6171 /* save *all* paren positions */
6172 regcppush(rex, 0, maxopenparen);
6173 REGCP_SET(runops_cp);
6176 caller_cv = find_runcv(NULL);
6180 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6182 (REGEXP*)(rexi->data->data[n])
6185 nop = (OP*)rexi->data->data[n+1];
6187 else if (rexi->data->what[n] == 'l') { /* literal code */
6189 nop = (OP*)rexi->data->data[n];
6190 assert(CvDEPTH(newcv));
6193 /* literal with own CV */
6194 assert(rexi->data->what[n] == 'L');
6195 newcv = rex->qr_anoncv;
6196 nop = (OP*)rexi->data->data[n];
6199 /* normally if we're about to execute code from the same
6200 * CV that we used previously, we just use the existing
6201 * CX stack entry. However, its possible that in the
6202 * meantime we may have backtracked, popped from the save
6203 * stack, and undone the SAVECOMPPAD(s) associated with
6204 * PUSH_MULTICALL; in which case PL_comppad no longer
6205 * points to newcv's pad. */
6206 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6208 U8 flags = (CXp_SUB_RE |
6209 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6210 if (last_pushed_cv) {
6211 CHANGE_MULTICALL_FLAGS(newcv, flags);
6214 PUSH_MULTICALL_FLAGS(newcv, flags);
6216 last_pushed_cv = newcv;
6219 /* these assignments are just to silence compiler
6221 multicall_cop = NULL;
6224 last_pad = PL_comppad;
6226 /* the initial nextstate you would normally execute
6227 * at the start of an eval (which would cause error
6228 * messages to come from the eval), may be optimised
6229 * away from the execution path in the regex code blocks;
6230 * so manually set PL_curcop to it initially */
6232 OP *o = cUNOPx(nop)->op_first;
6233 assert(o->op_type == OP_NULL);
6234 if (o->op_targ == OP_SCOPE) {
6235 o = cUNOPo->op_first;
6238 assert(o->op_targ == OP_LEAVE);
6239 o = cUNOPo->op_first;
6240 assert(o->op_type == OP_ENTER);
6244 if (o->op_type != OP_STUB) {
6245 assert( o->op_type == OP_NEXTSTATE
6246 || o->op_type == OP_DBSTATE
6247 || (o->op_type == OP_NULL
6248 && ( o->op_targ == OP_NEXTSTATE
6249 || o->op_targ == OP_DBSTATE
6253 PL_curcop = (COP*)o;
6258 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
6259 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6261 rex->offs[0].end = locinput - reginfo->strbeg;
6262 if (reginfo->info_aux_eval->pos_magic)
6263 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6264 reginfo->sv, reginfo->strbeg,
6265 locinput - reginfo->strbeg);
6268 SV *sv_mrk = get_sv("REGMARK", 1);
6269 sv_setsv(sv_mrk, sv_yes_mark);
6272 /* we don't use MULTICALL here as we want to call the
6273 * first op of the block of interest, rather than the
6274 * first op of the sub */
6275 before = (IV)(SP-PL_stack_base);
6277 CALLRUNOPS(aTHX); /* Scalar context. */
6279 if ((IV)(SP-PL_stack_base) == before)
6280 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6286 /* before restoring everything, evaluate the returned
6287 * value, so that 'uninit' warnings don't use the wrong
6288 * PL_op or pad. Also need to process any magic vars
6289 * (e.g. $1) *before* parentheses are restored */
6294 if (logical == 0) /* (?{})/ */
6295 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6296 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6297 sw = cBOOL(SvTRUE(ret));
6300 else { /* /(??{}) */
6301 /* if its overloaded, let the regex compiler handle
6302 * it; otherwise extract regex, or stringify */
6303 if (SvGMAGICAL(ret))
6304 ret = sv_mortalcopy(ret);
6305 if (!SvAMAGIC(ret)) {
6309 if (SvTYPE(sv) == SVt_REGEXP)
6310 re_sv = (REGEXP*) sv;
6311 else if (SvSMAGICAL(ret)) {
6312 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6314 re_sv = (REGEXP *) mg->mg_obj;
6317 /* force any undef warnings here */
6318 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6319 ret = sv_mortalcopy(ret);
6320 (void) SvPV_force_nolen(ret);
6326 /* *** Note that at this point we don't restore
6327 * PL_comppad, (or pop the CxSUB) on the assumption it may
6328 * be used again soon. This is safe as long as nothing
6329 * in the regexp code uses the pad ! */
6331 PL_curcop = ocurcop;
6332 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6333 PL_curpm = PL_reg_curpm;
6339 /* only /(??{})/ from now on */
6342 /* extract RE object from returned value; compiling if
6346 re_sv = reg_temp_copy(NULL, re_sv);
6351 if (SvUTF8(ret) && IN_BYTES) {
6352 /* In use 'bytes': make a copy of the octet
6353 * sequence, but without the flag on */
6355 const char *const p = SvPV(ret, len);
6356 ret = newSVpvn_flags(p, len, SVs_TEMP);
6358 if (rex->intflags & PREGf_USE_RE_EVAL)
6359 pm_flags |= PMf_USE_RE_EVAL;
6361 /* if we got here, it should be an engine which
6362 * supports compiling code blocks and stuff */
6363 assert(rex->engine && rex->engine->op_comp);
6364 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6365 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6366 rex->engine, NULL, NULL,
6367 /* copy /msixn etc to inner pattern */
6372 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6373 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6374 /* This isn't a first class regexp. Instead, it's
6375 caching a regexp onto an existing, Perl visible
6377 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6383 RXp_MATCH_COPIED_off(re);
6384 re->subbeg = rex->subbeg;
6385 re->sublen = rex->sublen;
6386 re->suboffset = rex->suboffset;
6387 re->subcoffset = rex->subcoffset;
6389 re->lastcloseparen = 0;
6392 debug_start_match(re_sv, utf8_target, locinput,
6393 reginfo->strend, "Matching embedded");
6395 startpoint = rei->program + 1;
6396 ST.close_paren = 0; /* only used for GOSUB */
6397 /* Save all the seen positions so far. */
6398 ST.cp = regcppush(rex, 0, maxopenparen);
6399 REGCP_SET(ST.lastcp);
6400 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6402 /* run the pattern returned from (??{...}) */
6404 eval_recurse_doit: /* Share code with GOSUB below this line
6405 * At this point we expect the stack context to be
6406 * set up correctly */
6408 /* invalidate the S-L poscache. We're now executing a
6409 * different set of WHILEM ops (and their associated
6410 * indexes) against the same string, so the bits in the
6411 * cache are meaningless. Setting maxiter to zero forces
6412 * the cache to be invalidated and zeroed before reuse.
6413 * XXX This is too dramatic a measure. Ideally we should
6414 * save the old cache and restore when running the outer
6416 reginfo->poscache_maxiter = 0;
6418 /* the new regexp might have a different is_utf8_pat than we do */
6419 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6421 ST.prev_rex = rex_sv;
6422 ST.prev_curlyx = cur_curlyx;
6424 SET_reg_curpm(rex_sv);
6429 ST.prev_eval = cur_eval;
6431 /* now continue from first node in postoned RE */
6432 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
6434 NOT_REACHED; /* NOTREACHED */
6437 case EVAL_AB: /* cleanup after a successful (??{A})B */
6438 /* note: this is called twice; first after popping B, then A */
6439 rex_sv = ST.prev_rex;
6440 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6441 SET_reg_curpm(rex_sv);
6442 rex = ReANY(rex_sv);
6443 rexi = RXi_GET(rex);
6445 /* preserve $^R across LEAVE's. See Bug 121070. */
6446 SV *save_sv= GvSV(PL_replgv);
6447 SvREFCNT_inc(save_sv);
6448 regcpblow(ST.cp); /* LEAVE in disguise */
6449 sv_setsv(GvSV(PL_replgv), save_sv);
6450 SvREFCNT_dec(save_sv);
6452 cur_eval = ST.prev_eval;
6453 cur_curlyx = ST.prev_curlyx;
6455 /* Invalidate cache. See "invalidate" comment above. */
6456 reginfo->poscache_maxiter = 0;
6457 if ( nochange_depth )
6462 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
6463 /* note: this is called twice; first after popping B, then A */
6464 rex_sv = ST.prev_rex;
6465 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6466 SET_reg_curpm(rex_sv);
6467 rex = ReANY(rex_sv);
6468 rexi = RXi_GET(rex);
6470 REGCP_UNWIND(ST.lastcp);
6471 regcppop(rex, &maxopenparen);
6472 cur_eval = ST.prev_eval;
6473 cur_curlyx = ST.prev_curlyx;
6474 /* Invalidate cache. See "invalidate" comment above. */
6475 reginfo->poscache_maxiter = 0;
6476 if ( nochange_depth )
6482 n = ARG(scan); /* which paren pair */
6483 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
6484 if (n > maxopenparen)
6486 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
6487 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
6491 (IV)rex->offs[n].start_tmp,
6497 /* XXX really need to log other places start/end are set too */
6498 #define CLOSE_CAPTURE \
6499 rex->offs[n].start = rex->offs[n].start_tmp; \
6500 rex->offs[n].end = locinput - reginfo->strbeg; \
6501 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
6502 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
6504 PTR2UV(rex->offs), \
6506 (IV)rex->offs[n].start, \
6507 (IV)rex->offs[n].end \
6511 n = ARG(scan); /* which paren pair */
6513 if (n > rex->lastparen)
6515 rex->lastcloseparen = n;
6516 if (cur_eval && cur_eval->u.eval.close_paren == n) {
6521 case ACCEPT: /* (*ACCEPT) */
6525 cursor && OP(cursor)!=END;
6526 cursor=regnext(cursor))
6528 if ( OP(cursor)==CLOSE ){
6530 if ( n <= lastopen ) {
6532 if (n > rex->lastparen)
6534 rex->lastcloseparen = n;
6535 if ( n == ARG(scan) || (cur_eval &&
6536 cur_eval->u.eval.close_paren == n))
6545 case GROUPP: /* (?(1)) */
6546 n = ARG(scan); /* which paren pair */
6547 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
6550 case NGROUPP: /* (?(<name>)) */
6551 /* reg_check_named_buff_matched returns 0 for no match */
6552 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
6555 case INSUBP: /* (?(R)) */
6557 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
6560 case DEFINEP: /* (?(DEFINE)) */
6564 case IFTHEN: /* (?(cond)A|B) */
6565 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6567 next = NEXTOPER(NEXTOPER(scan));
6569 next = scan + ARG(scan);
6570 if (OP(next) == IFTHEN) /* Fake one. */
6571 next = NEXTOPER(NEXTOPER(next));
6575 case LOGICAL: /* modifier for EVAL and IFMATCH */
6576 logical = scan->flags;
6579 /*******************************************************************
6581 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
6582 pattern, where A and B are subpatterns. (For simple A, CURLYM or
6583 STAR/PLUS/CURLY/CURLYN are used instead.)
6585 A*B is compiled as <CURLYX><A><WHILEM><B>
6587 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
6588 state, which contains the current count, initialised to -1. It also sets
6589 cur_curlyx to point to this state, with any previous value saved in the
6592 CURLYX then jumps straight to the WHILEM op, rather than executing A,
6593 since the pattern may possibly match zero times (i.e. it's a while {} loop
6594 rather than a do {} while loop).
6596 Each entry to WHILEM represents a successful match of A. The count in the
6597 CURLYX block is incremented, another WHILEM state is pushed, and execution
6598 passes to A or B depending on greediness and the current count.
6600 For example, if matching against the string a1a2a3b (where the aN are
6601 substrings that match /A/), then the match progresses as follows: (the
6602 pushed states are interspersed with the bits of strings matched so far):
6605 <CURLYX cnt=0><WHILEM>
6606 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
6607 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
6608 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
6609 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
6611 (Contrast this with something like CURLYM, which maintains only a single
6615 a1 <CURLYM cnt=1> a2
6616 a1 a2 <CURLYM cnt=2> a3
6617 a1 a2 a3 <CURLYM cnt=3> b
6620 Each WHILEM state block marks a point to backtrack to upon partial failure
6621 of A or B, and also contains some minor state data related to that
6622 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
6623 overall state, such as the count, and pointers to the A and B ops.
6625 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
6626 must always point to the *current* CURLYX block, the rules are:
6628 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
6629 and set cur_curlyx to point the new block.
6631 When popping the CURLYX block after a successful or unsuccessful match,
6632 restore the previous cur_curlyx.
6634 When WHILEM is about to execute B, save the current cur_curlyx, and set it
6635 to the outer one saved in the CURLYX block.
6637 When popping the WHILEM block after a successful or unsuccessful B match,
6638 restore the previous cur_curlyx.
6640 Here's an example for the pattern (AI* BI)*BO
6641 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
6644 curlyx backtrack stack
6645 ------ ---------------
6647 CO <CO prev=NULL> <WO>
6648 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6649 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6650 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
6652 At this point the pattern succeeds, and we work back down the stack to
6653 clean up, restoring as we go:
6655 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6656 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6657 CO <CO prev=NULL> <WO>
6660 *******************************************************************/
6662 #define ST st->u.curlyx
6664 case CURLYX: /* start of /A*B/ (for complex A) */
6666 /* No need to save/restore up to this paren */
6667 I32 parenfloor = scan->flags;
6669 assert(next); /* keep Coverity happy */
6670 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
6673 /* XXXX Probably it is better to teach regpush to support
6674 parenfloor > maxopenparen ... */
6675 if (parenfloor > (I32)rex->lastparen)
6676 parenfloor = rex->lastparen; /* Pessimization... */
6678 ST.prev_curlyx= cur_curlyx;
6680 ST.cp = PL_savestack_ix;
6682 /* these fields contain the state of the current curly.
6683 * they are accessed by subsequent WHILEMs */
6684 ST.parenfloor = parenfloor;
6689 ST.count = -1; /* this will be updated by WHILEM */
6690 ST.lastloc = NULL; /* this will be updated by WHILEM */
6692 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
6694 NOT_REACHED; /* NOTREACHED */
6697 case CURLYX_end: /* just finished matching all of A*B */
6698 cur_curlyx = ST.prev_curlyx;
6701 NOT_REACHED; /* NOTREACHED */
6703 case CURLYX_end_fail: /* just failed to match all of A*B */
6705 cur_curlyx = ST.prev_curlyx;
6708 NOT_REACHED; /* NOTREACHED */
6712 #define ST st->u.whilem
6714 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
6716 /* see the discussion above about CURLYX/WHILEM */
6721 assert(cur_curlyx); /* keep Coverity happy */
6723 min = ARG1(cur_curlyx->u.curlyx.me);
6724 max = ARG2(cur_curlyx->u.curlyx.me);
6725 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
6726 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
6727 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
6728 ST.cache_offset = 0;
6732 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6733 "%*s whilem: matched %ld out of %d..%d\n",
6734 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
6737 /* First just match a string of min A's. */
6740 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6742 cur_curlyx->u.curlyx.lastloc = locinput;
6743 REGCP_SET(ST.lastcp);
6745 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
6747 NOT_REACHED; /* NOTREACHED */
6750 /* If degenerate A matches "", assume A done. */
6752 if (locinput == cur_curlyx->u.curlyx.lastloc) {
6753 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6754 "%*s whilem: empty match detected, trying continuation...\n",
6755 REPORT_CODE_OFF+depth*2, "")
6757 goto do_whilem_B_max;
6760 /* super-linear cache processing.
6762 * The idea here is that for certain types of CURLYX/WHILEM -
6763 * principally those whose upper bound is infinity (and
6764 * excluding regexes that have things like \1 and other very
6765 * non-regular expresssiony things), then if a pattern like
6766 * /....A*.../ fails and we backtrack to the WHILEM, then we
6767 * make a note that this particular WHILEM op was at string
6768 * position 47 (say) when the rest of pattern failed. Then, if
6769 * we ever find ourselves back at that WHILEM, and at string
6770 * position 47 again, we can just fail immediately rather than
6771 * running the rest of the pattern again.
6773 * This is very handy when patterns start to go
6774 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
6775 * with a combinatorial explosion of backtracking.
6777 * The cache is implemented as a bit array, with one bit per
6778 * string byte position per WHILEM op (up to 16) - so its
6779 * between 0.25 and 2x the string size.
6781 * To avoid allocating a poscache buffer every time, we do an
6782 * initially countdown; only after we have executed a WHILEM
6783 * op (string-length x #WHILEMs) times do we allocate the
6786 * The top 4 bits of scan->flags byte say how many different
6787 * relevant CURLLYX/WHILEM op pairs there are, while the
6788 * bottom 4-bits is the identifying index number of this
6794 if (!reginfo->poscache_maxiter) {
6795 /* start the countdown: Postpone detection until we
6796 * know the match is not *that* much linear. */
6797 reginfo->poscache_maxiter
6798 = (reginfo->strend - reginfo->strbeg + 1)
6800 /* possible overflow for long strings and many CURLYX's */
6801 if (reginfo->poscache_maxiter < 0)
6802 reginfo->poscache_maxiter = I32_MAX;
6803 reginfo->poscache_iter = reginfo->poscache_maxiter;
6806 if (reginfo->poscache_iter-- == 0) {
6807 /* initialise cache */
6808 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
6809 regmatch_info_aux *const aux = reginfo->info_aux;
6810 if (aux->poscache) {
6811 if ((SSize_t)reginfo->poscache_size < size) {
6812 Renew(aux->poscache, size, char);
6813 reginfo->poscache_size = size;
6815 Zero(aux->poscache, size, char);
6818 reginfo->poscache_size = size;
6819 Newxz(aux->poscache, size, char);
6821 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6822 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
6823 PL_colors[4], PL_colors[5])
6827 if (reginfo->poscache_iter < 0) {
6828 /* have we already failed at this position? */
6829 SSize_t offset, mask;
6831 reginfo->poscache_iter = -1; /* stop eventual underflow */
6832 offset = (scan->flags & 0xf) - 1
6833 + (locinput - reginfo->strbeg)
6835 mask = 1 << (offset % 8);
6837 if (reginfo->info_aux->poscache[offset] & mask) {
6838 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6839 "%*s whilem: (cache) already tried at this position...\n",
6840 REPORT_CODE_OFF+depth*2, "")
6842 sayNO; /* cache records failure */
6844 ST.cache_offset = offset;
6845 ST.cache_mask = mask;
6849 /* Prefer B over A for minimal matching. */
6851 if (cur_curlyx->u.curlyx.minmod) {
6852 ST.save_curlyx = cur_curlyx;
6853 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6854 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
6856 REGCP_SET(ST.lastcp);
6857 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
6860 NOT_REACHED; /* NOTREACHED */
6863 /* Prefer A over B for maximal matching. */
6865 if (n < max) { /* More greed allowed? */
6866 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6868 cur_curlyx->u.curlyx.lastloc = locinput;
6869 REGCP_SET(ST.lastcp);
6870 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
6872 NOT_REACHED; /* NOTREACHED */
6874 goto do_whilem_B_max;
6877 NOT_REACHED; /* NOTREACHED */
6879 case WHILEM_B_min: /* just matched B in a minimal match */
6880 case WHILEM_B_max: /* just matched B in a maximal match */
6881 cur_curlyx = ST.save_curlyx;
6884 NOT_REACHED; /* NOTREACHED */
6886 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
6887 cur_curlyx = ST.save_curlyx;
6888 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6889 cur_curlyx->u.curlyx.count--;
6892 NOT_REACHED; /* NOTREACHED */
6894 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
6896 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
6897 REGCP_UNWIND(ST.lastcp);
6898 regcppop(rex, &maxopenparen);
6899 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6900 cur_curlyx->u.curlyx.count--;
6903 NOT_REACHED; /* NOTREACHED */
6905 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
6906 REGCP_UNWIND(ST.lastcp);
6907 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
6908 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6909 "%*s whilem: failed, trying continuation...\n",
6910 REPORT_CODE_OFF+depth*2, "")
6913 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6914 && ckWARN(WARN_REGEXP)
6915 && !reginfo->warned)
6917 reginfo->warned = TRUE;
6918 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6919 "Complex regular subexpression recursion limit (%d) "
6925 ST.save_curlyx = cur_curlyx;
6926 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6927 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
6930 NOT_REACHED; /* NOTREACHED */
6932 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
6933 cur_curlyx = ST.save_curlyx;
6934 REGCP_UNWIND(ST.lastcp);
6935 regcppop(rex, &maxopenparen);
6937 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
6938 /* Maximum greed exceeded */
6939 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6940 && ckWARN(WARN_REGEXP)
6941 && !reginfo->warned)
6943 reginfo->warned = TRUE;
6944 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6945 "Complex regular subexpression recursion "
6946 "limit (%d) exceeded",
6949 cur_curlyx->u.curlyx.count--;
6953 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6954 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
6956 /* Try grabbing another A and see if it helps. */
6957 cur_curlyx->u.curlyx.lastloc = locinput;
6958 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6960 REGCP_SET(ST.lastcp);
6961 PUSH_STATE_GOTO(WHILEM_A_min,
6962 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6965 NOT_REACHED; /* NOTREACHED */
6968 #define ST st->u.branch
6970 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6971 next = scan + ARG(scan);
6974 scan = NEXTOPER(scan);
6977 case BRANCH: /* /(...|A|...)/ */
6978 scan = NEXTOPER(scan); /* scan now points to inner node */
6979 ST.lastparen = rex->lastparen;
6980 ST.lastcloseparen = rex->lastcloseparen;
6981 ST.next_branch = next;
6984 /* Now go into the branch */
6986 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
6988 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
6991 NOT_REACHED; /* NOTREACHED */
6993 case CUTGROUP: /* /(*THEN)/ */
6994 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
6995 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6996 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
6998 NOT_REACHED; /* NOTREACHED */
7000 case CUTGROUP_next_fail:
7003 if (st->u.mark.mark_name)
7004 sv_commit = st->u.mark.mark_name;
7007 NOT_REACHED; /* NOTREACHED */
7012 NOT_REACHED; /* NOTREACHED */
7014 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7019 REGCP_UNWIND(ST.cp);
7020 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7021 scan = ST.next_branch;
7022 /* no more branches? */
7023 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7025 PerlIO_printf( Perl_debug_log,
7026 "%*s %sBRANCH failed...%s\n",
7027 REPORT_CODE_OFF+depth*2, "",
7033 continue; /* execute next BRANCH[J] op */
7036 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7041 #define ST st->u.curlym
7043 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7045 /* This is an optimisation of CURLYX that enables us to push
7046 * only a single backtracking state, no matter how many matches
7047 * there are in {m,n}. It relies on the pattern being constant
7048 * length, with no parens to influence future backrefs
7052 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7054 ST.lastparen = rex->lastparen;
7055 ST.lastcloseparen = rex->lastcloseparen;
7057 /* if paren positive, emulate an OPEN/CLOSE around A */
7059 U32 paren = ST.me->flags;
7060 if (paren > maxopenparen)
7061 maxopenparen = paren;
7062 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7070 ST.c1 = CHRTEST_UNINIT;
7073 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7076 curlym_do_A: /* execute the A in /A{m,n}B/ */
7077 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7079 NOT_REACHED; /* NOTREACHED */
7081 case CURLYM_A: /* we've just matched an A */
7083 /* after first match, determine A's length: u.curlym.alen */
7084 if (ST.count == 1) {
7085 if (reginfo->is_utf8_target) {
7086 char *s = st->locinput;
7087 while (s < locinput) {
7093 ST.alen = locinput - st->locinput;
7096 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7099 PerlIO_printf(Perl_debug_log,
7100 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7101 (int)(REPORT_CODE_OFF+(depth*2)), "",
7102 (IV) ST.count, (IV)ST.alen)
7105 if (cur_eval && cur_eval->u.eval.close_paren &&
7106 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7110 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7111 if ( max == REG_INFTY || ST.count < max )
7112 goto curlym_do_A; /* try to match another A */
7114 goto curlym_do_B; /* try to match B */
7116 case CURLYM_A_fail: /* just failed to match an A */
7117 REGCP_UNWIND(ST.cp);
7119 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7120 || (cur_eval && cur_eval->u.eval.close_paren &&
7121 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7124 curlym_do_B: /* execute the B in /A{m,n}B/ */
7125 if (ST.c1 == CHRTEST_UNINIT) {
7126 /* calculate c1 and c2 for possible match of 1st char
7127 * following curly */
7128 ST.c1 = ST.c2 = CHRTEST_VOID;
7130 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7131 regnode *text_node = ST.B;
7132 if (! HAS_TEXT(text_node))
7133 FIND_NEXT_IMPT(text_node);
7136 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7138 But the former is redundant in light of the latter.
7140 if this changes back then the macro for
7141 IS_TEXT and friends need to change.
7143 if (PL_regkind[OP(text_node)] == EXACT) {
7144 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7145 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7155 PerlIO_printf(Perl_debug_log,
7156 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
7157 (int)(REPORT_CODE_OFF+(depth*2)),
7160 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7161 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7162 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7163 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7165 /* simulate B failing */
7167 PerlIO_printf(Perl_debug_log,
7168 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7169 (int)(REPORT_CODE_OFF+(depth*2)),"",
7170 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7171 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7172 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7174 state_num = CURLYM_B_fail;
7175 goto reenter_switch;
7178 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7179 /* simulate B failing */
7181 PerlIO_printf(Perl_debug_log,
7182 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7183 (int)(REPORT_CODE_OFF+(depth*2)),"",
7184 (int) nextchr, ST.c1, ST.c2)
7186 state_num = CURLYM_B_fail;
7187 goto reenter_switch;
7192 /* emulate CLOSE: mark current A as captured */
7193 I32 paren = ST.me->flags;
7195 rex->offs[paren].start
7196 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7197 rex->offs[paren].end = locinput - reginfo->strbeg;
7198 if ((U32)paren > rex->lastparen)
7199 rex->lastparen = paren;
7200 rex->lastcloseparen = paren;
7203 rex->offs[paren].end = -1;
7204 if (cur_eval && cur_eval->u.eval.close_paren &&
7205 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7214 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7216 NOT_REACHED; /* NOTREACHED */
7218 case CURLYM_B_fail: /* just failed to match a B */
7219 REGCP_UNWIND(ST.cp);
7220 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7222 I32 max = ARG2(ST.me);
7223 if (max != REG_INFTY && ST.count == max)
7225 goto curlym_do_A; /* try to match a further A */
7227 /* backtrack one A */
7228 if (ST.count == ARG1(ST.me) /* min */)
7231 SET_locinput(HOPc(locinput, -ST.alen));
7232 goto curlym_do_B; /* try to match B */
7235 #define ST st->u.curly
7237 #define CURLY_SETPAREN(paren, success) \
7240 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7241 rex->offs[paren].end = locinput - reginfo->strbeg; \
7242 if (paren > rex->lastparen) \
7243 rex->lastparen = paren; \
7244 rex->lastcloseparen = paren; \
7247 rex->offs[paren].end = -1; \
7248 rex->lastparen = ST.lastparen; \
7249 rex->lastcloseparen = ST.lastcloseparen; \
7253 case STAR: /* /A*B/ where A is width 1 char */
7257 scan = NEXTOPER(scan);
7260 case PLUS: /* /A+B/ where A is width 1 char */
7264 scan = NEXTOPER(scan);
7267 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7268 ST.paren = scan->flags; /* Which paren to set */
7269 ST.lastparen = rex->lastparen;
7270 ST.lastcloseparen = rex->lastcloseparen;
7271 if (ST.paren > maxopenparen)
7272 maxopenparen = ST.paren;
7273 ST.min = ARG1(scan); /* min to match */
7274 ST.max = ARG2(scan); /* max to match */
7275 if (cur_eval && cur_eval->u.eval.close_paren &&
7276 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7280 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7283 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7285 ST.min = ARG1(scan); /* min to match */
7286 ST.max = ARG2(scan); /* max to match */
7287 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7290 * Lookahead to avoid useless match attempts
7291 * when we know what character comes next.
7293 * Used to only do .*x and .*?x, but now it allows
7294 * for )'s, ('s and (?{ ... })'s to be in the way
7295 * of the quantifier and the EXACT-like node. -- japhy
7298 assert(ST.min <= ST.max);
7299 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7300 ST.c1 = ST.c2 = CHRTEST_VOID;
7303 regnode *text_node = next;
7305 if (! HAS_TEXT(text_node))
7306 FIND_NEXT_IMPT(text_node);
7308 if (! HAS_TEXT(text_node))
7309 ST.c1 = ST.c2 = CHRTEST_VOID;
7311 if ( PL_regkind[OP(text_node)] != EXACT ) {
7312 ST.c1 = ST.c2 = CHRTEST_VOID;
7316 /* Currently we only get here when
7318 PL_rekind[OP(text_node)] == EXACT
7320 if this changes back then the macro for IS_TEXT and
7321 friends need to change. */
7322 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7323 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7335 char *li = locinput;
7338 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7344 if (ST.c1 == CHRTEST_VOID)
7345 goto curly_try_B_min;
7347 ST.oldloc = locinput;
7349 /* set ST.maxpos to the furthest point along the
7350 * string that could possibly match */
7351 if (ST.max == REG_INFTY) {
7352 ST.maxpos = reginfo->strend - 1;
7354 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7357 else if (utf8_target) {
7358 int m = ST.max - ST.min;
7359 for (ST.maxpos = locinput;
7360 m >0 && ST.maxpos < reginfo->strend; m--)
7361 ST.maxpos += UTF8SKIP(ST.maxpos);
7364 ST.maxpos = locinput + ST.max - ST.min;
7365 if (ST.maxpos >= reginfo->strend)
7366 ST.maxpos = reginfo->strend - 1;
7368 goto curly_try_B_min_known;
7372 /* avoid taking address of locinput, so it can remain
7374 char *li = locinput;
7375 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7376 if (ST.count < ST.min)
7379 if ((ST.count > ST.min)
7380 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7382 /* A{m,n} must come at the end of the string, there's
7383 * no point in backing off ... */
7385 /* ...except that $ and \Z can match before *and* after
7386 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7387 We may back off by one in this case. */
7388 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7392 goto curly_try_B_max;
7395 NOT_REACHED; /* NOTREACHED */
7397 case CURLY_B_min_known_fail:
7398 /* failed to find B in a non-greedy match where c1,c2 valid */
7400 REGCP_UNWIND(ST.cp);
7402 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7404 /* Couldn't or didn't -- move forward. */
7405 ST.oldloc = locinput;
7407 locinput += UTF8SKIP(locinput);
7411 curly_try_B_min_known:
7412 /* find the next place where 'B' could work, then call B */
7416 n = (ST.oldloc == locinput) ? 0 : 1;
7417 if (ST.c1 == ST.c2) {
7418 /* set n to utf8_distance(oldloc, locinput) */
7419 while (locinput <= ST.maxpos
7420 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7422 locinput += UTF8SKIP(locinput);
7427 /* set n to utf8_distance(oldloc, locinput) */
7428 while (locinput <= ST.maxpos
7429 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7430 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7432 locinput += UTF8SKIP(locinput);
7437 else { /* Not utf8_target */
7438 if (ST.c1 == ST.c2) {
7439 while (locinput <= ST.maxpos &&
7440 UCHARAT(locinput) != ST.c1)
7444 while (locinput <= ST.maxpos
7445 && UCHARAT(locinput) != ST.c1
7446 && UCHARAT(locinput) != ST.c2)
7449 n = locinput - ST.oldloc;
7451 if (locinput > ST.maxpos)
7454 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7455 * at b; check that everything between oldloc and
7456 * locinput matches */
7457 char *li = ST.oldloc;
7459 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7461 assert(n == REG_INFTY || locinput == li);
7463 CURLY_SETPAREN(ST.paren, ST.count);
7464 if (cur_eval && cur_eval->u.eval.close_paren &&
7465 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7468 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7471 NOT_REACHED; /* NOTREACHED */
7473 case CURLY_B_min_fail:
7474 /* failed to find B in a non-greedy match where c1,c2 invalid */
7476 REGCP_UNWIND(ST.cp);
7478 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7480 /* failed -- move forward one */
7482 char *li = locinput;
7483 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7490 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7491 ST.count > 0)) /* count overflow ? */
7494 CURLY_SETPAREN(ST.paren, ST.count);
7495 if (cur_eval && cur_eval->u.eval.close_paren &&
7496 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7499 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7504 NOT_REACHED; /* NOTREACHED */
7507 /* a successful greedy match: now try to match B */
7508 if (cur_eval && cur_eval->u.eval.close_paren &&
7509 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7513 bool could_match = locinput < reginfo->strend;
7515 /* If it could work, try it. */
7516 if (ST.c1 != CHRTEST_VOID && could_match) {
7517 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7519 could_match = memEQ(locinput,
7524 UTF8SKIP(locinput));
7527 could_match = UCHARAT(locinput) == ST.c1
7528 || UCHARAT(locinput) == ST.c2;
7531 if (ST.c1 == CHRTEST_VOID || could_match) {
7532 CURLY_SETPAREN(ST.paren, ST.count);
7533 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7535 NOT_REACHED; /* NOTREACHED */
7540 case CURLY_B_max_fail:
7541 /* failed to find B in a greedy match */
7543 REGCP_UNWIND(ST.cp);
7545 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7548 if (--ST.count < ST.min)
7550 locinput = HOPc(locinput, -1);
7551 goto curly_try_B_max;
7555 case END: /* last op of main pattern */
7558 /* we've just finished A in /(??{A})B/; now continue with B */
7560 st->u.eval.prev_rex = rex_sv; /* inner */
7562 /* Save *all* the positions. */
7563 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7564 rex_sv = cur_eval->u.eval.prev_rex;
7565 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7566 SET_reg_curpm(rex_sv);
7567 rex = ReANY(rex_sv);
7568 rexi = RXi_GET(rex);
7569 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7571 REGCP_SET(st->u.eval.lastcp);
7573 /* Restore parens of the outer rex without popping the
7575 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7578 st->u.eval.prev_eval = cur_eval;
7579 cur_eval = cur_eval->u.eval.prev_eval;
7581 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
7582 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7583 if ( nochange_depth )
7586 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7587 locinput); /* match B */
7590 if (locinput < reginfo->till) {
7591 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7592 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7594 (long)(locinput - startpos),
7595 (long)(reginfo->till - startpos),
7598 sayNO_SILENT; /* Cannot match: too short. */
7600 sayYES; /* Success! */
7602 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7604 PerlIO_printf(Perl_debug_log,
7605 "%*s %ssubpattern success...%s\n",
7606 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7607 sayYES; /* Success! */
7610 #define ST st->u.ifmatch
7615 case SUSPEND: /* (?>A) */
7617 newstart = locinput;
7620 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
7622 goto ifmatch_trivial_fail_test;
7624 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
7626 ifmatch_trivial_fail_test:
7628 char * const s = HOPBACKc(locinput, scan->flags);
7633 sw = 1 - cBOOL(ST.wanted);
7637 next = scan + ARG(scan);
7645 newstart = locinput;
7649 ST.logical = logical;
7650 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
7652 /* execute body of (?...A) */
7653 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
7655 NOT_REACHED; /* NOTREACHED */
7658 case IFMATCH_A_fail: /* body of (?...A) failed */
7659 ST.wanted = !ST.wanted;
7662 case IFMATCH_A: /* body of (?...A) succeeded */
7664 sw = cBOOL(ST.wanted);
7666 else if (!ST.wanted)
7669 if (OP(ST.me) != SUSPEND) {
7670 /* restore old position except for (?>...) */
7671 locinput = st->locinput;
7673 scan = ST.me + ARG(ST.me);
7676 continue; /* execute B */
7680 case LONGJMP: /* alternative with many branches compiles to
7681 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
7682 next = scan + ARG(scan);
7687 case COMMIT: /* (*COMMIT) */
7688 reginfo->cutpoint = reginfo->strend;
7691 case PRUNE: /* (*PRUNE) */
7693 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7694 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
7696 NOT_REACHED; /* NOTREACHED */
7698 case COMMIT_next_fail:
7702 case OPFAIL: /* (*FAIL) */
7705 NOT_REACHED; /* NOTREACHED */
7707 #define ST st->u.mark
7708 case MARKPOINT: /* (*MARK:foo) */
7709 ST.prev_mark = mark_state;
7710 ST.mark_name = sv_commit = sv_yes_mark
7711 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7713 ST.mark_loc = locinput;
7714 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
7716 NOT_REACHED; /* NOTREACHED */
7718 case MARKPOINT_next:
7719 mark_state = ST.prev_mark;
7722 NOT_REACHED; /* NOTREACHED */
7724 case MARKPOINT_next_fail:
7725 if (popmark && sv_eq(ST.mark_name,popmark))
7727 if (ST.mark_loc > startpoint)
7728 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7729 popmark = NULL; /* we found our mark */
7730 sv_commit = ST.mark_name;
7733 PerlIO_printf(Perl_debug_log,
7734 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
7735 REPORT_CODE_OFF+depth*2, "",
7736 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
7739 mark_state = ST.prev_mark;
7740 sv_yes_mark = mark_state ?
7741 mark_state->u.mark.mark_name : NULL;
7744 NOT_REACHED; /* NOTREACHED */
7746 case SKIP: /* (*SKIP) */
7748 /* (*SKIP) : if we fail we cut here*/
7749 ST.mark_name = NULL;
7750 ST.mark_loc = locinput;
7751 PUSH_STATE_GOTO(SKIP_next,next, locinput);
7753 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
7754 otherwise do nothing. Meaning we need to scan
7756 regmatch_state *cur = mark_state;
7757 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7760 if ( sv_eq( cur->u.mark.mark_name,
7763 ST.mark_name = find;
7764 PUSH_STATE_GOTO( SKIP_next, next, locinput);
7766 cur = cur->u.mark.prev_mark;
7769 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
7772 case SKIP_next_fail:
7774 /* (*CUT:NAME) - Set up to search for the name as we
7775 collapse the stack*/
7776 popmark = ST.mark_name;
7778 /* (*CUT) - No name, we cut here.*/
7779 if (ST.mark_loc > startpoint)
7780 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7781 /* but we set sv_commit to latest mark_name if there
7782 is one so they can test to see how things lead to this
7785 sv_commit=mark_state->u.mark.mark_name;
7790 NOT_REACHED; /* NOTREACHED */
7793 case LNBREAK: /* \R */
7794 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
7801 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
7802 PTR2UV(scan), OP(scan));
7803 Perl_croak(aTHX_ "regexp memory corruption");
7805 /* this is a point to jump to in order to increment
7806 * locinput by one character */
7808 assert(!NEXTCHR_IS_EOS);
7810 locinput += PL_utf8skip[nextchr];
7811 /* locinput is allowed to go 1 char off the end, but not 2+ */
7812 if (locinput > reginfo->strend)
7821 /* switch break jumps here */
7822 scan = next; /* prepare to execute the next op and ... */
7823 continue; /* ... jump back to the top, reusing st */
7827 /* push a state that backtracks on success */
7828 st->u.yes.prev_yes_state = yes_state;
7832 /* push a new regex state, then continue at scan */
7834 regmatch_state *newst;
7837 regmatch_state *cur = st;
7838 regmatch_state *curyes = yes_state;
7840 regmatch_slab *slab = PL_regmatch_slab;
7841 for (;curd > -1;cur--,curd--) {
7842 if (cur < SLAB_FIRST(slab)) {
7844 cur = SLAB_LAST(slab);
7846 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
7847 REPORT_CODE_OFF + 2 + depth * 2,"",
7848 curd, PL_reg_name[cur->resume_state],
7849 (curyes == cur) ? "yes" : ""
7852 curyes = cur->u.yes.prev_yes_state;
7855 DEBUG_STATE_pp("push")
7858 st->locinput = locinput;
7860 if (newst > SLAB_LAST(PL_regmatch_slab))
7861 newst = S_push_slab(aTHX);
7862 PL_regmatch_state = newst;
7864 locinput = pushinput;
7872 * We get here only if there's trouble -- normally "case END" is
7873 * the terminating point.
7875 Perl_croak(aTHX_ "corrupted regexp pointers");
7878 NOT_REACHED; /* NOTREACHED */
7882 /* we have successfully completed a subexpression, but we must now
7883 * pop to the state marked by yes_state and continue from there */
7884 assert(st != yes_state);
7886 while (st != yes_state) {
7888 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7889 PL_regmatch_slab = PL_regmatch_slab->prev;
7890 st = SLAB_LAST(PL_regmatch_slab);
7894 DEBUG_STATE_pp("pop (no final)");
7896 DEBUG_STATE_pp("pop (yes)");
7902 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
7903 || yes_state > SLAB_LAST(PL_regmatch_slab))
7905 /* not in this slab, pop slab */
7906 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
7907 PL_regmatch_slab = PL_regmatch_slab->prev;
7908 st = SLAB_LAST(PL_regmatch_slab);
7910 depth -= (st - yes_state);
7913 yes_state = st->u.yes.prev_yes_state;
7914 PL_regmatch_state = st;
7917 locinput= st->locinput;
7918 state_num = st->resume_state + no_final;
7919 goto reenter_switch;
7922 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
7923 PL_colors[4], PL_colors[5]));
7925 if (reginfo->info_aux_eval) {
7926 /* each successfully executed (?{...}) block does the equivalent of
7927 * local $^R = do {...}
7928 * When popping the save stack, all these locals would be undone;
7929 * bypass this by setting the outermost saved $^R to the latest
7931 /* I dont know if this is needed or works properly now.
7932 * see code related to PL_replgv elsewhere in this file.
7935 if (oreplsv != GvSV(PL_replgv))
7936 sv_setsv(oreplsv, GvSV(PL_replgv));
7943 PerlIO_printf(Perl_debug_log,
7944 "%*s %sfailed...%s\n",
7945 REPORT_CODE_OFF+depth*2, "",
7946 PL_colors[4], PL_colors[5])
7958 /* there's a previous state to backtrack to */
7960 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7961 PL_regmatch_slab = PL_regmatch_slab->prev;
7962 st = SLAB_LAST(PL_regmatch_slab);
7964 PL_regmatch_state = st;
7965 locinput= st->locinput;
7967 DEBUG_STATE_pp("pop");
7969 if (yes_state == st)
7970 yes_state = st->u.yes.prev_yes_state;
7972 state_num = st->resume_state + 1; /* failure = success + 1 */
7973 goto reenter_switch;
7978 if (rex->intflags & PREGf_VERBARG_SEEN) {
7979 SV *sv_err = get_sv("REGERROR", 1);
7980 SV *sv_mrk = get_sv("REGMARK", 1);
7982 sv_commit = &PL_sv_no;
7984 sv_yes_mark = &PL_sv_yes;
7987 sv_commit = &PL_sv_yes;
7988 sv_yes_mark = &PL_sv_no;
7992 sv_setsv(sv_err, sv_commit);
7993 sv_setsv(sv_mrk, sv_yes_mark);
7997 if (last_pushed_cv) {
8000 PERL_UNUSED_VAR(SP);
8003 assert(!result || locinput - reginfo->strbeg >= 0);
8004 return result ? locinput - reginfo->strbeg : -1;
8008 - regrepeat - repeatedly match something simple, report how many
8010 * What 'simple' means is a node which can be the operand of a quantifier like
8013 * startposp - pointer a pointer to the start position. This is updated
8014 * to point to the byte following the highest successful
8016 * p - the regnode to be repeatedly matched against.
8017 * reginfo - struct holding match state, such as strend
8018 * max - maximum number of things to match.
8019 * depth - (for debugging) backtracking depth.
8022 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8023 regmatch_info *const reginfo, I32 max, int depth)
8025 char *scan; /* Pointer to current position in target string */
8027 char *loceol = reginfo->strend; /* local version */
8028 I32 hardcount = 0; /* How many matches so far */
8029 bool utf8_target = reginfo->is_utf8_target;
8030 unsigned int to_complement = 0; /* Invert the result? */
8032 _char_class_number classnum;
8034 PERL_UNUSED_ARG(depth);
8037 PERL_ARGS_ASSERT_REGREPEAT;
8040 if (max == REG_INFTY)
8042 else if (! utf8_target && loceol - scan > max)
8043 loceol = scan + max;
8045 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8046 * to the maximum of how far we should go in it (leaving it set to the real
8047 * end, if the maximum permissible would take us beyond that). This allows
8048 * us to make the loop exit condition that we haven't gone past <loceol> to
8049 * also mean that we haven't exceeded the max permissible count, saving a
8050 * test each time through the loop. But it assumes that the OP matches a
8051 * single byte, which is true for most of the OPs below when applied to a
8052 * non-UTF-8 target. Those relatively few OPs that don't have this
8053 * characteristic will have to compensate.
8055 * There is no adjustment for UTF-8 targets, as the number of bytes per
8056 * character varies. OPs will have to test both that the count is less
8057 * than the max permissible (using <hardcount> to keep track), and that we
8058 * are still within the bounds of the string (using <loceol>. A few OPs
8059 * match a single byte no matter what the encoding. They can omit the max
8060 * test if, for the UTF-8 case, they do the adjustment that was skipped
8063 * Thus, the code above sets things up for the common case; and exceptional
8064 * cases need extra work; the common case is to make sure <scan> doesn't
8065 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8066 * count doesn't exceed the maximum permissible */
8071 while (scan < loceol && hardcount < max && *scan != '\n') {
8072 scan += UTF8SKIP(scan);
8076 while (scan < loceol && *scan != '\n')
8082 while (scan < loceol && hardcount < max) {
8083 scan += UTF8SKIP(scan);
8091 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8092 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8093 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8097 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8101 /* Can use a simple loop if the pattern char to match on is invariant
8102 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8103 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8104 * true iff it doesn't matter if the argument is in UTF-8 or not */
8105 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8106 if (utf8_target && loceol - scan > max) {
8107 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8108 * since here, to match at all, 1 char == 1 byte */
8109 loceol = scan + max;
8111 while (scan < loceol && UCHARAT(scan) == c) {
8115 else if (reginfo->is_utf8_pat) {
8117 STRLEN scan_char_len;
8119 /* When both target and pattern are UTF-8, we have to do
8121 while (hardcount < max
8123 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8124 && memEQ(scan, STRING(p), scan_char_len))
8126 scan += scan_char_len;
8130 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8132 /* Target isn't utf8; convert the character in the UTF-8
8133 * pattern to non-UTF8, and do a simple loop */
8134 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8135 while (scan < loceol && UCHARAT(scan) == c) {
8138 } /* else pattern char is above Latin1, can't possibly match the
8143 /* Here, the string must be utf8; pattern isn't, and <c> is
8144 * different in utf8 than not, so can't compare them directly.
8145 * Outside the loop, find the two utf8 bytes that represent c, and
8146 * then look for those in sequence in the utf8 string */
8147 U8 high = UTF8_TWO_BYTE_HI(c);
8148 U8 low = UTF8_TWO_BYTE_LO(c);
8150 while (hardcount < max
8151 && scan + 1 < loceol
8152 && UCHARAT(scan) == high
8153 && UCHARAT(scan + 1) == low)
8161 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8162 assert(! reginfo->is_utf8_pat);
8165 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8169 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8170 utf8_flags = FOLDEQ_LOCALE;
8173 case EXACTF: /* This node only generated for non-utf8 patterns */
8174 assert(! reginfo->is_utf8_pat);
8179 if (! utf8_target) {
8182 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8183 | FOLDEQ_S2_FOLDS_SANE;
8188 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8192 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8194 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8196 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8199 if (c1 == CHRTEST_VOID) {
8200 /* Use full Unicode fold matching */
8201 char *tmpeol = reginfo->strend;
8202 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8203 while (hardcount < max
8204 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8205 STRING(p), NULL, pat_len,
8206 reginfo->is_utf8_pat, utf8_flags))
8209 tmpeol = reginfo->strend;
8213 else if (utf8_target) {
8215 while (scan < loceol
8217 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8219 scan += UTF8SKIP(scan);
8224 while (scan < loceol
8226 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8227 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8229 scan += UTF8SKIP(scan);
8234 else if (c1 == c2) {
8235 while (scan < loceol && UCHARAT(scan) == c1) {
8240 while (scan < loceol &&
8241 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8250 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8254 while (hardcount < max
8256 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8258 scan += UTF8SKIP(scan);
8262 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
8267 /* The argument (FLAGS) to all the POSIX node types is the class number */
8274 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8275 if (! utf8_target) {
8276 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8282 while (hardcount < max && scan < loceol
8283 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8286 scan += UTF8SKIP(scan);
8299 if (utf8_target && loceol - scan > max) {
8301 /* We didn't adjust <loceol> at the beginning of this routine
8302 * because is UTF-8, but it is actually ok to do so, since here, to
8303 * match, 1 char == 1 byte. */
8304 loceol = scan + max;
8306 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8319 if (! utf8_target) {
8320 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8326 /* The complement of something that matches only ASCII matches all
8327 * non-ASCII, plus everything in ASCII that isn't in the class. */
8328 while (hardcount < max && scan < loceol
8329 && (! isASCII_utf8(scan)
8330 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8332 scan += UTF8SKIP(scan);
8343 if (! utf8_target) {
8344 while (scan < loceol && to_complement
8345 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8352 classnum = (_char_class_number) FLAGS(p);
8353 if (classnum < _FIRST_NON_SWASH_CC) {
8355 /* Here, a swash is needed for above-Latin1 code points.
8356 * Process as many Latin1 code points using the built-in rules.
8357 * Go to another loop to finish processing upon encountering
8358 * the first Latin1 code point. We could do that in this loop
8359 * as well, but the other way saves having to test if the swash
8360 * has been loaded every time through the loop: extra space to
8362 while (hardcount < max && scan < loceol) {
8363 if (UTF8_IS_INVARIANT(*scan)) {
8364 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8371 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8372 if (! (to_complement
8373 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
8382 goto found_above_latin1;
8389 /* For these character classes, the knowledge of how to handle
8390 * every code point is compiled in to Perl via a macro. This
8391 * code is written for making the loops as tight as possible.
8392 * It could be refactored to save space instead */
8394 case _CC_ENUM_SPACE:
8395 while (hardcount < max
8397 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8399 scan += UTF8SKIP(scan);
8403 case _CC_ENUM_BLANK:
8404 while (hardcount < max
8406 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8408 scan += UTF8SKIP(scan);
8412 case _CC_ENUM_XDIGIT:
8413 while (hardcount < max
8415 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8417 scan += UTF8SKIP(scan);
8421 case _CC_ENUM_VERTSPACE:
8422 while (hardcount < max
8424 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8426 scan += UTF8SKIP(scan);
8430 case _CC_ENUM_CNTRL:
8431 while (hardcount < max
8433 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8435 scan += UTF8SKIP(scan);
8440 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8446 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
8448 /* Load the swash if not already present */
8449 if (! PL_utf8_swash_ptrs[classnum]) {
8450 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8451 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8455 PL_XPosix_ptrs[classnum], &flags);
8458 while (hardcount < max && scan < loceol
8459 && to_complement ^ cBOOL(_generic_utf8(
8462 swash_fetch(PL_utf8_swash_ptrs[classnum],
8466 scan += UTF8SKIP(scan);
8473 while (hardcount < max && scan < loceol &&
8474 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8479 /* LNBREAK can match one or two latin chars, which is ok, but we
8480 * have to use hardcount in this situation, and throw away the
8481 * adjustment to <loceol> done before the switch statement */
8482 loceol = reginfo->strend;
8483 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8492 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8506 /* These are all 0 width, so match right here or not at all. */
8510 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8512 NOT_REACHED; /* NOTREACHED */
8519 c = scan - *startposp;
8523 GET_RE_DEBUG_FLAGS_DECL;
8525 SV * const prop = sv_newmortal();
8526 regprop(prog, prop, p, reginfo, NULL);
8527 PerlIO_printf(Perl_debug_log,
8528 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
8529 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8537 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8539 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
8540 create a copy so that changes the caller makes won't change the shared one.
8541 If <altsvp> is non-null, will return NULL in it, for back-compat.
8544 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8546 PERL_ARGS_ASSERT_REGCLASS_SWASH;
8552 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8555 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8558 - reginclass - determine if a character falls into a character class
8560 n is the ANYOF-type regnode
8561 p is the target string
8562 p_end points to one byte beyond the end of the target string
8563 utf8_target tells whether p is in UTF-8.
8565 Returns true if matched; false otherwise.
8567 Note that this can be a synthetic start class, a combination of various
8568 nodes, so things you think might be mutually exclusive, such as locale,
8569 aren't. It can match both locale and non-locale
8574 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8577 const char flags = ANYOF_FLAGS(n);
8581 PERL_ARGS_ASSERT_REGINCLASS;
8583 /* If c is not already the code point, get it. Note that
8584 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8585 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8587 c = utf8n_to_uvchr(p, p_end - p, &c_len,
8588 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8589 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8590 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8591 * UTF8_ALLOW_FFFF */
8592 if (c_len == (STRLEN)-1)
8593 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8594 if (c > 255 && OP(n) == ANYOFL && ! is_ANYOF_SYNTHETIC(n)) {
8595 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8599 /* If this character is potentially in the bitmap, check it */
8600 if (c < NUM_ANYOF_CODE_POINTS) {
8601 if (ANYOF_BITMAP_TEST(n, c))
8603 else if ((flags & ANYOF_MATCHES_ALL_NON_UTF8_NON_ASCII)
8609 else if (flags & ANYOF_LOCALE_FLAGS) {
8610 if ((flags & ANYOF_LOC_FOLD)
8612 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
8616 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
8620 /* The data structure is arranged so bits 0, 2, 4, ... are set
8621 * if the class includes the Posix character class given by
8622 * bit/2; and 1, 3, 5, ... are set if the class includes the
8623 * complemented Posix class given by int(bit/2). So we loop
8624 * through the bits, each time changing whether we complement
8625 * the result or not. Suppose for the sake of illustration
8626 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
8627 * is set, it means there is a match for this ANYOF node if the
8628 * character is in the class given by the expression (0 / 2 = 0
8629 * = \w). If it is in that class, isFOO_lc() will return 1,
8630 * and since 'to_complement' is 0, the result will stay TRUE,
8631 * and we exit the loop. Suppose instead that bit 0 is 0, but
8632 * bit 1 is 1. That means there is a match if the character
8633 * matches \W. We won't bother to call isFOO_lc() on bit 0,
8634 * but will on bit 1. On the second iteration 'to_complement'
8635 * will be 1, so the exclusive or will reverse things, so we
8636 * are testing for \W. On the third iteration, 'to_complement'
8637 * will be 0, and we would be testing for \s; the fourth
8638 * iteration would test for \S, etc.
8640 * Note that this code assumes that all the classes are closed
8641 * under folding. For example, if a character matches \w, then
8642 * its fold does too; and vice versa. This should be true for
8643 * any well-behaved locale for all the currently defined Posix
8644 * classes, except for :lower: and :upper:, which are handled
8645 * by the pseudo-class :cased: which matches if either of the
8646 * other two does. To get rid of this assumption, an outer
8647 * loop could be used below to iterate over both the source
8648 * character, and its fold (if different) */
8651 int to_complement = 0;
8653 while (count < ANYOF_MAX) {
8654 if (ANYOF_POSIXL_TEST(n, count)
8655 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
8668 /* If the bitmap didn't (or couldn't) match, and something outside the
8669 * bitmap could match, try that. */
8671 if (c >= NUM_ANYOF_CODE_POINTS
8672 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
8674 match = TRUE; /* Everything above the bitmap matches */
8676 else if ((flags & ANYOF_HAS_NONBITMAP_NON_UTF8_MATCHES)
8677 || (utf8_target && (flags & ANYOF_HAS_UTF8_NONBITMAP_MATCHES))
8678 || ((flags & ANYOF_LOC_FOLD)
8679 && IN_UTF8_CTYPE_LOCALE
8680 && ARG(n) != ANYOF_ONLY_HAS_BITMAP))
8682 SV* only_utf8_locale = NULL;
8683 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
8684 &only_utf8_locale, NULL);
8690 } else { /* Convert to utf8 */
8691 utf8_p = utf8_buffer;
8692 append_utf8_from_native_byte(*p, &utf8_p);
8693 utf8_p = utf8_buffer;
8696 if (swash_fetch(sw, utf8_p, TRUE)) {
8700 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
8701 match = _invlist_contains_cp(only_utf8_locale, c);
8705 if (UNICODE_IS_SUPER(c)
8706 && (flags & ANYOF_WARN_SUPER)
8707 && ckWARN_d(WARN_NON_UNICODE))
8709 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
8710 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
8714 #if ANYOF_INVERT != 1
8715 /* Depending on compiler optimization cBOOL takes time, so if don't have to
8717 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
8720 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
8721 return (flags & ANYOF_INVERT) ^ match;
8725 S_reghop3(U8 *s, SSize_t off, const U8* lim)
8727 /* return the position 'off' UTF-8 characters away from 's', forward if
8728 * 'off' >= 0, backwards if negative. But don't go outside of position
8729 * 'lim', which better be < s if off < 0 */
8731 PERL_ARGS_ASSERT_REGHOP3;
8734 while (off-- && s < lim) {
8735 /* XXX could check well-formedness here */
8740 while (off++ && s > lim) {
8742 if (UTF8_IS_CONTINUED(*s)) {
8743 while (s > lim && UTF8_IS_CONTINUATION(*s))
8746 /* XXX could check well-formedness here */
8753 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
8755 PERL_ARGS_ASSERT_REGHOP4;
8758 while (off-- && s < rlim) {
8759 /* XXX could check well-formedness here */
8764 while (off++ && s > llim) {
8766 if (UTF8_IS_CONTINUED(*s)) {
8767 while (s > llim && UTF8_IS_CONTINUATION(*s))
8770 /* XXX could check well-formedness here */
8776 /* like reghop3, but returns NULL on overrun, rather than returning last
8780 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
8782 PERL_ARGS_ASSERT_REGHOPMAYBE3;
8785 while (off-- && s < lim) {
8786 /* XXX could check well-formedness here */
8793 while (off++ && s > lim) {
8795 if (UTF8_IS_CONTINUED(*s)) {
8796 while (s > lim && UTF8_IS_CONTINUATION(*s))
8799 /* XXX could check well-formedness here */
8808 /* when executing a regex that may have (?{}), extra stuff needs setting
8809 up that will be visible to the called code, even before the current
8810 match has finished. In particular:
8812 * $_ is localised to the SV currently being matched;
8813 * pos($_) is created if necessary, ready to be updated on each call-out
8815 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
8816 isn't set until the current pattern is successfully finished), so that
8817 $1 etc of the match-so-far can be seen;
8818 * save the old values of subbeg etc of the current regex, and set then
8819 to the current string (again, this is normally only done at the end
8824 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
8827 regexp *const rex = ReANY(reginfo->prog);
8828 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
8830 eval_state->rex = rex;
8833 /* Make $_ available to executed code. */
8834 if (reginfo->sv != DEFSV) {
8836 DEFSV_set(reginfo->sv);
8839 if (!(mg = mg_find_mglob(reginfo->sv))) {
8840 /* prepare for quick setting of pos */
8841 mg = sv_magicext_mglob(reginfo->sv);
8844 eval_state->pos_magic = mg;
8845 eval_state->pos = mg->mg_len;
8846 eval_state->pos_flags = mg->mg_flags;
8849 eval_state->pos_magic = NULL;
8851 if (!PL_reg_curpm) {
8852 /* PL_reg_curpm is a fake PMOP that we can attach the current
8853 * regex to and point PL_curpm at, so that $1 et al are visible
8854 * within a /(?{})/. It's just allocated once per interpreter the
8855 * first time its needed */
8856 Newxz(PL_reg_curpm, 1, PMOP);
8859 SV* const repointer = &PL_sv_undef;
8860 /* this regexp is also owned by the new PL_reg_curpm, which
8861 will try to free it. */
8862 av_push(PL_regex_padav, repointer);
8863 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
8864 PL_regex_pad = AvARRAY(PL_regex_padav);
8868 SET_reg_curpm(reginfo->prog);
8869 eval_state->curpm = PL_curpm;
8870 PL_curpm = PL_reg_curpm;
8871 if (RXp_MATCH_COPIED(rex)) {
8872 /* Here is a serious problem: we cannot rewrite subbeg,
8873 since it may be needed if this match fails. Thus
8874 $` inside (?{}) could fail... */
8875 eval_state->subbeg = rex->subbeg;
8876 eval_state->sublen = rex->sublen;
8877 eval_state->suboffset = rex->suboffset;
8878 eval_state->subcoffset = rex->subcoffset;
8880 eval_state->saved_copy = rex->saved_copy;
8882 RXp_MATCH_COPIED_off(rex);
8885 eval_state->subbeg = NULL;
8886 rex->subbeg = (char *)reginfo->strbeg;
8888 rex->subcoffset = 0;
8889 rex->sublen = reginfo->strend - reginfo->strbeg;
8893 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8896 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8898 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8899 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8902 Safefree(aux->poscache);
8906 /* undo the effects of S_setup_eval_state() */
8908 if (eval_state->subbeg) {
8909 regexp * const rex = eval_state->rex;
8910 rex->subbeg = eval_state->subbeg;
8911 rex->sublen = eval_state->sublen;
8912 rex->suboffset = eval_state->suboffset;
8913 rex->subcoffset = eval_state->subcoffset;
8915 rex->saved_copy = eval_state->saved_copy;
8917 RXp_MATCH_COPIED_on(rex);
8919 if (eval_state->pos_magic)
8921 eval_state->pos_magic->mg_len = eval_state->pos;
8922 eval_state->pos_magic->mg_flags =
8923 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8924 | (eval_state->pos_flags & MGf_BYTES);
8927 PL_curpm = eval_state->curpm;
8930 PL_regmatch_state = aux->old_regmatch_state;
8931 PL_regmatch_slab = aux->old_regmatch_slab;
8933 /* free all slabs above current one - this must be the last action
8934 * of this function, as aux and eval_state are allocated within
8935 * slabs and may be freed here */
8937 s = PL_regmatch_slab->next;
8939 PL_regmatch_slab->next = NULL;
8941 regmatch_slab * const osl = s;
8950 S_to_utf8_substr(pTHX_ regexp *prog)
8952 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8953 * on the converted value */
8957 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8960 if (prog->substrs->data[i].substr
8961 && !prog->substrs->data[i].utf8_substr) {
8962 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8963 prog->substrs->data[i].utf8_substr = sv;
8964 sv_utf8_upgrade(sv);
8965 if (SvVALID(prog->substrs->data[i].substr)) {
8966 if (SvTAIL(prog->substrs->data[i].substr)) {
8967 /* Trim the trailing \n that fbm_compile added last
8969 SvCUR_set(sv, SvCUR(sv) - 1);
8970 /* Whilst this makes the SV technically "invalid" (as its
8971 buffer is no longer followed by "\0") when fbm_compile()
8972 adds the "\n" back, a "\0" is restored. */
8973 fbm_compile(sv, FBMcf_TAIL);
8977 if (prog->substrs->data[i].substr == prog->check_substr)
8978 prog->check_utf8 = sv;
8984 S_to_byte_substr(pTHX_ regexp *prog)
8986 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8987 * on the converted value; returns FALSE if can't be converted. */
8991 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8994 if (prog->substrs->data[i].utf8_substr
8995 && !prog->substrs->data[i].substr) {
8996 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
8997 if (! sv_utf8_downgrade(sv, TRUE)) {
9000 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9001 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9002 /* Trim the trailing \n that fbm_compile added last
9004 SvCUR_set(sv, SvCUR(sv) - 1);
9005 fbm_compile(sv, FBMcf_TAIL);
9009 prog->substrs->data[i].substr = sv;
9010 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9011 prog->check_substr = sv;
9019 * ex: set ts=8 sts=4 sw=4 et: