5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
89 static const char utf8_locale_required[] =
90 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
93 /* At least one required character in the target string is expressible only in
95 static const char* const non_utf8_target_but_utf8_required
96 = "Can't match, because target string needs to be in UTF-8\n";
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
107 #define STATIC static
110 /* Valid only if 'c', the character being looke-up, is an invariant under
111 * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
112 * everything matchable is straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c,u) (ANYOF_FLAGS(p) \
114 ? reginclass(prog,p,c,c+1,u) \
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, (SSize_t)0-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_SMALL_LIGATURE_LONG_S_T_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 && \
217 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
219 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
220 OP(rn) == PLUS || OP(rn) == MINMOD || \
222 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
224 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
226 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
229 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
230 we don't need this definition. XXX These are now out-of-sync*/
231 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
232 #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 )
233 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
236 /* ... so we use this as its faster. */
237 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
238 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
239 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
240 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
245 Search for mandatory following text node; for lookahead, the text must
246 follow but for lookbehind (rn->flags != 0) we skip to the next step.
248 #define FIND_NEXT_IMPT(rn) STMT_START { \
249 while (JUMPABLE(rn)) { \
250 const OPCODE type = OP(rn); \
251 if (type == SUSPEND || PL_regkind[type] == CURLY) \
252 rn = NEXTOPER(NEXTOPER(rn)); \
253 else if (type == PLUS) \
255 else if (type == IFMATCH) \
256 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
257 else rn += NEXT_OFF(rn); \
261 #define SLAB_FIRST(s) (&(s)->states[0])
262 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
264 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
265 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
266 static regmatch_state * S_push_slab(pTHX);
268 #define REGCP_PAREN_ELEMS 3
269 #define REGCP_OTHER_ELEMS 3
270 #define REGCP_FRAME_ELEMS 1
271 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
272 * are needed for the regexp context stack bookkeeping. */
275 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
277 const int retval = PL_savestack_ix;
278 const int paren_elems_to_push =
279 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
280 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
281 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
283 GET_RE_DEBUG_FLAGS_DECL;
285 PERL_ARGS_ASSERT_REGCPPUSH;
287 if (paren_elems_to_push < 0)
288 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
289 (int)paren_elems_to_push, (int)maxopenparen,
290 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
292 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
293 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
294 " out of range (%lu-%ld)",
296 (unsigned long)maxopenparen,
299 SSGROW(total_elems + REGCP_FRAME_ELEMS);
302 if ((int)maxopenparen > (int)parenfloor)
303 Perl_re_printf( aTHX_
304 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
309 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
310 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
311 SSPUSHIV(rex->offs[p].end);
312 SSPUSHIV(rex->offs[p].start);
313 SSPUSHINT(rex->offs[p].start_tmp);
314 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
315 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
317 (IV)rex->offs[p].start,
318 (IV)rex->offs[p].start_tmp,
322 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
323 SSPUSHINT(maxopenparen);
324 SSPUSHINT(rex->lastparen);
325 SSPUSHINT(rex->lastcloseparen);
326 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
331 /* These are needed since we do not localize EVAL nodes: */
332 #define REGCP_SET(cp) \
334 Perl_re_exec_indentf( aTHX_ \
335 "Setting an EVAL scope, savestack=%"IVdf",\n", \
336 depth, (IV)PL_savestack_ix \
341 #define REGCP_UNWIND(cp) \
343 if (cp != PL_savestack_ix) \
344 Perl_re_exec_indentf( aTHX_ \
345 "Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n",\
346 depth, (IV)(cp), (IV)PL_savestack_ix \
351 #define UNWIND_PAREN(lp, lcp) \
352 for (n = rex->lastparen; n > lp; n--) \
353 rex->offs[n].end = -1; \
354 rex->lastparen = n; \
355 rex->lastcloseparen = lcp;
359 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
363 GET_RE_DEBUG_FLAGS_DECL;
365 PERL_ARGS_ASSERT_REGCPPOP;
367 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
369 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
370 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
371 rex->lastcloseparen = SSPOPINT;
372 rex->lastparen = SSPOPINT;
373 *maxopenparen_p = SSPOPINT;
375 i -= REGCP_OTHER_ELEMS;
376 /* Now restore the parentheses context. */
378 if (i || rex->lastparen + 1 <= rex->nparens)
379 Perl_re_printf( aTHX_
380 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
385 paren = *maxopenparen_p;
386 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
388 rex->offs[paren].start_tmp = SSPOPINT;
389 rex->offs[paren].start = SSPOPIV;
391 if (paren <= rex->lastparen)
392 rex->offs[paren].end = tmps;
393 DEBUG_BUFFERS_r( Perl_re_printf( aTHX_
394 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
396 (IV)rex->offs[paren].start,
397 (IV)rex->offs[paren].start_tmp,
398 (IV)rex->offs[paren].end,
399 (paren > rex->lastparen ? "(skipped)" : ""));
404 /* It would seem that the similar code in regtry()
405 * already takes care of this, and in fact it is in
406 * a better location to since this code can #if 0-ed out
407 * but the code in regtry() is needed or otherwise tests
408 * requiring null fields (pat.t#187 and split.t#{13,14}
409 * (as of patchlevel 7877) will fail. Then again,
410 * this code seems to be necessary or otherwise
411 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
412 * --jhi updated by dapm */
413 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
414 if (i > *maxopenparen_p)
415 rex->offs[i].start = -1;
416 rex->offs[i].end = -1;
417 DEBUG_BUFFERS_r( Perl_re_printf( aTHX_
418 " \\%"UVuf": %s ..-1 undeffing\n",
420 (i > *maxopenparen_p) ? "-1" : " "
426 /* restore the parens and associated vars at savestack position ix,
427 * but without popping the stack */
430 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
432 I32 tmpix = PL_savestack_ix;
433 PL_savestack_ix = ix;
434 regcppop(rex, maxopenparen_p);
435 PL_savestack_ix = tmpix;
438 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
441 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
443 /* Returns a boolean as to whether or not 'character' is a member of the
444 * Posix character class given by 'classnum' that should be equivalent to a
445 * value in the typedef '_char_class_number'.
447 * Ideally this could be replaced by a just an array of function pointers
448 * to the C library functions that implement the macros this calls.
449 * However, to compile, the precise function signatures are required, and
450 * these may vary from platform to to platform. To avoid having to figure
451 * out what those all are on each platform, I (khw) am using this method,
452 * which adds an extra layer of function call overhead (unless the C
453 * optimizer strips it away). But we don't particularly care about
454 * performance with locales anyway. */
456 switch ((_char_class_number) classnum) {
457 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
458 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
459 case _CC_ENUM_ASCII: return isASCII_LC(character);
460 case _CC_ENUM_BLANK: return isBLANK_LC(character);
461 case _CC_ENUM_CASED: return isLOWER_LC(character)
462 || isUPPER_LC(character);
463 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
464 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
465 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
466 case _CC_ENUM_LOWER: return isLOWER_LC(character);
467 case _CC_ENUM_PRINT: return isPRINT_LC(character);
468 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
469 case _CC_ENUM_SPACE: return isSPACE_LC(character);
470 case _CC_ENUM_UPPER: return isUPPER_LC(character);
471 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
472 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
473 default: /* VERTSPACE should never occur in locales */
474 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
477 NOT_REACHED; /* NOTREACHED */
482 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
484 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
485 * 'character' is a member of the Posix character class given by 'classnum'
486 * that should be equivalent to a value in the typedef
487 * '_char_class_number'.
489 * This just calls isFOO_lc on the code point for the character if it is in
490 * the range 0-255. Outside that range, all characters use Unicode
491 * rules, ignoring any locale. So use the Unicode function if this class
492 * requires a swash, and use the Unicode macro otherwise. */
494 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
496 if (UTF8_IS_INVARIANT(*character)) {
497 return isFOO_lc(classnum, *character);
499 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
500 return isFOO_lc(classnum,
501 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
504 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
506 if (classnum < _FIRST_NON_SWASH_CC) {
508 /* Initialize the swash unless done already */
509 if (! PL_utf8_swash_ptrs[classnum]) {
510 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
511 PL_utf8_swash_ptrs[classnum] =
512 _core_swash_init("utf8",
515 PL_XPosix_ptrs[classnum], &flags);
518 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
520 TRUE /* is UTF */ ));
523 switch ((_char_class_number) classnum) {
524 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
525 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
526 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
527 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
531 return FALSE; /* Things like CNTRL are always below 256 */
535 * pregexec and friends
538 #ifndef PERL_IN_XSUB_RE
540 - pregexec - match a regexp against a string
543 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
544 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
545 /* stringarg: the point in the string at which to begin matching */
546 /* strend: pointer to null at end of string */
547 /* strbeg: real beginning of string */
548 /* minend: end of match must be >= minend bytes after stringarg. */
549 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
550 * itself is accessed via the pointers above */
551 /* nosave: For optimizations. */
553 PERL_ARGS_ASSERT_PREGEXEC;
556 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
557 nosave ? 0 : REXEC_COPY_STR);
563 /* re_intuit_start():
565 * Based on some optimiser hints, try to find the earliest position in the
566 * string where the regex could match.
568 * rx: the regex to match against
569 * sv: the SV being matched: only used for utf8 flag; the string
570 * itself is accessed via the pointers below. Note that on
571 * something like an overloaded SV, SvPOK(sv) may be false
572 * and the string pointers may point to something unrelated to
574 * strbeg: real beginning of string
575 * strpos: the point in the string at which to begin matching
576 * strend: pointer to the byte following the last char of the string
577 * flags currently unused; set to 0
578 * data: currently unused; set to NULL
580 * The basic idea of re_intuit_start() is to use some known information
581 * about the pattern, namely:
583 * a) the longest known anchored substring (i.e. one that's at a
584 * constant offset from the beginning of the pattern; but not
585 * necessarily at a fixed offset from the beginning of the
587 * b) the longest floating substring (i.e. one that's not at a constant
588 * offset from the beginning of the pattern);
589 * c) Whether the pattern is anchored to the string; either
590 * an absolute anchor: /^../, or anchored to \n: /^.../m,
591 * or anchored to pos(): /\G/;
592 * d) A start class: a real or synthetic character class which
593 * represents which characters are legal at the start of the pattern;
595 * to either quickly reject the match, or to find the earliest position
596 * within the string at which the pattern might match, thus avoiding
597 * running the full NFA engine at those earlier locations, only to
598 * eventually fail and retry further along.
600 * Returns NULL if the pattern can't match, or returns the address within
601 * the string which is the earliest place the match could occur.
603 * The longest of the anchored and floating substrings is called 'check'
604 * and is checked first. The other is called 'other' and is checked
605 * second. The 'other' substring may not be present. For example,
607 * /(abc|xyz)ABC\d{0,3}DEFG/
611 * check substr (float) = "DEFG", offset 6..9 chars
612 * other substr (anchored) = "ABC", offset 3..3 chars
615 * Be aware that during the course of this function, sometimes 'anchored'
616 * refers to a substring being anchored relative to the start of the
617 * pattern, and sometimes to the pattern itself being anchored relative to
618 * the string. For example:
620 * /\dabc/: "abc" is anchored to the pattern;
621 * /^\dabc/: "abc" is anchored to the pattern and the string;
622 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
623 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
624 * but the pattern is anchored to the string.
628 Perl_re_intuit_start(pTHX_
631 const char * const strbeg,
635 re_scream_pos_data *data)
637 struct regexp *const prog = ReANY(rx);
638 SSize_t start_shift = prog->check_offset_min;
639 /* Should be nonnegative! */
640 SSize_t end_shift = 0;
641 /* current lowest pos in string where the regex can start matching */
642 char *rx_origin = strpos;
644 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
645 U8 other_ix = 1 - prog->substrs->check_ix;
647 char *other_last = strpos;/* latest pos 'other' substr already checked to */
648 char *check_at = NULL; /* check substr found at this pos */
649 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
650 RXi_GET_DECL(prog,progi);
651 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
652 regmatch_info *const reginfo = ®info_buf;
653 GET_RE_DEBUG_FLAGS_DECL;
655 PERL_ARGS_ASSERT_RE_INTUIT_START;
656 PERL_UNUSED_ARG(flags);
657 PERL_UNUSED_ARG(data);
659 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
660 "Intuit: trying to determine minimum start position...\n"));
662 /* for now, assume that all substr offsets are positive. If at some point
663 * in the future someone wants to do clever things with lookbehind and
664 * -ve offsets, they'll need to fix up any code in this function
665 * which uses these offsets. See the thread beginning
666 * <20140113145929.GF27210@iabyn.com>
668 assert(prog->substrs->data[0].min_offset >= 0);
669 assert(prog->substrs->data[0].max_offset >= 0);
670 assert(prog->substrs->data[1].min_offset >= 0);
671 assert(prog->substrs->data[1].max_offset >= 0);
672 assert(prog->substrs->data[2].min_offset >= 0);
673 assert(prog->substrs->data[2].max_offset >= 0);
675 /* for now, assume that if both present, that the floating substring
676 * doesn't start before the anchored substring.
677 * If you break this assumption (e.g. doing better optimisations
678 * with lookahead/behind), then you'll need to audit the code in this
679 * function carefully first
682 ! ( (prog->anchored_utf8 || prog->anchored_substr)
683 && (prog->float_utf8 || prog->float_substr))
684 || (prog->float_min_offset >= prog->anchored_offset));
686 /* byte rather than char calculation for efficiency. It fails
687 * to quickly reject some cases that can't match, but will reject
688 * them later after doing full char arithmetic */
689 if (prog->minlen > strend - strpos) {
690 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
691 " String too short...\n"));
695 RX_MATCH_UTF8_set(rx,utf8_target);
696 reginfo->is_utf8_target = cBOOL(utf8_target);
697 reginfo->info_aux = NULL;
698 reginfo->strbeg = strbeg;
699 reginfo->strend = strend;
700 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
702 /* not actually used within intuit, but zero for safety anyway */
703 reginfo->poscache_maxiter = 0;
706 if (!prog->check_utf8 && prog->check_substr)
707 to_utf8_substr(prog);
708 check = prog->check_utf8;
710 if (!prog->check_substr && prog->check_utf8) {
711 if (! to_byte_substr(prog)) {
712 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
715 check = prog->check_substr;
718 /* dump the various substring data */
719 DEBUG_OPTIMISE_MORE_r({
721 for (i=0; i<=2; i++) {
722 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
723 : prog->substrs->data[i].substr);
727 Perl_re_printf( aTHX_
728 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
729 " useful=%"IVdf" utf8=%d [%s]\n",
731 (IV)prog->substrs->data[i].min_offset,
732 (IV)prog->substrs->data[i].max_offset,
733 (IV)prog->substrs->data[i].end_shift,
740 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
742 /* ml_anch: check after \n?
744 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
745 * with /.*.../, these flags will have been added by the
747 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
748 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
750 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
751 && !(prog->intflags & PREGf_IMPLICIT);
753 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
754 /* we are only allowed to match at BOS or \G */
756 /* trivially reject if there's a BOS anchor and we're not at BOS.
758 * Note that we don't try to do a similar quick reject for
759 * \G, since generally the caller will have calculated strpos
760 * based on pos() and gofs, so the string is already correctly
761 * anchored by definition; and handling the exceptions would
762 * be too fiddly (e.g. REXEC_IGNOREPOS).
764 if ( strpos != strbeg
765 && (prog->intflags & PREGf_ANCH_SBOL))
767 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
768 " Not at start...\n"));
772 /* in the presence of an anchor, the anchored (relative to the
773 * start of the regex) substr must also be anchored relative
774 * to strpos. So quickly reject if substr isn't found there.
775 * This works for \G too, because the caller will already have
776 * subtracted gofs from pos, and gofs is the offset from the
777 * \G to the start of the regex. For example, in /.abc\Gdef/,
778 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
779 * caller will have set strpos=pos()-4; we look for the substr
780 * at position pos()-4+1, which lines up with the "a" */
782 if (prog->check_offset_min == prog->check_offset_max) {
783 /* Substring at constant offset from beg-of-str... */
784 SSize_t slen = SvCUR(check);
785 char *s = HOP3c(strpos, prog->check_offset_min, strend);
787 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
788 " Looking for check substr at fixed offset %"IVdf"...\n",
789 (IV)prog->check_offset_min));
792 /* In this case, the regex is anchored at the end too.
793 * Unless it's a multiline match, the lengths must match
794 * exactly, give or take a \n. NB: slen >= 1 since
795 * the last char of check is \n */
797 && ( strend - s > slen
798 || strend - s < slen - 1
799 || (strend - s == slen && strend[-1] != '\n')))
801 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
802 " String too long...\n"));
805 /* Now should match s[0..slen-2] */
808 if (slen && (*SvPVX_const(check) != *s
809 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
811 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
812 " String not equal...\n"));
817 goto success_at_start;
822 end_shift = prog->check_end_shift;
824 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
826 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
827 (IV)end_shift, RX_PRECOMP(prog));
832 /* This is the (re)entry point of the main loop in this function.
833 * The goal of this loop is to:
834 * 1) find the "check" substring in the region rx_origin..strend
835 * (adjusted by start_shift / end_shift). If not found, reject
837 * 2) If it exists, look for the "other" substr too if defined; for
838 * example, if the check substr maps to the anchored substr, then
839 * check the floating substr, and vice-versa. If not found, go
840 * back to (1) with rx_origin suitably incremented.
841 * 3) If we find an rx_origin position that doesn't contradict
842 * either of the substrings, then check the possible additional
843 * constraints on rx_origin of /^.../m or a known start class.
844 * If these fail, then depending on which constraints fail, jump
845 * back to here, or to various other re-entry points further along
846 * that skip some of the first steps.
847 * 4) If we pass all those tests, update the BmUSEFUL() count on the
848 * substring. If the start position was determined to be at the
849 * beginning of the string - so, not rejected, but not optimised,
850 * since we have to run regmatch from position 0 - decrement the
851 * BmUSEFUL() count. Otherwise increment it.
855 /* first, look for the 'check' substring */
861 DEBUG_OPTIMISE_MORE_r({
862 Perl_re_printf( aTHX_
863 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
864 " Start shift: %"IVdf" End shift %"IVdf
865 " Real end Shift: %"IVdf"\n",
866 (IV)(rx_origin - strbeg),
867 (IV)prog->check_offset_min,
870 (IV)prog->check_end_shift);
873 end_point = HOP3(strend, -end_shift, strbeg);
874 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
879 /* If the regex is absolutely anchored to either the start of the
880 * string (SBOL) or to pos() (ANCH_GPOS), then
881 * check_offset_max represents an upper bound on the string where
882 * the substr could start. For the ANCH_GPOS case, we assume that
883 * the caller of intuit will have already set strpos to
884 * pos()-gofs, so in this case strpos + offset_max will still be
885 * an upper bound on the substr.
888 && prog->intflags & PREGf_ANCH
889 && prog->check_offset_max != SSize_t_MAX)
891 SSize_t len = SvCUR(check) - !!SvTAIL(check);
892 const char * const anchor =
893 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
895 /* do a bytes rather than chars comparison. It's conservative;
896 * so it skips doing the HOP if the result can't possibly end
897 * up earlier than the old value of end_point.
899 if ((char*)end_point - anchor > prog->check_offset_max) {
900 end_point = HOP3lim((U8*)anchor,
901 prog->check_offset_max,
907 check_at = fbm_instr( start_point, end_point,
908 check, multiline ? FBMrf_MULTILINE : 0);
910 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
911 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
912 (IV)((char*)start_point - strbeg),
913 (IV)((char*)end_point - strbeg),
914 (IV)(check_at ? check_at - strbeg : -1)
917 /* Update the count-of-usability, remove useless subpatterns,
921 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
922 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
923 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
924 (check_at ? "Found" : "Did not find"),
925 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
926 ? "anchored" : "floating"),
929 (check_at ? " at offset " : "...\n") );
934 /* set rx_origin to the minimum position where the regex could start
935 * matching, given the constraint of the just-matched check substring.
936 * But don't set it lower than previously.
939 if (check_at - rx_origin > prog->check_offset_max)
940 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
941 /* Finish the diagnostic message */
942 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
943 "%ld (rx_origin now %"IVdf")...\n",
944 (long)(check_at - strbeg),
945 (IV)(rx_origin - strbeg)
950 /* now look for the 'other' substring if defined */
952 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
953 : prog->substrs->data[other_ix].substr)
955 /* Take into account the "other" substring. */
959 struct reg_substr_datum *other;
962 other = &prog->substrs->data[other_ix];
964 /* if "other" is anchored:
965 * we've previously found a floating substr starting at check_at.
966 * This means that the regex origin must lie somewhere
967 * between min (rx_origin): HOP3(check_at, -check_offset_max)
968 * and max: HOP3(check_at, -check_offset_min)
969 * (except that min will be >= strpos)
970 * So the fixed substr must lie somewhere between
971 * HOP3(min, anchored_offset)
972 * HOP3(max, anchored_offset) + SvCUR(substr)
975 /* if "other" is floating
976 * Calculate last1, the absolute latest point where the
977 * floating substr could start in the string, ignoring any
978 * constraints from the earlier fixed match. It is calculated
981 * strend - prog->minlen (in chars) is the absolute latest
982 * position within the string where the origin of the regex
983 * could appear. The latest start point for the floating
984 * substr is float_min_offset(*) on from the start of the
985 * regex. last1 simply combines thee two offsets.
987 * (*) You might think the latest start point should be
988 * float_max_offset from the regex origin, and technically
989 * you'd be correct. However, consider
991 * Here, float min, max are 3,5 and minlen is 7.
992 * This can match either
996 * In the first case, the regex matches minlen chars; in the
997 * second, minlen+1, in the third, minlen+2.
998 * In the first case, the floating offset is 3 (which equals
999 * float_min), in the second, 4, and in the third, 5 (which
1000 * equals float_max). In all cases, the floating string bcd
1001 * can never start more than 4 chars from the end of the
1002 * string, which equals minlen - float_min. As the substring
1003 * starts to match more than float_min from the start of the
1004 * regex, it makes the regex match more than minlen chars,
1005 * and the two cancel each other out. So we can always use
1006 * float_min - minlen, rather than float_max - minlen for the
1007 * latest position in the string.
1009 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1010 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1013 assert(prog->minlen >= other->min_offset);
1014 last1 = HOP3c(strend,
1015 other->min_offset - prog->minlen, strbeg);
1017 if (other_ix) {/* i.e. if (other-is-float) */
1018 /* last is the latest point where the floating substr could
1019 * start, *given* any constraints from the earlier fixed
1020 * match. This constraint is that the floating string starts
1021 * <= float_max_offset chars from the regex origin (rx_origin).
1022 * If this value is less than last1, use it instead.
1024 assert(rx_origin <= last1);
1026 /* this condition handles the offset==infinity case, and
1027 * is a short-cut otherwise. Although it's comparing a
1028 * byte offset to a char length, it does so in a safe way,
1029 * since 1 char always occupies 1 or more bytes,
1030 * so if a string range is (last1 - rx_origin) bytes,
1031 * it will be less than or equal to (last1 - rx_origin)
1032 * chars; meaning it errs towards doing the accurate HOP3
1033 * rather than just using last1 as a short-cut */
1034 (last1 - rx_origin) < other->max_offset
1036 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1039 assert(strpos + start_shift <= check_at);
1040 last = HOP4c(check_at, other->min_offset - start_shift,
1044 s = HOP3c(rx_origin, other->min_offset, strend);
1045 if (s < other_last) /* These positions already checked */
1048 must = utf8_target ? other->utf8_substr : other->substr;
1049 assert(SvPOK(must));
1052 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1058 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1059 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1060 (IV)(from - strbeg),
1066 (unsigned char*)from,
1069 multiline ? FBMrf_MULTILINE : 0
1071 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1072 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1073 (IV)(from - strbeg),
1075 (IV)(s ? s - strbeg : -1)
1081 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1082 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1083 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1084 s ? "Found" : "Contradicts",
1085 other_ix ? "floating" : "anchored",
1086 quoted, RE_SV_TAIL(must));
1091 /* last1 is latest possible substr location. If we didn't
1092 * find it before there, we never will */
1093 if (last >= last1) {
1094 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1095 "; giving up...\n"));
1099 /* try to find the check substr again at a later
1100 * position. Maybe next time we'll find the "other" substr
1102 other_last = HOP3c(last, 1, strend) /* highest failure */;
1104 other_ix /* i.e. if other-is-float */
1105 ? HOP3c(rx_origin, 1, strend)
1106 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1107 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1108 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1109 (other_ix ? "floating" : "anchored"),
1110 (long)(HOP3c(check_at, 1, strend) - strbeg),
1111 (IV)(rx_origin - strbeg)
1116 if (other_ix) { /* if (other-is-float) */
1117 /* other_last is set to s, not s+1, since its possible for
1118 * a floating substr to fail first time, then succeed
1119 * second time at the same floating position; e.g.:
1120 * "-AB--AABZ" =~ /\wAB\d*Z/
1121 * The first time round, anchored and float match at
1122 * "-(AB)--AAB(Z)" then fail on the initial \w character
1123 * class. Second time round, they match at "-AB--A(AB)(Z)".
1128 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1129 other_last = HOP3c(s, 1, strend);
1131 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1132 " at offset %ld (rx_origin now %"IVdf")...\n",
1134 (IV)(rx_origin - strbeg)
1140 DEBUG_OPTIMISE_MORE_r(
1141 Perl_re_printf( aTHX_
1142 " Check-only match: offset min:%"IVdf" max:%"IVdf
1143 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1144 " strend:%"IVdf"\n",
1145 (IV)prog->check_offset_min,
1146 (IV)prog->check_offset_max,
1147 (IV)(check_at-strbeg),
1148 (IV)(rx_origin-strbeg),
1149 (IV)(rx_origin-check_at),
1155 postprocess_substr_matches:
1157 /* handle the extra constraint of /^.../m if present */
1159 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1162 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1163 " looking for /^/m anchor"));
1165 /* we have failed the constraint of a \n before rx_origin.
1166 * Find the next \n, if any, even if it's beyond the current
1167 * anchored and/or floating substrings. Whether we should be
1168 * scanning ahead for the next \n or the next substr is debatable.
1169 * On the one hand you'd expect rare substrings to appear less
1170 * often than \n's. On the other hand, searching for \n means
1171 * we're effectively flipping between check_substr and "\n" on each
1172 * iteration as the current "rarest" string candidate, which
1173 * means for example that we'll quickly reject the whole string if
1174 * hasn't got a \n, rather than trying every substr position
1178 s = HOP3c(strend, - prog->minlen, strpos);
1179 if (s <= rx_origin ||
1180 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1182 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1183 " Did not find /%s^%s/m...\n",
1184 PL_colors[0], PL_colors[1]));
1188 /* earliest possible origin is 1 char after the \n.
1189 * (since *rx_origin == '\n', it's safe to ++ here rather than
1190 * HOP(rx_origin, 1)) */
1193 if (prog->substrs->check_ix == 0 /* check is anchored */
1194 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1196 /* Position contradicts check-string; either because
1197 * check was anchored (and thus has no wiggle room),
1198 * or check was float and rx_origin is above the float range */
1199 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1200 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1201 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1205 /* if we get here, the check substr must have been float,
1206 * is in range, and we may or may not have had an anchored
1207 * "other" substr which still contradicts */
1208 assert(prog->substrs->check_ix); /* check is float */
1210 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1211 /* whoops, the anchored "other" substr exists, so we still
1212 * contradict. On the other hand, the float "check" substr
1213 * didn't contradict, so just retry the anchored "other"
1215 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1216 " Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1217 PL_colors[0], PL_colors[1],
1218 (IV)(rx_origin - strbeg + prog->anchored_offset),
1219 (IV)(rx_origin - strbeg)
1221 goto do_other_substr;
1224 /* success: we don't contradict the found floating substring
1225 * (and there's no anchored substr). */
1226 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1227 " Found /%s^%s/m with rx_origin %ld...\n",
1228 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1231 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1232 " (multiline anchor test skipped)\n"));
1238 /* if we have a starting character class, then test that extra constraint.
1239 * (trie stclasses are too expensive to use here, we are better off to
1240 * leave it to regmatch itself) */
1242 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1243 const U8* const str = (U8*)STRING(progi->regstclass);
1245 /* XXX this value could be pre-computed */
1246 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1247 ? (reginfo->is_utf8_pat
1248 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1249 : STR_LEN(progi->regstclass))
1253 /* latest pos that a matching float substr constrains rx start to */
1254 char *rx_max_float = NULL;
1256 /* if the current rx_origin is anchored, either by satisfying an
1257 * anchored substring constraint, or a /^.../m constraint, then we
1258 * can reject the current origin if the start class isn't found
1259 * at the current position. If we have a float-only match, then
1260 * rx_origin is constrained to a range; so look for the start class
1261 * in that range. if neither, then look for the start class in the
1262 * whole rest of the string */
1264 /* XXX DAPM it's not clear what the minlen test is for, and why
1265 * it's not used in the floating case. Nothing in the test suite
1266 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1267 * Here are some old comments, which may or may not be correct:
1269 * minlen == 0 is possible if regstclass is \b or \B,
1270 * and the fixed substr is ''$.
1271 * Since minlen is already taken into account, rx_origin+1 is
1272 * before strend; accidentally, minlen >= 1 guaranties no false
1273 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1274 * 0) below assumes that regstclass does not come from lookahead...
1275 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1276 * This leaves EXACTF-ish only, which are dealt with in
1280 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1281 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1282 else if (prog->float_substr || prog->float_utf8) {
1283 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1284 endpos= HOP3c(rx_max_float, cl_l, strend);
1289 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1290 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1291 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1292 (IV)start_shift, (IV)(check_at - strbeg),
1293 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1295 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1298 if (endpos == strend) {
1299 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1300 " Could not match STCLASS...\n") );
1303 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1304 " This position contradicts STCLASS...\n") );
1305 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1306 && !(prog->intflags & PREGf_IMPLICIT))
1309 /* Contradict one of substrings */
1310 if (prog->anchored_substr || prog->anchored_utf8) {
1311 if (prog->substrs->check_ix == 1) { /* check is float */
1312 /* Have both, check_string is floating */
1313 assert(rx_origin + start_shift <= check_at);
1314 if (rx_origin + start_shift != check_at) {
1315 /* not at latest position float substr could match:
1316 * Recheck anchored substring, but not floating.
1317 * The condition above is in bytes rather than
1318 * chars for efficiency. It's conservative, in
1319 * that it errs on the side of doing 'goto
1320 * do_other_substr'. In this case, at worst,
1321 * an extra anchored search may get done, but in
1322 * practice the extra fbm_instr() is likely to
1323 * get skipped anyway. */
1324 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1325 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1326 (long)(other_last - strbeg),
1327 (IV)(rx_origin - strbeg)
1329 goto do_other_substr;
1337 /* In the presence of ml_anch, we might be able to
1338 * find another \n without breaking the current float
1341 /* strictly speaking this should be HOP3c(..., 1, ...),
1342 * but since we goto a block of code that's going to
1343 * search for the next \n if any, its safe here */
1345 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1346 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1347 PL_colors[0], PL_colors[1],
1348 (long)(rx_origin - strbeg)) );
1349 goto postprocess_substr_matches;
1352 /* strictly speaking this can never be true; but might
1353 * be if we ever allow intuit without substrings */
1354 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1357 rx_origin = rx_max_float;
1360 /* at this point, any matching substrings have been
1361 * contradicted. Start again... */
1363 rx_origin = HOP3c(rx_origin, 1, strend);
1365 /* uses bytes rather than char calculations for efficiency.
1366 * It's conservative: it errs on the side of doing 'goto restart',
1367 * where there is code that does a proper char-based test */
1368 if (rx_origin + start_shift + end_shift > strend) {
1369 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1370 " Could not match STCLASS...\n") );
1373 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1374 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1375 (prog->substrs->check_ix ? "floating" : "anchored"),
1376 (long)(rx_origin + start_shift - strbeg),
1377 (IV)(rx_origin - strbeg)
1384 if (rx_origin != s) {
1385 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1386 " By STCLASS: moving %ld --> %ld\n",
1387 (long)(rx_origin - strbeg), (long)(s - strbeg))
1391 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1392 " Does not contradict STCLASS...\n");
1397 /* Decide whether using the substrings helped */
1399 if (rx_origin != strpos) {
1400 /* Fixed substring is found far enough so that the match
1401 cannot start at strpos. */
1403 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1404 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1407 /* The found rx_origin position does not prohibit matching at
1408 * strpos, so calling intuit didn't gain us anything. Decrement
1409 * the BmUSEFUL() count on the check substring, and if we reach
1411 if (!(prog->intflags & PREGf_NAUGHTY)
1413 prog->check_utf8 /* Could be deleted already */
1414 && --BmUSEFUL(prog->check_utf8) < 0
1415 && (prog->check_utf8 == prog->float_utf8)
1417 prog->check_substr /* Could be deleted already */
1418 && --BmUSEFUL(prog->check_substr) < 0
1419 && (prog->check_substr == prog->float_substr)
1422 /* If flags & SOMETHING - do not do it many times on the same match */
1423 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1424 /* XXX Does the destruction order has to change with utf8_target? */
1425 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1426 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1427 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1428 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1429 check = NULL; /* abort */
1430 /* XXXX This is a remnant of the old implementation. It
1431 looks wasteful, since now INTUIT can use many
1432 other heuristics. */
1433 prog->extflags &= ~RXf_USE_INTUIT;
1437 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1438 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1439 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1443 fail_finish: /* Substring not found */
1444 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1445 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1447 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1448 PL_colors[4], PL_colors[5]));
1453 #define DECL_TRIE_TYPE(scan) \
1454 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1455 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1456 trie_utf8l, trie_flu8 } \
1457 trie_type = ((scan->flags == EXACT) \
1458 ? (utf8_target ? trie_utf8 : trie_plain) \
1459 : (scan->flags == EXACTL) \
1460 ? (utf8_target ? trie_utf8l : trie_plain) \
1461 : (scan->flags == EXACTFA) \
1463 ? trie_utf8_exactfa_fold \
1464 : trie_latin_utf8_exactfa_fold) \
1465 : (scan->flags == EXACTFLU8 \
1469 : trie_latin_utf8_fold)))
1471 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1474 U8 flags = FOLD_FLAGS_FULL; \
1475 switch (trie_type) { \
1477 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1478 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1479 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1481 goto do_trie_utf8_fold; \
1482 case trie_utf8_exactfa_fold: \
1483 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1485 case trie_utf8_fold: \
1486 do_trie_utf8_fold: \
1487 if ( foldlen>0 ) { \
1488 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1493 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1494 len = UTF8SKIP(uc); \
1495 skiplen = UVCHR_SKIP( uvc ); \
1496 foldlen -= skiplen; \
1497 uscan = foldbuf + skiplen; \
1500 case trie_latin_utf8_exactfa_fold: \
1501 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1503 case trie_latin_utf8_fold: \
1504 if ( foldlen>0 ) { \
1505 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1511 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1512 skiplen = UVCHR_SKIP( uvc ); \
1513 foldlen -= skiplen; \
1514 uscan = foldbuf + skiplen; \
1518 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1519 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1520 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1524 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1531 charid = trie->charmap[ uvc ]; \
1535 if (widecharmap) { \
1536 SV** const svpp = hv_fetch(widecharmap, \
1537 (char*)&uvc, sizeof(UV), 0); \
1539 charid = (U16)SvIV(*svpp); \
1544 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1545 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1546 startpos, doutf8, depth)
1548 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1552 && (ln == 1 || folder(s, pat_string, ln)) \
1553 && (reginfo->intuit || regtry(reginfo, &s)) )\
1559 #define REXEC_FBC_UTF8_SCAN(CODE) \
1561 while (s < strend) { \
1567 #define REXEC_FBC_SCAN(CODE) \
1569 while (s < strend) { \
1575 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1576 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1578 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1587 #define REXEC_FBC_CLASS_SCAN(COND) \
1588 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1590 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1599 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1600 if (utf8_target) { \
1601 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1604 REXEC_FBC_CLASS_SCAN(COND); \
1607 /* The three macros below are slightly different versions of the same logic.
1609 * The first is for /a and /aa when the target string is UTF-8. This can only
1610 * match ascii, but it must advance based on UTF-8. The other two handle the
1611 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1612 * for the boundary (or non-boundary) between a word and non-word character.
1613 * The utf8 and non-utf8 cases have the same logic, but the details must be
1614 * different. Find the "wordness" of the character just prior to this one, and
1615 * compare it with the wordness of this one. If they differ, we have a
1616 * boundary. At the beginning of the string, pretend that the previous
1617 * character was a new-line.
1619 * All these macros uncleanly have side-effects with each other and outside
1620 * variables. So far it's been too much trouble to clean-up
1622 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1623 * a word character or not.
1624 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1626 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1628 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1629 * are looking for a boundary or for a non-boundary. If we are looking for a
1630 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1631 * see if this tentative match actually works, and if so, to quit the loop
1632 * here. And vice-versa if we are looking for a non-boundary.
1634 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1635 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1636 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1637 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1638 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1639 * complement. But in that branch we complement tmp, meaning that at the
1640 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1641 * which means at the top of the loop in the next iteration, it is
1642 * TEST_NON_UTF8(s-1) */
1643 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1644 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1645 tmp = TEST_NON_UTF8(tmp); \
1646 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1647 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1649 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1656 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1657 * TEST_UTF8 is a macro that for the same input code points returns identically
1658 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1659 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1660 if (s == reginfo->strbeg) { \
1663 else { /* Back-up to the start of the previous character */ \
1664 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1665 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1666 0, UTF8_ALLOW_DEFAULT); \
1668 tmp = TEST_UV(tmp); \
1669 LOAD_UTF8_CHARCLASS_ALNUM(); \
1670 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1671 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1680 /* Like the above two macros. UTF8_CODE is the complete code for handling
1681 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1683 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1684 if (utf8_target) { \
1687 else { /* Not utf8 */ \
1688 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1689 tmp = TEST_NON_UTF8(tmp); \
1690 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1691 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1700 /* Here, things have been set up by the previous code so that tmp is the \
1701 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1702 * utf8ness of the target). We also have to check if this matches against \
1703 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1704 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1706 if (tmp == ! TEST_NON_UTF8('\n')) { \
1713 /* This is the macro to use when we want to see if something that looks like it
1714 * could match, actually does, and if so exits the loop */
1715 #define REXEC_FBC_TRYIT \
1716 if ((reginfo->intuit || regtry(reginfo, &s))) \
1719 /* The only difference between the BOUND and NBOUND cases is that
1720 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1721 * NBOUND. This is accomplished by passing it as either the if or else clause,
1722 * with the other one being empty (PLACEHOLDER is defined as empty).
1724 * The TEST_FOO parameters are for operating on different forms of input, but
1725 * all should be ones that return identically for the same underlying code
1727 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1729 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1730 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1732 #define FBC_BOUND_A(TEST_NON_UTF8) \
1734 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1735 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1737 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1739 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1740 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1742 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1744 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1745 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1749 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1750 IV cp_out = Perl__invlist_search(invlist, cp_in);
1751 assert(cp_out >= 0);
1754 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1755 invmap[S_get_break_val_cp_checked(invlist, cp)]
1757 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1758 invmap[_invlist_search(invlist, cp)]
1761 /* Takes a pointer to an inversion list, a pointer to its corresponding
1762 * inversion map, and a code point, and returns the code point's value
1763 * according to the two arrays. It assumes that all code points have a value.
1764 * This is used as the base macro for macros for particular properties */
1765 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1766 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1768 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1769 * of a code point, returning the value for the first code point in the string.
1770 * And it takes the particular macro name that finds the desired value given a
1771 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1772 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1773 (__ASSERT_(pos < strend) \
1774 /* Note assumes is valid UTF-8 */ \
1775 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1777 /* Returns the GCB value for the input code point */
1778 #define getGCB_VAL_CP(cp) \
1779 _generic_GET_BREAK_VAL_CP( \
1784 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1785 * bounded by pos and strend */
1786 #define getGCB_VAL_UTF8(pos, strend) \
1787 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1789 /* Returns the LB value for the input code point */
1790 #define getLB_VAL_CP(cp) \
1791 _generic_GET_BREAK_VAL_CP( \
1796 /* Returns the LB value for the first code point in the UTF-8 encoded string
1797 * bounded by pos and strend */
1798 #define getLB_VAL_UTF8(pos, strend) \
1799 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1802 /* Returns the SB value for the input code point */
1803 #define getSB_VAL_CP(cp) \
1804 _generic_GET_BREAK_VAL_CP( \
1809 /* Returns the SB value for the first code point in the UTF-8 encoded string
1810 * bounded by pos and strend */
1811 #define getSB_VAL_UTF8(pos, strend) \
1812 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1814 /* Returns the WB value for the input code point */
1815 #define getWB_VAL_CP(cp) \
1816 _generic_GET_BREAK_VAL_CP( \
1821 /* Returns the WB value for the first code point in the UTF-8 encoded string
1822 * bounded by pos and strend */
1823 #define getWB_VAL_UTF8(pos, strend) \
1824 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1826 /* We know what class REx starts with. Try to find this position... */
1827 /* if reginfo->intuit, its a dryrun */
1828 /* annoyingly all the vars in this routine have different names from their counterparts
1829 in regmatch. /grrr */
1831 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1832 const char *strend, regmatch_info *reginfo)
1835 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1836 char *pat_string; /* The pattern's exactish string */
1837 char *pat_end; /* ptr to end char of pat_string */
1838 re_fold_t folder; /* Function for computing non-utf8 folds */
1839 const U8 *fold_array; /* array for folding ords < 256 */
1845 I32 tmp = 1; /* Scratch variable? */
1846 const bool utf8_target = reginfo->is_utf8_target;
1847 UV utf8_fold_flags = 0;
1848 const bool is_utf8_pat = reginfo->is_utf8_pat;
1849 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1850 with a result inverts that result, as 0^1 =
1852 _char_class_number classnum;
1854 RXi_GET_DECL(prog,progi);
1856 PERL_ARGS_ASSERT_FIND_BYCLASS;
1858 /* We know what class it must start with. */
1861 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1863 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1864 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1871 REXEC_FBC_UTF8_CLASS_SCAN(
1872 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1875 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s, 0));
1879 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1880 assert(! is_utf8_pat);
1883 if (is_utf8_pat || utf8_target) {
1884 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1885 goto do_exactf_utf8;
1887 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1888 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1889 goto do_exactf_non_utf8; /* isn't dealt with by these */
1891 case EXACTF: /* This node only generated for non-utf8 patterns */
1892 assert(! is_utf8_pat);
1894 utf8_fold_flags = 0;
1895 goto do_exactf_utf8;
1897 fold_array = PL_fold;
1899 goto do_exactf_non_utf8;
1902 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1903 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1904 utf8_fold_flags = FOLDEQ_LOCALE;
1905 goto do_exactf_utf8;
1907 fold_array = PL_fold_locale;
1908 folder = foldEQ_locale;
1909 goto do_exactf_non_utf8;
1913 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1915 goto do_exactf_utf8;
1918 if (! utf8_target) { /* All code points in this node require
1919 UTF-8 to express. */
1922 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1923 | FOLDEQ_S2_FOLDS_SANE;
1924 goto do_exactf_utf8;
1927 if (is_utf8_pat || utf8_target) {
1928 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1929 goto do_exactf_utf8;
1932 /* Any 'ss' in the pattern should have been replaced by regcomp,
1933 * so we don't have to worry here about this single special case
1934 * in the Latin1 range */
1935 fold_array = PL_fold_latin1;
1936 folder = foldEQ_latin1;
1940 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1941 are no glitches with fold-length differences
1942 between the target string and pattern */
1944 /* The idea in the non-utf8 EXACTF* cases is to first find the
1945 * first character of the EXACTF* node and then, if necessary,
1946 * case-insensitively compare the full text of the node. c1 is the
1947 * first character. c2 is its fold. This logic will not work for
1948 * Unicode semantics and the german sharp ss, which hence should
1949 * not be compiled into a node that gets here. */
1950 pat_string = STRING(c);
1951 ln = STR_LEN(c); /* length to match in octets/bytes */
1953 /* We know that we have to match at least 'ln' bytes (which is the
1954 * same as characters, since not utf8). If we have to match 3
1955 * characters, and there are only 2 availabe, we know without
1956 * trying that it will fail; so don't start a match past the
1957 * required minimum number from the far end */
1958 e = HOP3c(strend, -((SSize_t)ln), s);
1960 if (reginfo->intuit && e < s) {
1961 e = s; /* Due to minlen logic of intuit() */
1965 c2 = fold_array[c1];
1966 if (c1 == c2) { /* If char and fold are the same */
1967 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1970 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1978 /* If one of the operands is in utf8, we can't use the simpler folding
1979 * above, due to the fact that many different characters can have the
1980 * same fold, or portion of a fold, or different- length fold */
1981 pat_string = STRING(c);
1982 ln = STR_LEN(c); /* length to match in octets/bytes */
1983 pat_end = pat_string + ln;
1984 lnc = is_utf8_pat /* length to match in characters */
1985 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1988 /* We have 'lnc' characters to match in the pattern, but because of
1989 * multi-character folding, each character in the target can match
1990 * up to 3 characters (Unicode guarantees it will never exceed
1991 * this) if it is utf8-encoded; and up to 2 if not (based on the
1992 * fact that the Latin 1 folds are already determined, and the
1993 * only multi-char fold in that range is the sharp-s folding to
1994 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1995 * string character. Adjust lnc accordingly, rounding up, so that
1996 * if we need to match at least 4+1/3 chars, that really is 5. */
1997 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1998 lnc = (lnc + expansion - 1) / expansion;
2000 /* As in the non-UTF8 case, if we have to match 3 characters, and
2001 * only 2 are left, it's guaranteed to fail, so don't start a
2002 * match that would require us to go beyond the end of the string
2004 e = HOP3c(strend, -((SSize_t)lnc), s);
2006 if (reginfo->intuit && e < s) {
2007 e = s; /* Due to minlen logic of intuit() */
2010 /* XXX Note that we could recalculate e to stop the loop earlier,
2011 * as the worst case expansion above will rarely be met, and as we
2012 * go along we would usually find that e moves further to the left.
2013 * This would happen only after we reached the point in the loop
2014 * where if there were no expansion we should fail. Unclear if
2015 * worth the expense */
2018 char *my_strend= (char *)strend;
2019 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2020 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2021 && (reginfo->intuit || regtry(reginfo, &s)) )
2025 s += (utf8_target) ? UTF8SKIP(s) : 1;
2031 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2032 if (FLAGS(c) != TRADITIONAL_BOUND) {
2033 if (! IN_UTF8_CTYPE_LOCALE) {
2034 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2035 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2040 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2044 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2045 if (FLAGS(c) != TRADITIONAL_BOUND) {
2046 if (! IN_UTF8_CTYPE_LOCALE) {
2047 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2048 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2053 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2056 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2058 assert(FLAGS(c) == TRADITIONAL_BOUND);
2060 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2063 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2065 assert(FLAGS(c) == TRADITIONAL_BOUND);
2067 FBC_BOUND_A(isWORDCHAR_A);
2070 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2072 assert(FLAGS(c) == TRADITIONAL_BOUND);
2074 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2077 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2079 assert(FLAGS(c) == TRADITIONAL_BOUND);
2081 FBC_NBOUND_A(isWORDCHAR_A);
2085 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2086 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2097 switch((bound_type) FLAGS(c)) {
2098 case TRADITIONAL_BOUND:
2099 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2102 if (s == reginfo->strbeg) {
2103 if (reginfo->intuit || regtry(reginfo, &s))
2108 /* Didn't match. Try at the next position (if there is one) */
2109 s += (utf8_target) ? UTF8SKIP(s) : 1;
2110 if (UNLIKELY(s >= reginfo->strend)) {
2116 GCB_enum before = getGCB_VAL_UTF8(
2118 (U8*)(reginfo->strbeg)),
2119 (U8*) reginfo->strend);
2120 while (s < strend) {
2121 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2122 (U8*) reginfo->strend);
2123 if ( (to_complement ^ isGCB(before,
2125 (U8*) reginfo->strbeg,
2128 && (reginfo->intuit || regtry(reginfo, &s)))
2136 else { /* Not utf8. Everything is a GCB except between CR and
2138 while (s < strend) {
2139 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2140 || UCHARAT(s) != '\n'))
2141 && (reginfo->intuit || regtry(reginfo, &s)))
2149 /* And, since this is a bound, it can match after the final
2150 * character in the string */
2151 if ((reginfo->intuit || regtry(reginfo, &s))) {
2157 if (s == reginfo->strbeg) {
2158 if (reginfo->intuit || regtry(reginfo, &s)) {
2161 s += (utf8_target) ? UTF8SKIP(s) : 1;
2162 if (UNLIKELY(s >= reginfo->strend)) {
2168 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2170 (U8*)(reginfo->strbeg)),
2171 (U8*) reginfo->strend);
2172 while (s < strend) {
2173 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2174 if (to_complement ^ isLB(before,
2176 (U8*) reginfo->strbeg,
2178 (U8*) reginfo->strend,
2180 && (reginfo->intuit || regtry(reginfo, &s)))
2188 else { /* Not utf8. */
2189 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2190 while (s < strend) {
2191 LB_enum after = getLB_VAL_CP((U8) *s);
2192 if (to_complement ^ isLB(before,
2194 (U8*) reginfo->strbeg,
2196 (U8*) reginfo->strend,
2198 && (reginfo->intuit || regtry(reginfo, &s)))
2207 if (reginfo->intuit || regtry(reginfo, &s)) {
2214 if (s == reginfo->strbeg) {
2215 if (reginfo->intuit || regtry(reginfo, &s)) {
2218 s += (utf8_target) ? UTF8SKIP(s) : 1;
2219 if (UNLIKELY(s >= reginfo->strend)) {
2225 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2227 (U8*)(reginfo->strbeg)),
2228 (U8*) reginfo->strend);
2229 while (s < strend) {
2230 SB_enum after = getSB_VAL_UTF8((U8*) s,
2231 (U8*) reginfo->strend);
2232 if ((to_complement ^ isSB(before,
2234 (U8*) reginfo->strbeg,
2236 (U8*) reginfo->strend,
2238 && (reginfo->intuit || regtry(reginfo, &s)))
2246 else { /* Not utf8. */
2247 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2248 while (s < strend) {
2249 SB_enum after = getSB_VAL_CP((U8) *s);
2250 if ((to_complement ^ isSB(before,
2252 (U8*) reginfo->strbeg,
2254 (U8*) reginfo->strend,
2256 && (reginfo->intuit || regtry(reginfo, &s)))
2265 /* Here are at the final position in the target string. The SB
2266 * value is always true here, so matches, depending on other
2268 if (reginfo->intuit || regtry(reginfo, &s)) {
2275 if (s == reginfo->strbeg) {
2276 if (reginfo->intuit || regtry(reginfo, &s)) {
2279 s += (utf8_target) ? UTF8SKIP(s) : 1;
2280 if (UNLIKELY(s >= reginfo->strend)) {
2286 /* We are at a boundary between char_sub_0 and char_sub_1.
2287 * We also keep track of the value for char_sub_-1 as we
2288 * loop through the line. Context may be needed to make a
2289 * determination, and if so, this can save having to
2291 WB_enum previous = WB_UNKNOWN;
2292 WB_enum before = getWB_VAL_UTF8(
2295 (U8*)(reginfo->strbeg)),
2296 (U8*) reginfo->strend);
2297 while (s < strend) {
2298 WB_enum after = getWB_VAL_UTF8((U8*) s,
2299 (U8*) reginfo->strend);
2300 if ((to_complement ^ isWB(previous,
2303 (U8*) reginfo->strbeg,
2305 (U8*) reginfo->strend,
2307 && (reginfo->intuit || regtry(reginfo, &s)))
2316 else { /* Not utf8. */
2317 WB_enum previous = WB_UNKNOWN;
2318 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2319 while (s < strend) {
2320 WB_enum after = getWB_VAL_CP((U8) *s);
2321 if ((to_complement ^ isWB(previous,
2324 (U8*) reginfo->strbeg,
2326 (U8*) reginfo->strend,
2328 && (reginfo->intuit || regtry(reginfo, &s)))
2338 if (reginfo->intuit || regtry(reginfo, &s)) {
2345 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2346 is_LNBREAK_latin1_safe(s, strend)
2350 /* The argument to all the POSIX node types is the class number to pass to
2351 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2358 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2359 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2360 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2375 /* The complement of something that matches only ASCII matches all
2376 * non-ASCII, plus everything in ASCII that isn't in the class. */
2377 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2378 || ! _generic_isCC_A(*s, FLAGS(c)));
2387 /* Don't need to worry about utf8, as it can match only a single
2388 * byte invariant character. */
2389 REXEC_FBC_CLASS_SCAN(
2390 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2398 if (! utf8_target) {
2399 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2405 classnum = (_char_class_number) FLAGS(c);
2406 if (classnum < _FIRST_NON_SWASH_CC) {
2407 while (s < strend) {
2409 /* We avoid loading in the swash as long as possible, but
2410 * should we have to, we jump to a separate loop. This
2411 * extra 'if' statement is what keeps this code from being
2412 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2413 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2414 goto found_above_latin1;
2416 if ((UTF8_IS_INVARIANT(*s)
2417 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2419 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2420 && to_complement ^ cBOOL(
2421 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2425 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2437 else switch (classnum) { /* These classes are implemented as
2439 case _CC_ENUM_SPACE:
2440 REXEC_FBC_UTF8_CLASS_SCAN(
2441 to_complement ^ cBOOL(isSPACE_utf8(s)));
2444 case _CC_ENUM_BLANK:
2445 REXEC_FBC_UTF8_CLASS_SCAN(
2446 to_complement ^ cBOOL(isBLANK_utf8(s)));
2449 case _CC_ENUM_XDIGIT:
2450 REXEC_FBC_UTF8_CLASS_SCAN(
2451 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2454 case _CC_ENUM_VERTSPACE:
2455 REXEC_FBC_UTF8_CLASS_SCAN(
2456 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2459 case _CC_ENUM_CNTRL:
2460 REXEC_FBC_UTF8_CLASS_SCAN(
2461 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2465 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2466 NOT_REACHED; /* NOTREACHED */
2471 found_above_latin1: /* Here we have to load a swash to get the result
2472 for the current code point */
2473 if (! PL_utf8_swash_ptrs[classnum]) {
2474 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2475 PL_utf8_swash_ptrs[classnum] =
2476 _core_swash_init("utf8",
2479 PL_XPosix_ptrs[classnum], &flags);
2482 /* This is a copy of the loop above for swash classes, though using the
2483 * FBC macro instead of being expanded out. Since we've loaded the
2484 * swash, we don't have to check for that each time through the loop */
2485 REXEC_FBC_UTF8_CLASS_SCAN(
2486 to_complement ^ cBOOL(_generic_utf8(
2489 swash_fetch(PL_utf8_swash_ptrs[classnum],
2497 /* what trie are we using right now */
2498 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2499 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2500 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2502 const char *last_start = strend - trie->minlen;
2504 const char *real_start = s;
2506 STRLEN maxlen = trie->maxlen;
2508 U8 **points; /* map of where we were in the input string
2509 when reading a given char. For ASCII this
2510 is unnecessary overhead as the relationship
2511 is always 1:1, but for Unicode, especially
2512 case folded Unicode this is not true. */
2513 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2517 GET_RE_DEBUG_FLAGS_DECL;
2519 /* We can't just allocate points here. We need to wrap it in
2520 * an SV so it gets freed properly if there is a croak while
2521 * running the match */
2524 sv_points=newSV(maxlen * sizeof(U8 *));
2525 SvCUR_set(sv_points,
2526 maxlen * sizeof(U8 *));
2527 SvPOK_on(sv_points);
2528 sv_2mortal(sv_points);
2529 points=(U8**)SvPV_nolen(sv_points );
2530 if ( trie_type != trie_utf8_fold
2531 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2534 bitmap=(U8*)trie->bitmap;
2536 bitmap=(U8*)ANYOF_BITMAP(c);
2538 /* this is the Aho-Corasick algorithm modified a touch
2539 to include special handling for long "unknown char" sequences.
2540 The basic idea being that we use AC as long as we are dealing
2541 with a possible matching char, when we encounter an unknown char
2542 (and we have not encountered an accepting state) we scan forward
2543 until we find a legal starting char.
2544 AC matching is basically that of trie matching, except that when
2545 we encounter a failing transition, we fall back to the current
2546 states "fail state", and try the current char again, a process
2547 we repeat until we reach the root state, state 1, or a legal
2548 transition. If we fail on the root state then we can either
2549 terminate if we have reached an accepting state previously, or
2550 restart the entire process from the beginning if we have not.
2553 while (s <= last_start) {
2554 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2562 U8 *uscan = (U8*)NULL;
2563 U8 *leftmost = NULL;
2565 U32 accepted_word= 0;
2569 while ( state && uc <= (U8*)strend ) {
2571 U32 word = aho->states[ state ].wordnum;
2575 DEBUG_TRIE_EXECUTE_r(
2576 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2577 dump_exec_pos( (char *)uc, c, strend, real_start,
2578 (char *)uc, utf8_target, 0 );
2579 Perl_re_printf( aTHX_
2580 " Scanning for legal start char...\n");
2584 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2588 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2594 if (uc >(U8*)last_start) break;
2598 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2599 if (!leftmost || lpos < leftmost) {
2600 DEBUG_r(accepted_word=word);
2606 points[pointpos++ % maxlen]= uc;
2607 if (foldlen || uc < (U8*)strend) {
2608 REXEC_TRIE_READ_CHAR(trie_type, trie,
2610 uscan, len, uvc, charid, foldlen,
2612 DEBUG_TRIE_EXECUTE_r({
2613 dump_exec_pos( (char *)uc, c, strend,
2614 real_start, s, utf8_target, 0);
2615 Perl_re_printf( aTHX_
2616 " Charid:%3u CP:%4"UVxf" ",
2628 word = aho->states[ state ].wordnum;
2630 base = aho->states[ state ].trans.base;
2632 DEBUG_TRIE_EXECUTE_r({
2634 dump_exec_pos( (char *)uc, c, strend, real_start,
2635 s, utf8_target, 0 );
2636 Perl_re_printf( aTHX_
2637 "%sState: %4"UVxf", word=%"UVxf,
2638 failed ? " Fail transition to " : "",
2639 (UV)state, (UV)word);
2645 ( ((offset = base + charid
2646 - 1 - trie->uniquecharcount)) >= 0)
2647 && ((U32)offset < trie->lasttrans)
2648 && trie->trans[offset].check == state
2649 && (tmp=trie->trans[offset].next))
2651 DEBUG_TRIE_EXECUTE_r(
2652 Perl_re_printf( aTHX_ " - legal\n"));
2657 DEBUG_TRIE_EXECUTE_r(
2658 Perl_re_printf( aTHX_ " - fail\n"));
2660 state = aho->fail[state];
2664 /* we must be accepting here */
2665 DEBUG_TRIE_EXECUTE_r(
2666 Perl_re_printf( aTHX_ " - accepting\n"));
2675 if (!state) state = 1;
2678 if ( aho->states[ state ].wordnum ) {
2679 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2680 if (!leftmost || lpos < leftmost) {
2681 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2686 s = (char*)leftmost;
2687 DEBUG_TRIE_EXECUTE_r({
2688 Perl_re_printf( aTHX_ "Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2689 (UV)accepted_word, (IV)(s - real_start)
2692 if (reginfo->intuit || regtry(reginfo, &s)) {
2698 DEBUG_TRIE_EXECUTE_r({
2699 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2702 DEBUG_TRIE_EXECUTE_r(
2703 Perl_re_printf( aTHX_ "No match.\n"));
2712 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2719 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2720 * flags have same meanings as with regexec_flags() */
2723 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2730 struct regexp *const prog = ReANY(rx);
2732 if (flags & REXEC_COPY_STR) {
2735 DEBUG_C(Perl_re_printf( aTHX_
2736 "Copy on write: regexp capture, type %d\n",
2738 /* Create a new COW SV to share the match string and store
2739 * in saved_copy, unless the current COW SV in saved_copy
2740 * is valid and suitable for our purpose */
2741 if (( prog->saved_copy
2742 && SvIsCOW(prog->saved_copy)
2743 && SvPOKp(prog->saved_copy)
2746 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2748 /* just reuse saved_copy SV */
2749 if (RXp_MATCH_COPIED(prog)) {
2750 Safefree(prog->subbeg);
2751 RXp_MATCH_COPIED_off(prog);
2755 /* create new COW SV to share string */
2756 RX_MATCH_COPY_FREE(rx);
2757 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2759 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2760 assert (SvPOKp(prog->saved_copy));
2761 prog->sublen = strend - strbeg;
2762 prog->suboffset = 0;
2763 prog->subcoffset = 0;
2768 SSize_t max = strend - strbeg;
2771 if ( (flags & REXEC_COPY_SKIP_POST)
2772 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2773 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2774 ) { /* don't copy $' part of string */
2777 /* calculate the right-most part of the string covered
2778 * by a capture. Due to lookahead, this may be to
2779 * the right of $&, so we have to scan all captures */
2780 while (n <= prog->lastparen) {
2781 if (prog->offs[n].end > max)
2782 max = prog->offs[n].end;
2786 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2787 ? prog->offs[0].start
2789 assert(max >= 0 && max <= strend - strbeg);
2792 if ( (flags & REXEC_COPY_SKIP_PRE)
2793 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2794 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2795 ) { /* don't copy $` part of string */
2798 /* calculate the left-most part of the string covered
2799 * by a capture. Due to lookbehind, this may be to
2800 * the left of $&, so we have to scan all captures */
2801 while (min && n <= prog->lastparen) {
2802 if ( prog->offs[n].start != -1
2803 && prog->offs[n].start < min)
2805 min = prog->offs[n].start;
2809 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2810 && min > prog->offs[0].end
2812 min = prog->offs[0].end;
2816 assert(min >= 0 && min <= max && min <= strend - strbeg);
2819 if (RX_MATCH_COPIED(rx)) {
2820 if (sublen > prog->sublen)
2822 (char*)saferealloc(prog->subbeg, sublen+1);
2825 prog->subbeg = (char*)safemalloc(sublen+1);
2826 Copy(strbeg + min, prog->subbeg, sublen, char);
2827 prog->subbeg[sublen] = '\0';
2828 prog->suboffset = min;
2829 prog->sublen = sublen;
2830 RX_MATCH_COPIED_on(rx);
2832 prog->subcoffset = prog->suboffset;
2833 if (prog->suboffset && utf8_target) {
2834 /* Convert byte offset to chars.
2835 * XXX ideally should only compute this if @-/@+
2836 * has been seen, a la PL_sawampersand ??? */
2838 /* If there's a direct correspondence between the
2839 * string which we're matching and the original SV,
2840 * then we can use the utf8 len cache associated with
2841 * the SV. In particular, it means that under //g,
2842 * sv_pos_b2u() will use the previously cached
2843 * position to speed up working out the new length of
2844 * subcoffset, rather than counting from the start of
2845 * the string each time. This stops
2846 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2847 * from going quadratic */
2848 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2849 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2850 SV_GMAGIC|SV_CONST_RETURN);
2852 prog->subcoffset = utf8_length((U8*)strbeg,
2853 (U8*)(strbeg+prog->suboffset));
2857 RX_MATCH_COPY_FREE(rx);
2858 prog->subbeg = strbeg;
2859 prog->suboffset = 0;
2860 prog->subcoffset = 0;
2861 prog->sublen = strend - strbeg;
2869 - regexec_flags - match a regexp against a string
2872 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2873 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2874 /* stringarg: the point in the string at which to begin matching */
2875 /* strend: pointer to null at end of string */
2876 /* strbeg: real beginning of string */
2877 /* minend: end of match must be >= minend bytes after stringarg. */
2878 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2879 * itself is accessed via the pointers above */
2880 /* data: May be used for some additional optimizations.
2881 Currently unused. */
2882 /* flags: For optimizations. See REXEC_* in regexp.h */
2885 struct regexp *const prog = ReANY(rx);
2889 SSize_t minlen; /* must match at least this many chars */
2890 SSize_t dontbother = 0; /* how many characters not to try at end */
2891 const bool utf8_target = cBOOL(DO_UTF8(sv));
2893 RXi_GET_DECL(prog,progi);
2894 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2895 regmatch_info *const reginfo = ®info_buf;
2896 regexp_paren_pair *swap = NULL;
2898 GET_RE_DEBUG_FLAGS_DECL;
2900 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2901 PERL_UNUSED_ARG(data);
2903 /* Be paranoid... */
2905 Perl_croak(aTHX_ "NULL regexp parameter");
2909 debug_start_match(rx, utf8_target, stringarg, strend,
2913 startpos = stringarg;
2915 /* set these early as they may be used by the HOP macros below */
2916 reginfo->strbeg = strbeg;
2917 reginfo->strend = strend;
2918 reginfo->is_utf8_target = cBOOL(utf8_target);
2920 if (prog->intflags & PREGf_GPOS_SEEN) {
2923 /* set reginfo->ganch, the position where \G can match */
2926 (flags & REXEC_IGNOREPOS)
2927 ? stringarg /* use start pos rather than pos() */
2928 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2929 /* Defined pos(): */
2930 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2931 : strbeg; /* pos() not defined; use start of string */
2933 DEBUG_GPOS_r(Perl_re_printf( aTHX_
2934 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2936 /* in the presence of \G, we may need to start looking earlier in
2937 * the string than the suggested start point of stringarg:
2938 * if prog->gofs is set, then that's a known, fixed minimum
2941 * /ab|c\G/: gofs = 1
2942 * or if the minimum offset isn't known, then we have to go back
2943 * to the start of the string, e.g. /w+\G/
2946 if (prog->intflags & PREGf_ANCH_GPOS) {
2948 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2950 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2952 DEBUG_r(Perl_re_printf( aTHX_
2953 "fail: ganch-gofs before earliest possible start\n"));
2958 startpos = reginfo->ganch;
2960 else if (prog->gofs) {
2961 startpos = HOPBACKc(startpos, prog->gofs);
2965 else if (prog->intflags & PREGf_GPOS_FLOAT)
2969 minlen = prog->minlen;
2970 if ((startpos + minlen) > strend || startpos < strbeg) {
2971 DEBUG_r(Perl_re_printf( aTHX_
2972 "Regex match can't succeed, so not even tried\n"));
2976 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2977 * which will call destuctors to reset PL_regmatch_state, free higher
2978 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2979 * regmatch_info_aux_eval */
2981 oldsave = PL_savestack_ix;
2985 if ((prog->extflags & RXf_USE_INTUIT)
2986 && !(flags & REXEC_CHECKED))
2988 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2993 if (prog->extflags & RXf_CHECK_ALL) {
2994 /* we can match based purely on the result of INTUIT.
2995 * Set up captures etc just for $& and $-[0]
2996 * (an intuit-only match wont have $1,$2,..) */
2997 assert(!prog->nparens);
2999 /* s/// doesn't like it if $& is earlier than where we asked it to
3000 * start searching (which can happen on something like /.\G/) */
3001 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3004 /* this should only be possible under \G */
3005 assert(prog->intflags & PREGf_GPOS_SEEN);
3006 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3007 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3011 /* match via INTUIT shouldn't have any captures.
3012 * Let @-, @+, $^N know */
3013 prog->lastparen = prog->lastcloseparen = 0;
3014 RX_MATCH_UTF8_set(rx, utf8_target);
3015 prog->offs[0].start = s - strbeg;
3016 prog->offs[0].end = utf8_target
3017 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3018 : s - strbeg + prog->minlenret;
3019 if ( !(flags & REXEC_NOT_FIRST) )
3020 S_reg_set_capture_string(aTHX_ rx,
3022 sv, flags, utf8_target);
3028 multiline = prog->extflags & RXf_PMf_MULTILINE;
3030 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3031 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3032 "String too short [regexec_flags]...\n"));
3036 /* Check validity of program. */
3037 if (UCHARAT(progi->program) != REG_MAGIC) {
3038 Perl_croak(aTHX_ "corrupted regexp program");
3041 RX_MATCH_TAINTED_off(rx);
3042 RX_MATCH_UTF8_set(rx, utf8_target);
3044 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3045 reginfo->intuit = 0;
3046 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3047 reginfo->warned = FALSE;
3049 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3050 /* see how far we have to get to not match where we matched before */
3051 reginfo->till = stringarg + minend;
3053 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3054 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3055 S_cleanup_regmatch_info_aux has executed (registered by
3056 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3057 magic belonging to this SV.
3058 Not newSVsv, either, as it does not COW.
3060 reginfo->sv = newSV(0);
3061 SvSetSV_nosteal(reginfo->sv, sv);
3062 SAVEFREESV(reginfo->sv);
3065 /* reserve next 2 or 3 slots in PL_regmatch_state:
3066 * slot N+0: may currently be in use: skip it
3067 * slot N+1: use for regmatch_info_aux struct
3068 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3069 * slot N+3: ready for use by regmatch()
3073 regmatch_state *old_regmatch_state;
3074 regmatch_slab *old_regmatch_slab;
3075 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3077 /* on first ever match, allocate first slab */
3078 if (!PL_regmatch_slab) {
3079 Newx(PL_regmatch_slab, 1, regmatch_slab);
3080 PL_regmatch_slab->prev = NULL;
3081 PL_regmatch_slab->next = NULL;
3082 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3085 old_regmatch_state = PL_regmatch_state;
3086 old_regmatch_slab = PL_regmatch_slab;
3088 for (i=0; i <= max; i++) {
3090 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3092 reginfo->info_aux_eval =
3093 reginfo->info_aux->info_aux_eval =
3094 &(PL_regmatch_state->u.info_aux_eval);
3096 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3097 PL_regmatch_state = S_push_slab(aTHX);
3100 /* note initial PL_regmatch_state position; at end of match we'll
3101 * pop back to there and free any higher slabs */
3103 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3104 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3105 reginfo->info_aux->poscache = NULL;
3107 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3109 if ((prog->extflags & RXf_EVAL_SEEN))
3110 S_setup_eval_state(aTHX_ reginfo);
3112 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3115 /* If there is a "must appear" string, look for it. */
3117 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3118 /* We have to be careful. If the previous successful match
3119 was from this regex we don't want a subsequent partially
3120 successful match to clobber the old results.
3121 So when we detect this possibility we add a swap buffer
3122 to the re, and switch the buffer each match. If we fail,
3123 we switch it back; otherwise we leave it swapped.
3126 /* do we need a save destructor here for eval dies? */
3127 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3128 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
3129 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3136 if (prog->recurse_locinput)
3137 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3139 /* Simplest case: anchored match need be tried only once, or with
3140 * MBOL, only at the beginning of each line.
3142 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3143 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3144 * match at the start of the string then it won't match anywhere else
3145 * either; while with /.*.../, if it doesn't match at the beginning,
3146 * the earliest it could match is at the start of the next line */
3148 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3151 if (regtry(reginfo, &s))
3154 if (!(prog->intflags & PREGf_ANCH_MBOL))
3157 /* didn't match at start, try at other newline positions */
3160 dontbother = minlen - 1;
3161 end = HOP3c(strend, -dontbother, strbeg) - 1;
3163 /* skip to next newline */
3165 while (s <= end) { /* note it could be possible to match at the end of the string */
3166 /* NB: newlines are the same in unicode as they are in latin */
3169 if (prog->check_substr || prog->check_utf8) {
3170 /* note that with PREGf_IMPLICIT, intuit can only fail
3171 * or return the start position, so it's of limited utility.
3172 * Nevertheless, I made the decision that the potential for
3173 * quick fail was still worth it - DAPM */
3174 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3178 if (regtry(reginfo, &s))
3182 } /* end anchored search */
3184 if (prog->intflags & PREGf_ANCH_GPOS)
3186 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3187 assert(prog->intflags & PREGf_GPOS_SEEN);
3188 /* For anchored \G, the only position it can match from is
3189 * (ganch-gofs); we already set startpos to this above; if intuit
3190 * moved us on from there, we can't possibly succeed */
3191 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3192 if (s == startpos && regtry(reginfo, &s))
3197 /* Messy cases: unanchored match. */
3198 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3199 /* we have /x+whatever/ */
3200 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3206 if (! prog->anchored_utf8) {
3207 to_utf8_substr(prog);
3209 ch = SvPVX_const(prog->anchored_utf8)[0];
3212 DEBUG_EXECUTE_r( did_match = 1 );
3213 if (regtry(reginfo, &s)) goto got_it;
3215 while (s < strend && *s == ch)
3222 if (! prog->anchored_substr) {
3223 if (! to_byte_substr(prog)) {
3224 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3227 ch = SvPVX_const(prog->anchored_substr)[0];
3230 DEBUG_EXECUTE_r( did_match = 1 );
3231 if (regtry(reginfo, &s)) goto got_it;
3233 while (s < strend && *s == ch)
3238 DEBUG_EXECUTE_r(if (!did_match)
3239 Perl_re_printf( aTHX_
3240 "Did not find anchored character...\n")
3243 else if (prog->anchored_substr != NULL
3244 || prog->anchored_utf8 != NULL
3245 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3246 && prog->float_max_offset < strend - s)) {
3251 char *last1; /* Last position checked before */
3255 if (prog->anchored_substr || prog->anchored_utf8) {
3257 if (! prog->anchored_utf8) {
3258 to_utf8_substr(prog);
3260 must = prog->anchored_utf8;
3263 if (! prog->anchored_substr) {
3264 if (! to_byte_substr(prog)) {
3265 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3268 must = prog->anchored_substr;
3270 back_max = back_min = prog->anchored_offset;
3273 if (! prog->float_utf8) {
3274 to_utf8_substr(prog);
3276 must = prog->float_utf8;
3279 if (! prog->float_substr) {
3280 if (! to_byte_substr(prog)) {
3281 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3284 must = prog->float_substr;
3286 back_max = prog->float_max_offset;
3287 back_min = prog->float_min_offset;
3293 last = HOP3c(strend, /* Cannot start after this */
3294 -(SSize_t)(CHR_SVLEN(must)
3295 - (SvTAIL(must) != 0) + back_min), strbeg);
3297 if (s > reginfo->strbeg)
3298 last1 = HOPc(s, -1);
3300 last1 = s - 1; /* bogus */
3302 /* XXXX check_substr already used to find "s", can optimize if
3303 check_substr==must. */
3305 strend = HOPc(strend, -dontbother);
3306 while ( (s <= last) &&
3307 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3308 (unsigned char*)strend, must,
3309 multiline ? FBMrf_MULTILINE : 0)) ) {
3310 DEBUG_EXECUTE_r( did_match = 1 );
3311 if (HOPc(s, -back_max) > last1) {
3312 last1 = HOPc(s, -back_min);
3313 s = HOPc(s, -back_max);
3316 char * const t = (last1 >= reginfo->strbeg)
3317 ? HOPc(last1, 1) : last1 + 1;
3319 last1 = HOPc(s, -back_min);
3323 while (s <= last1) {
3324 if (regtry(reginfo, &s))
3327 s++; /* to break out of outer loop */
3334 while (s <= last1) {
3335 if (regtry(reginfo, &s))
3341 DEBUG_EXECUTE_r(if (!did_match) {
3342 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3343 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3344 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3345 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3346 ? "anchored" : "floating"),
3347 quoted, RE_SV_TAIL(must));
3351 else if ( (c = progi->regstclass) ) {
3353 const OPCODE op = OP(progi->regstclass);
3354 /* don't bother with what can't match */
3355 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3356 strend = HOPc(strend, -(minlen - 1));
3359 SV * const prop = sv_newmortal();
3360 regprop(prog, prop, c, reginfo, NULL);
3362 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3364 Perl_re_printf( aTHX_
3365 "Matching stclass %.*s against %s (%d bytes)\n",
3366 (int)SvCUR(prop), SvPVX_const(prop),
3367 quoted, (int)(strend - s));
3370 if (find_byclass(prog, c, s, strend, reginfo))
3372 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3376 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3384 if (! prog->float_utf8) {
3385 to_utf8_substr(prog);
3387 float_real = prog->float_utf8;
3390 if (! prog->float_substr) {
3391 if (! to_byte_substr(prog)) {
3392 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3395 float_real = prog->float_substr;
3398 little = SvPV_const(float_real, len);
3399 if (SvTAIL(float_real)) {
3400 /* This means that float_real contains an artificial \n on
3401 * the end due to the presence of something like this:
3402 * /foo$/ where we can match both "foo" and "foo\n" at the
3403 * end of the string. So we have to compare the end of the
3404 * string first against the float_real without the \n and
3405 * then against the full float_real with the string. We
3406 * have to watch out for cases where the string might be
3407 * smaller than the float_real or the float_real without
3409 char *checkpos= strend - len;
3411 Perl_re_printf( aTHX_
3412 "%sChecking for float_real.%s\n",
3413 PL_colors[4], PL_colors[5]));
3414 if (checkpos + 1 < strbeg) {
3415 /* can't match, even if we remove the trailing \n
3416 * string is too short to match */
3418 Perl_re_printf( aTHX_
3419 "%sString shorter than required trailing substring, cannot match.%s\n",
3420 PL_colors[4], PL_colors[5]));
3422 } else if (memEQ(checkpos + 1, little, len - 1)) {
3423 /* can match, the end of the string matches without the
3425 last = checkpos + 1;
3426 } else if (checkpos < strbeg) {
3427 /* cant match, string is too short when the "\n" is
3430 Perl_re_printf( aTHX_
3431 "%sString does not contain required trailing substring, cannot match.%s\n",
3432 PL_colors[4], PL_colors[5]));
3434 } else if (!multiline) {
3435 /* non multiline match, so compare with the "\n" at the
3436 * end of the string */
3437 if (memEQ(checkpos, little, len)) {
3441 Perl_re_printf( aTHX_
3442 "%sString does not contain required trailing substring, cannot match.%s\n",
3443 PL_colors[4], PL_colors[5]));
3447 /* multiline match, so we have to search for a place
3448 * where the full string is located */
3454 last = rninstr(s, strend, little, little + len);
3456 last = strend; /* matching "$" */
3459 /* at one point this block contained a comment which was
3460 * probably incorrect, which said that this was a "should not
3461 * happen" case. Even if it was true when it was written I am
3462 * pretty sure it is not anymore, so I have removed the comment
3463 * and replaced it with this one. Yves */
3465 Perl_re_printf( aTHX_
3466 "%sString does not contain required substring, cannot match.%s\n",
3467 PL_colors[4], PL_colors[5]
3471 dontbother = strend - last + prog->float_min_offset;
3473 if (minlen && (dontbother < minlen))
3474 dontbother = minlen - 1;
3475 strend -= dontbother; /* this one's always in bytes! */
3476 /* We don't know much -- general case. */
3479 if (regtry(reginfo, &s))
3488 if (regtry(reginfo, &s))
3490 } while (s++ < strend);
3498 /* s/// doesn't like it if $& is earlier than where we asked it to
3499 * start searching (which can happen on something like /.\G/) */
3500 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3501 && (prog->offs[0].start < stringarg - strbeg))
3503 /* this should only be possible under \G */
3504 assert(prog->intflags & PREGf_GPOS_SEEN);
3505 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3506 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3512 Perl_re_printf( aTHX_
3513 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3520 /* clean up; this will trigger destructors that will free all slabs
3521 * above the current one, and cleanup the regmatch_info_aux
3522 * and regmatch_info_aux_eval sructs */
3524 LEAVE_SCOPE(oldsave);
3526 if (RXp_PAREN_NAMES(prog))
3527 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3529 /* make sure $`, $&, $', and $digit will work later */
3530 if ( !(flags & REXEC_NOT_FIRST) )
3531 S_reg_set_capture_string(aTHX_ rx,
3532 strbeg, reginfo->strend,
3533 sv, flags, utf8_target);
3538 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3539 PL_colors[4], PL_colors[5]));
3541 /* clean up; this will trigger destructors that will free all slabs
3542 * above the current one, and cleanup the regmatch_info_aux
3543 * and regmatch_info_aux_eval sructs */
3545 LEAVE_SCOPE(oldsave);
3548 /* we failed :-( roll it back */
3549 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
3550 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3555 Safefree(prog->offs);
3562 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3563 * Do inc before dec, in case old and new rex are the same */
3564 #define SET_reg_curpm(Re2) \
3565 if (reginfo->info_aux_eval) { \
3566 (void)ReREFCNT_inc(Re2); \
3567 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3568 PM_SETRE((PL_reg_curpm), (Re2)); \
3573 - regtry - try match at specific point
3575 STATIC bool /* 0 failure, 1 success */
3576 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3579 REGEXP *const rx = reginfo->prog;
3580 regexp *const prog = ReANY(rx);
3583 U32 depth = 0; /* used by REGCP_SET */
3585 RXi_GET_DECL(prog,progi);
3586 GET_RE_DEBUG_FLAGS_DECL;
3588 PERL_ARGS_ASSERT_REGTRY;
3590 reginfo->cutpoint=NULL;
3592 prog->offs[0].start = *startposp - reginfo->strbeg;
3593 prog->lastparen = 0;
3594 prog->lastcloseparen = 0;
3596 /* XXXX What this code is doing here?!!! There should be no need
3597 to do this again and again, prog->lastparen should take care of
3600 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3601 * Actually, the code in regcppop() (which Ilya may be meaning by
3602 * prog->lastparen), is not needed at all by the test suite
3603 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3604 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3605 * Meanwhile, this code *is* needed for the
3606 * above-mentioned test suite tests to succeed. The common theme
3607 * on those tests seems to be returning null fields from matches.
3608 * --jhi updated by dapm */
3610 if (prog->nparens) {
3611 regexp_paren_pair *pp = prog->offs;
3613 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3621 result = regmatch(reginfo, *startposp, progi->program + 1);
3623 prog->offs[0].end = result;
3626 if (reginfo->cutpoint)
3627 *startposp= reginfo->cutpoint;
3628 REGCP_UNWIND(lastcp);
3633 #define sayYES goto yes
3634 #define sayNO goto no
3635 #define sayNO_SILENT goto no_silent
3637 /* we dont use STMT_START/END here because it leads to
3638 "unreachable code" warnings, which are bogus, but distracting. */
3639 #define CACHEsayNO \
3640 if (ST.cache_mask) \
3641 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3644 /* this is used to determine how far from the left messages like
3645 'failed...' are printed in regexec.c. It should be set such that
3646 messages are inline with the regop output that created them.
3648 #define REPORT_CODE_OFF 29
3649 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3652 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3656 PerlIO *f= Perl_debug_log;
3657 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3658 va_start(ap, depth);
3659 PerlIO_printf(f, "%*s|%4"UVuf"| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3660 result = PerlIO_vprintf(f, fmt, ap);
3664 #endif /* DEBUGGING */
3667 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3668 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3669 #define CHRTEST_NOT_A_CP_1 -999
3670 #define CHRTEST_NOT_A_CP_2 -998
3672 /* grab a new slab and return the first slot in it */
3674 STATIC regmatch_state *
3677 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3680 regmatch_slab *s = PL_regmatch_slab->next;
3682 Newx(s, 1, regmatch_slab);
3683 s->prev = PL_regmatch_slab;
3685 PL_regmatch_slab->next = s;
3687 PL_regmatch_slab = s;
3688 return SLAB_FIRST(s);
3692 /* push a new state then goto it */
3694 #define PUSH_STATE_GOTO(state, node, input) \
3695 pushinput = input; \
3697 st->resume_state = state; \
3700 /* push a new state with success backtracking, then goto it */
3702 #define PUSH_YES_STATE_GOTO(state, node, input) \
3703 pushinput = input; \
3705 st->resume_state = state; \
3706 goto push_yes_state;
3713 regmatch() - main matching routine
3715 This is basically one big switch statement in a loop. We execute an op,
3716 set 'next' to point the next op, and continue. If we come to a point which
3717 we may need to backtrack to on failure such as (A|B|C), we push a
3718 backtrack state onto the backtrack stack. On failure, we pop the top
3719 state, and re-enter the loop at the state indicated. If there are no more
3720 states to pop, we return failure.
3722 Sometimes we also need to backtrack on success; for example /A+/, where
3723 after successfully matching one A, we need to go back and try to
3724 match another one; similarly for lookahead assertions: if the assertion
3725 completes successfully, we backtrack to the state just before the assertion
3726 and then carry on. In these cases, the pushed state is marked as
3727 'backtrack on success too'. This marking is in fact done by a chain of
3728 pointers, each pointing to the previous 'yes' state. On success, we pop to
3729 the nearest yes state, discarding any intermediate failure-only states.
3730 Sometimes a yes state is pushed just to force some cleanup code to be
3731 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3732 it to free the inner regex.
3734 Note that failure backtracking rewinds the cursor position, while
3735 success backtracking leaves it alone.
3737 A pattern is complete when the END op is executed, while a subpattern
3738 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3739 ops trigger the "pop to last yes state if any, otherwise return true"
3742 A common convention in this function is to use A and B to refer to the two
3743 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3744 the subpattern to be matched possibly multiple times, while B is the entire
3745 rest of the pattern. Variable and state names reflect this convention.
3747 The states in the main switch are the union of ops and failure/success of
3748 substates associated with with that op. For example, IFMATCH is the op
3749 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3750 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3751 successfully matched A and IFMATCH_A_fail is a state saying that we have
3752 just failed to match A. Resume states always come in pairs. The backtrack
3753 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3754 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3755 on success or failure.
3757 The struct that holds a backtracking state is actually a big union, with
3758 one variant for each major type of op. The variable st points to the
3759 top-most backtrack struct. To make the code clearer, within each
3760 block of code we #define ST to alias the relevant union.
3762 Here's a concrete example of a (vastly oversimplified) IFMATCH
3768 #define ST st->u.ifmatch
3770 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3771 ST.foo = ...; // some state we wish to save
3773 // push a yes backtrack state with a resume value of
3774 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3776 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3779 case IFMATCH_A: // we have successfully executed A; now continue with B
3781 bar = ST.foo; // do something with the preserved value
3784 case IFMATCH_A_fail: // A failed, so the assertion failed
3785 ...; // do some housekeeping, then ...
3786 sayNO; // propagate the failure
3793 For any old-timers reading this who are familiar with the old recursive
3794 approach, the code above is equivalent to:
3796 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3805 ...; // do some housekeeping, then ...
3806 sayNO; // propagate the failure
3809 The topmost backtrack state, pointed to by st, is usually free. If you
3810 want to claim it, populate any ST.foo fields in it with values you wish to
3811 save, then do one of
3813 PUSH_STATE_GOTO(resume_state, node, newinput);
3814 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3816 which sets that backtrack state's resume value to 'resume_state', pushes a
3817 new free entry to the top of the backtrack stack, then goes to 'node'.
3818 On backtracking, the free slot is popped, and the saved state becomes the
3819 new free state. An ST.foo field in this new top state can be temporarily
3820 accessed to retrieve values, but once the main loop is re-entered, it
3821 becomes available for reuse.
3823 Note that the depth of the backtrack stack constantly increases during the
3824 left-to-right execution of the pattern, rather than going up and down with
3825 the pattern nesting. For example the stack is at its maximum at Z at the
3826 end of the pattern, rather than at X in the following:
3828 /(((X)+)+)+....(Y)+....Z/
3830 The only exceptions to this are lookahead/behind assertions and the cut,
3831 (?>A), which pop all the backtrack states associated with A before
3834 Backtrack state structs are allocated in slabs of about 4K in size.
3835 PL_regmatch_state and st always point to the currently active state,
3836 and PL_regmatch_slab points to the slab currently containing
3837 PL_regmatch_state. The first time regmatch() is called, the first slab is
3838 allocated, and is never freed until interpreter destruction. When the slab
3839 is full, a new one is allocated and chained to the end. At exit from
3840 regmatch(), slabs allocated since entry are freed.
3845 #define DEBUG_STATE_pp(pp) \
3847 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
3848 Perl_re_printf( aTHX_ \
3849 "%*s" pp " %s%s%s%s%s\n", \
3850 INDENT_CHARS(depth), "", \
3851 PL_reg_name[st->resume_state], \
3852 ((st==yes_state||st==mark_state) ? "[" : ""), \
3853 ((st==yes_state) ? "Y" : ""), \
3854 ((st==mark_state) ? "M" : ""), \
3855 ((st==yes_state||st==mark_state) ? "]" : "") \
3860 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3865 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3866 const char *start, const char *end, const char *blurb)
3868 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3870 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3875 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3876 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3878 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3879 start, end - start, 60);
3881 Perl_re_printf( aTHX_
3882 "%s%s REx%s %s against %s\n",
3883 PL_colors[4], blurb, PL_colors[5], s0, s1);
3885 if (utf8_target||utf8_pat)
3886 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
3887 utf8_pat ? "pattern" : "",
3888 utf8_pat && utf8_target ? " and " : "",
3889 utf8_target ? "string" : ""
3895 S_dump_exec_pos(pTHX_ const char *locinput,
3896 const regnode *scan,
3897 const char *loc_regeol,
3898 const char *loc_bostr,
3899 const char *loc_reg_starttry,
3900 const bool utf8_target,
3904 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3905 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3906 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3907 /* The part of the string before starttry has one color
3908 (pref0_len chars), between starttry and current
3909 position another one (pref_len - pref0_len chars),
3910 after the current position the third one.
3911 We assume that pref0_len <= pref_len, otherwise we
3912 decrease pref0_len. */
3913 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3914 ? (5 + taill) - l : locinput - loc_bostr;
3917 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3919 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3921 pref0_len = pref_len - (locinput - loc_reg_starttry);
3922 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3923 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3924 ? (5 + taill) - pref_len : loc_regeol - locinput);
3925 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3929 if (pref0_len > pref_len)
3930 pref0_len = pref_len;
3932 const int is_uni = utf8_target ? 1 : 0;
3934 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3935 (locinput - pref_len),pref0_len, 60, 4, 5);
3937 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3938 (locinput - pref_len + pref0_len),
3939 pref_len - pref0_len, 60, 2, 3);
3941 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3942 locinput, loc_regeol - locinput, 10, 0, 1);
3944 const STRLEN tlen=len0+len1+len2;
3945 Perl_re_printf( aTHX_
3946 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|%4u| ",
3947 (IV)(locinput - loc_bostr),
3950 (docolor ? "" : "> <"),
3952 (int)(tlen > 19 ? 0 : 19 - tlen),
3960 /* reg_check_named_buff_matched()
3961 * Checks to see if a named buffer has matched. The data array of
3962 * buffer numbers corresponding to the buffer is expected to reside
3963 * in the regexp->data->data array in the slot stored in the ARG() of
3964 * node involved. Note that this routine doesn't actually care about the
3965 * name, that information is not preserved from compilation to execution.
3966 * Returns the index of the leftmost defined buffer with the given name
3967 * or 0 if non of the buffers matched.
3970 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3973 RXi_GET_DECL(rex,rexi);
3974 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3975 I32 *nums=(I32*)SvPVX(sv_dat);
3977 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3979 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3980 if ((I32)rex->lastparen >= nums[n] &&
3981 rex->offs[nums[n]].end != -1)
3991 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3992 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3994 /* This function determines if there are one or two characters that match
3995 * the first character of the passed-in EXACTish node <text_node>, and if
3996 * so, returns them in the passed-in pointers.
3998 * If it determines that no possible character in the target string can
3999 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4000 * the first character in <text_node> requires UTF-8 to represent, and the
4001 * target string isn't in UTF-8.)
4003 * If there are more than two characters that could match the beginning of
4004 * <text_node>, or if more context is required to determine a match or not,
4005 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4007 * The motiviation behind this function is to allow the caller to set up
4008 * tight loops for matching. If <text_node> is of type EXACT, there is
4009 * only one possible character that can match its first character, and so
4010 * the situation is quite simple. But things get much more complicated if
4011 * folding is involved. It may be that the first character of an EXACTFish
4012 * node doesn't participate in any possible fold, e.g., punctuation, so it
4013 * can be matched only by itself. The vast majority of characters that are
4014 * in folds match just two things, their lower and upper-case equivalents.
4015 * But not all are like that; some have multiple possible matches, or match
4016 * sequences of more than one character. This function sorts all that out.
4018 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4019 * loop of trying to match A*, we know we can't exit where the thing
4020 * following it isn't a B. And something can't be a B unless it is the
4021 * beginning of B. By putting a quick test for that beginning in a tight
4022 * loop, we can rule out things that can't possibly be B without having to
4023 * break out of the loop, thus avoiding work. Similarly, if A is a single
4024 * character, we can make a tight loop matching A*, using the outputs of
4027 * If the target string to match isn't in UTF-8, and there aren't
4028 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4029 * the one or two possible octets (which are characters in this situation)
4030 * that can match. In all cases, if there is only one character that can
4031 * match, *<c1p> and *<c2p> will be identical.
4033 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4034 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4035 * can match the beginning of <text_node>. They should be declared with at
4036 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4037 * undefined what these contain.) If one or both of the buffers are
4038 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4039 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4040 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4041 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4042 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4044 const bool utf8_target = reginfo->is_utf8_target;
4046 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4047 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4048 bool use_chrtest_void = FALSE;
4049 const bool is_utf8_pat = reginfo->is_utf8_pat;
4051 /* Used when we have both utf8 input and utf8 output, to avoid converting
4052 * to/from code points */
4053 bool utf8_has_been_setup = FALSE;
4057 U8 *pat = (U8*)STRING(text_node);
4058 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4060 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4062 /* In an exact node, only one thing can be matched, that first
4063 * character. If both the pat and the target are UTF-8, we can just
4064 * copy the input to the output, avoiding finding the code point of
4069 else if (utf8_target) {
4070 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4071 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4072 utf8_has_been_setup = TRUE;
4075 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4078 else { /* an EXACTFish node */
4079 U8 *pat_end = pat + STR_LEN(text_node);
4081 /* An EXACTFL node has at least some characters unfolded, because what
4082 * they match is not known until now. So, now is the time to fold
4083 * the first few of them, as many as are needed to determine 'c1' and
4084 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4085 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4086 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4087 * need to fold as many characters as a single character can fold to,
4088 * so that later we can check if the first ones are such a multi-char
4089 * fold. But, in such a pattern only locale-problematic characters
4090 * aren't folded, so we can skip this completely if the first character
4091 * in the node isn't one of the tricky ones */
4092 if (OP(text_node) == EXACTFL) {
4094 if (! is_utf8_pat) {
4095 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4097 folded[0] = folded[1] = 's';
4099 pat_end = folded + 2;
4102 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4107 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4109 *(d++) = (U8) toFOLD_LC(*s);
4114 _to_utf8_fold_flags(s,
4117 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4128 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4129 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4131 /* Multi-character folds require more context to sort out. Also
4132 * PL_utf8_foldclosures used below doesn't handle them, so have to
4133 * be handled outside this routine */
4134 use_chrtest_void = TRUE;
4136 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4137 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4139 /* Load the folds hash, if not already done */
4141 if (! PL_utf8_foldclosures) {
4142 _load_PL_utf8_foldclosures();
4145 /* The fold closures data structure is a hash with the keys
4146 * being the UTF-8 of every character that is folded to, like
4147 * 'k', and the values each an array of all code points that
4148 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4149 * Multi-character folds are not included */
4150 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4155 /* Not found in the hash, therefore there are no folds
4156 * containing it, so there is only a single character that
4160 else { /* Does participate in folds */
4161 AV* list = (AV*) *listp;
4162 if (av_tindex_nomg(list) != 1) {
4164 /* If there aren't exactly two folds to this, it is
4165 * outside the scope of this function */
4166 use_chrtest_void = TRUE;
4168 else { /* There are two. Get them */
4169 SV** c_p = av_fetch(list, 0, FALSE);
4171 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4175 c_p = av_fetch(list, 1, FALSE);
4177 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4181 /* Folds that cross the 255/256 boundary are forbidden
4182 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4183 * one is ASCIII. Since the pattern character is above
4184 * 255, and its only other match is below 256, the only
4185 * legal match will be to itself. We have thrown away
4186 * the original, so have to compute which is the one
4188 if ((c1 < 256) != (c2 < 256)) {
4189 if ((OP(text_node) == EXACTFL
4190 && ! IN_UTF8_CTYPE_LOCALE)
4191 || ((OP(text_node) == EXACTFA
4192 || OP(text_node) == EXACTFA_NO_TRIE)
4193 && (isASCII(c1) || isASCII(c2))))
4206 else /* Here, c1 is <= 255 */
4208 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4209 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4210 && ((OP(text_node) != EXACTFA
4211 && OP(text_node) != EXACTFA_NO_TRIE)
4214 /* Here, there could be something above Latin1 in the target
4215 * which folds to this character in the pattern. All such
4216 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4217 * than two characters involved in their folds, so are outside
4218 * the scope of this function */
4219 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4220 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4223 use_chrtest_void = TRUE;
4226 else { /* Here nothing above Latin1 can fold to the pattern
4228 switch (OP(text_node)) {
4230 case EXACTFL: /* /l rules */
4231 c2 = PL_fold_locale[c1];
4234 case EXACTF: /* This node only generated for non-utf8
4236 assert(! is_utf8_pat);
4237 if (! utf8_target) { /* /d rules */
4242 /* /u rules for all these. This happens to work for
4243 * EXACTFA as nothing in Latin1 folds to ASCII */
4244 case EXACTFA_NO_TRIE: /* This node only generated for
4245 non-utf8 patterns */
4246 assert(! is_utf8_pat);
4251 c2 = PL_fold_latin1[c1];
4255 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4256 NOT_REACHED; /* NOTREACHED */
4262 /* Here have figured things out. Set up the returns */
4263 if (use_chrtest_void) {
4264 *c2p = *c1p = CHRTEST_VOID;
4266 else if (utf8_target) {
4267 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4268 uvchr_to_utf8(c1_utf8, c1);
4269 uvchr_to_utf8(c2_utf8, c2);
4272 /* Invariants are stored in both the utf8 and byte outputs; Use
4273 * negative numbers otherwise for the byte ones. Make sure that the
4274 * byte ones are the same iff the utf8 ones are the same */
4275 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4276 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4279 ? CHRTEST_NOT_A_CP_1
4280 : CHRTEST_NOT_A_CP_2;
4282 else if (c1 > 255) {
4283 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4288 *c1p = *c2p = c2; /* c2 is the only representable value */
4290 else { /* c1 is representable; see about c2 */
4292 *c2p = (c2 < 256) ? c2 : c1;
4299 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4301 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4302 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4304 PERL_ARGS_ASSERT_ISGCB;
4306 switch (GCB_table[before][after]) {
4313 case GCB_RI_then_RI:
4316 U8 * temp_pos = (U8 *) curpos;
4318 /* Do not break within emoji flag sequences. That is, do not
4319 * break between regional indicator (RI) symbols if there is an
4320 * odd number of RI characters before the break point.
4321 * GB12 ^ (RI RI)* RI × RI
4322 * GB13 [^RI] (RI RI)* RI × RI */
4324 while (backup_one_GCB(strbeg,
4326 utf8_target) == GCB_Regional_Indicator)
4331 return RI_count % 2 != 1;
4334 case GCB_EX_then_EM:
4336 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4338 U8 * temp_pos = (U8 *) curpos;
4342 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4344 while (prev == GCB_Extend);
4346 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4354 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4355 before, after, GCB_table[before][after]);
4362 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4366 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4368 if (*curpos < strbeg) {
4373 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4374 U8 * prev_prev_char_pos;
4376 if (! prev_char_pos) {
4380 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4381 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4382 *curpos = prev_char_pos;
4383 prev_char_pos = prev_prev_char_pos;
4386 *curpos = (U8 *) strbeg;
4391 if (*curpos - 2 < strbeg) {
4392 *curpos = (U8 *) strbeg;
4396 gcb = getGCB_VAL_CP(*(*curpos - 1));
4402 /* Combining marks attach to most classes that precede them, but this defines
4403 * the exceptions (from TR14) */
4404 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4405 || prev == LB_Mandatory_Break \
4406 || prev == LB_Carriage_Return \
4407 || prev == LB_Line_Feed \
4408 || prev == LB_Next_Line \
4409 || prev == LB_Space \
4410 || prev == LB_ZWSpace))
4413 S_isLB(pTHX_ LB_enum before,
4415 const U8 * const strbeg,
4416 const U8 * const curpos,
4417 const U8 * const strend,
4418 const bool utf8_target)
4420 U8 * temp_pos = (U8 *) curpos;
4421 LB_enum prev = before;
4423 /* Is the boundary between 'before' and 'after' line-breakable?
4424 * Most of this is just a table lookup of a generated table from Unicode
4425 * rules. But some rules require context to decide, and so have to be
4426 * implemented in code */
4428 PERL_ARGS_ASSERT_ISLB;
4430 /* Rule numbers in the comments below are as of Unicode 9.0 */
4434 switch (LB_table[before][after]) {
4439 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4442 case LB_SP_foo + LB_BREAKABLE:
4443 case LB_SP_foo + LB_NOBREAK:
4444 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4446 /* When we have something following a SP, we have to look at the
4447 * context in order to know what to do.
4449 * SP SP should not reach here because LB7: Do not break before
4450 * spaces. (For two spaces in a row there is nothing that
4451 * overrides that) */
4452 assert(after != LB_Space);
4454 /* Here we have a space followed by a non-space. Mostly this is a
4455 * case of LB18: "Break after spaces". But there are complications
4456 * as the handling of spaces is somewhat tricky. They are in a
4457 * number of rules, which have to be applied in priority order, but
4458 * something earlier in the string can cause a rule to be skipped
4459 * and a lower priority rule invoked. A prime example is LB7 which
4460 * says don't break before a space. But rule LB8 (lower priority)
4461 * says that the first break opportunity after a ZW is after any
4462 * span of spaces immediately after it. If a ZW comes before a SP
4463 * in the input, rule LB8 applies, and not LB7. Other such rules
4464 * involve combining marks which are rules 9 and 10, but they may
4465 * override higher priority rules if they come earlier in the
4466 * string. Since we're doing random access into the middle of the
4467 * string, we have to look for rules that should get applied based
4468 * on both string position and priority. Combining marks do not
4469 * attach to either ZW nor SP, so we don't have to consider them
4472 * To check for LB8, we have to find the first non-space character
4473 * before this span of spaces */
4475 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4477 while (prev == LB_Space);
4479 /* LB8 Break before any character following a zero-width space,
4480 * even if one or more spaces intervene.
4482 * So if we have a ZW just before this span, and to get here this
4483 * is the final space in the span. */
4484 if (prev == LB_ZWSpace) {
4488 /* Here, not ZW SP+. There are several rules that have higher
4489 * priority than LB18 and can be resolved now, as they don't depend
4490 * on anything earlier in the string (except ZW, which we have
4491 * already handled). One of these rules is LB11 Do not break
4492 * before Word joiner, but we have specially encoded that in the
4493 * lookup table so it is caught by the single test below which
4494 * catches the other ones. */
4495 if (LB_table[LB_Space][after] - LB_SP_foo
4496 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4501 /* If we get here, we have to XXX consider combining marks. */
4502 if (prev == LB_Combining_Mark) {
4504 /* What happens with these depends on the character they
4507 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4509 while (prev == LB_Combining_Mark);
4511 /* Most times these attach to and inherit the characteristics
4512 * of that character, but not always, and when not, they are to
4513 * be treated as AL by rule LB10. */
4514 if (! LB_CM_ATTACHES_TO(prev)) {
4515 prev = LB_Alphabetic;
4519 /* Here, we have the character preceding the span of spaces all set
4520 * up. We follow LB18: "Break after spaces" unless the table shows
4521 * that is overriden */
4522 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4526 /* We don't know how to treat the CM except by looking at the first
4527 * non-CM character preceding it. ZWJ is treated as CM */
4529 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4531 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4533 /* Here, 'prev' is that first earlier non-CM character. If the CM
4534 * attatches to it, then it inherits the behavior of 'prev'. If it
4535 * doesn't attach, it is to be treated as an AL */
4536 if (! LB_CM_ATTACHES_TO(prev)) {
4537 prev = LB_Alphabetic;
4542 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4543 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4545 /* LB21a Don't break after Hebrew + Hyphen.
4546 * HL (HY | BA) × */
4548 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4549 == LB_Hebrew_Letter)
4554 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4556 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4557 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4559 /* LB25a (PR | PO) × ( OP | HY )? NU */
4560 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4564 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4567 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4568 case LB_SY_or_IS_then_various + LB_NOBREAK:
4570 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4572 LB_enum temp = prev;
4574 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4576 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4577 if (temp == LB_Numeric) {
4581 return LB_table[prev][after] - LB_SY_or_IS_then_various
4585 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4586 case LB_various_then_PO_or_PR + LB_NOBREAK:
4588 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4590 LB_enum temp = prev;
4591 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4593 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4595 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4596 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4598 if (temp == LB_Numeric) {
4601 return LB_various_then_PO_or_PR;
4604 case LB_RI_then_RI + LB_NOBREAK:
4605 case LB_RI_then_RI + LB_BREAKABLE:
4609 /* LB30a Break between two regional indicator symbols if and
4610 * only if there are an even number of regional indicators
4611 * preceding the position of the break.
4613 * sot (RI RI)* RI × RI
4614 * [^RI] (RI RI)* RI × RI */
4616 while (backup_one_LB(strbeg,
4618 utf8_target) == LB_Regional_Indicator)
4623 return RI_count % 2 == 0;
4631 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4632 before, after, LB_table[before][after]);
4639 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4643 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4645 if (*curpos >= strend) {
4650 *curpos += UTF8SKIP(*curpos);
4651 if (*curpos >= strend) {
4654 lb = getLB_VAL_UTF8(*curpos, strend);
4658 if (*curpos >= strend) {
4661 lb = getLB_VAL_CP(**curpos);
4668 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4672 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4674 if (*curpos < strbeg) {
4679 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4680 U8 * prev_prev_char_pos;
4682 if (! prev_char_pos) {
4686 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4687 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4688 *curpos = prev_char_pos;
4689 prev_char_pos = prev_prev_char_pos;
4692 *curpos = (U8 *) strbeg;
4697 if (*curpos - 2 < strbeg) {
4698 *curpos = (U8 *) strbeg;
4702 lb = getLB_VAL_CP(*(*curpos - 1));
4709 S_isSB(pTHX_ SB_enum before,
4711 const U8 * const strbeg,
4712 const U8 * const curpos,
4713 const U8 * const strend,
4714 const bool utf8_target)
4716 /* returns a boolean indicating if there is a Sentence Boundary Break
4717 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4719 U8 * lpos = (U8 *) curpos;
4720 bool has_para_sep = FALSE;
4721 bool has_sp = FALSE;
4723 PERL_ARGS_ASSERT_ISSB;
4725 /* Break at the start and end of text.
4728 But unstated in Unicode is don't break if the text is empty */
4729 if (before == SB_EDGE || after == SB_EDGE) {
4730 return before != after;
4733 /* SB 3: Do not break within CRLF. */
4734 if (before == SB_CR && after == SB_LF) {
4738 /* Break after paragraph separators. CR and LF are considered
4739 * so because Unicode views text as like word processing text where there
4740 * are no newlines except between paragraphs, and the word processor takes
4741 * care of wrapping without there being hard line-breaks in the text *./
4742 SB4. Sep | CR | LF ÷ */
4743 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4747 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4748 * (See Section 6.2, Replacing Ignore Rules.)
4749 SB5. X (Extend | Format)* → X */
4750 if (after == SB_Extend || after == SB_Format) {
4752 /* Implied is that the these characters attach to everything
4753 * immediately prior to them except for those separator-type
4754 * characters. And the rules earlier have already handled the case
4755 * when one of those immediately precedes the extend char */
4759 if (before == SB_Extend || before == SB_Format) {
4760 U8 * temp_pos = lpos;
4761 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4762 if ( backup != SB_EDGE
4771 /* Here, both 'before' and 'backup' are these types; implied is that we
4772 * don't break between them */
4773 if (backup == SB_Extend || backup == SB_Format) {
4778 /* Do not break after ambiguous terminators like period, if they are
4779 * immediately followed by a number or lowercase letter, if they are
4780 * between uppercase letters, if the first following letter (optionally
4781 * after certain punctuation) is lowercase, or if they are followed by
4782 * "continuation" punctuation such as comma, colon, or semicolon. For
4783 * example, a period may be an abbreviation or numeric period, and thus may
4784 * not mark the end of a sentence.
4786 * SB6. ATerm × Numeric */
4787 if (before == SB_ATerm && after == SB_Numeric) {
4791 /* SB7. (Upper | Lower) ATerm × Upper */
4792 if (before == SB_ATerm && after == SB_Upper) {
4793 U8 * temp_pos = lpos;
4794 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4795 if (backup == SB_Upper || backup == SB_Lower) {
4800 /* The remaining rules that aren't the final one, all require an STerm or
4801 * an ATerm after having backed up over some Close* Sp*, and in one case an
4802 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4803 * So do that backup now, setting flags if either Sp or a paragraph
4804 * separator are found */
4806 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4807 has_para_sep = TRUE;
4808 before = backup_one_SB(strbeg, &lpos, utf8_target);
4811 if (before == SB_Sp) {
4814 before = backup_one_SB(strbeg, &lpos, utf8_target);
4816 while (before == SB_Sp);
4819 while (before == SB_Close) {
4820 before = backup_one_SB(strbeg, &lpos, utf8_target);
4823 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4824 * most cases an STerm */
4825 if (before == SB_STerm || before == SB_ATerm) {
4827 /* So, here the lhs matches
4828 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4829 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4830 * The rules that apply here are:
4832 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4833 | LF | STerm | ATerm) )* Lower
4834 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4835 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4836 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4837 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4840 /* And all but SB11 forbid having seen a paragraph separator */
4841 if (! has_para_sep) {
4842 if (before == SB_ATerm) { /* SB8 */
4843 U8 * rpos = (U8 *) curpos;
4844 SB_enum later = after;
4846 while ( later != SB_OLetter
4847 && later != SB_Upper
4848 && later != SB_Lower
4852 && later != SB_STerm
4853 && later != SB_ATerm
4854 && later != SB_EDGE)
4856 later = advance_one_SB(&rpos, strend, utf8_target);
4858 if (later == SB_Lower) {
4863 if ( after == SB_SContinue /* SB8a */
4864 || after == SB_STerm
4865 || after == SB_ATerm)
4870 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4871 if ( after == SB_Close
4881 /* SB10. This and SB9 could probably be combined some way, but khw
4882 * has decided to follow the Unicode rule book precisely for
4883 * simplified maintenance */
4897 /* Otherwise, do not break.
4904 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4908 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4910 if (*curpos >= strend) {
4916 *curpos += UTF8SKIP(*curpos);
4917 if (*curpos >= strend) {
4920 sb = getSB_VAL_UTF8(*curpos, strend);
4921 } while (sb == SB_Extend || sb == SB_Format);
4926 if (*curpos >= strend) {
4929 sb = getSB_VAL_CP(**curpos);
4930 } while (sb == SB_Extend || sb == SB_Format);
4937 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4941 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4943 if (*curpos < strbeg) {
4948 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4949 if (! prev_char_pos) {
4953 /* Back up over Extend and Format. curpos is always just to the right
4954 * of the characater whose value we are getting */
4956 U8 * prev_prev_char_pos;
4957 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4960 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4961 *curpos = prev_char_pos;
4962 prev_char_pos = prev_prev_char_pos;
4965 *curpos = (U8 *) strbeg;
4968 } while (sb == SB_Extend || sb == SB_Format);
4972 if (*curpos - 2 < strbeg) {
4973 *curpos = (U8 *) strbeg;
4977 sb = getSB_VAL_CP(*(*curpos - 1));
4978 } while (sb == SB_Extend || sb == SB_Format);
4985 S_isWB(pTHX_ WB_enum previous,
4988 const U8 * const strbeg,
4989 const U8 * const curpos,
4990 const U8 * const strend,
4991 const bool utf8_target)
4993 /* Return a boolean as to if the boundary between 'before' and 'after' is
4994 * a Unicode word break, using their published algorithm, but tailored for
4995 * Perl by treating spans of white space as one unit. Context may be
4996 * needed to make this determination. If the value for the character
4997 * before 'before' is known, it is passed as 'previous'; otherwise that
4998 * should be set to WB_UNKNOWN. The other input parameters give the
4999 * boundaries and current position in the matching of the string. That
5000 * is, 'curpos' marks the position where the character whose wb value is
5001 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5003 U8 * before_pos = (U8 *) curpos;
5004 U8 * after_pos = (U8 *) curpos;
5005 WB_enum prev = before;
5008 PERL_ARGS_ASSERT_ISWB;
5010 /* Rule numbers in the comments below are as of Unicode 9.0 */
5014 switch (WB_table[before][after]) {
5021 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5022 next = advance_one_WB(&after_pos, strend, utf8_target,
5023 FALSE /* Don't skip Extend nor Format */ );
5024 /* A space immediately preceeding an Extend or Format is attached
5025 * to by them, and hence gets separated from previous spaces.
5026 * Otherwise don't break between horizontal white space */
5027 return next == WB_Extend || next == WB_Format;
5029 /* WB4 Ignore Format and Extend characters, except when they appear at
5030 * the beginning of a region of text. This code currently isn't
5031 * general purpose, but it works as the rules are currently and likely
5032 * to be laid out. The reason it works is that when 'they appear at
5033 * the beginning of a region of text', the rule is to break before
5034 * them, just like any other character. Therefore, the default rule
5035 * applies and we don't have to look in more depth. Should this ever
5036 * change, we would have to have 2 'case' statements, like in the rules
5037 * below, and backup a single character (not spacing over the extend
5038 * ones) and then see if that is one of the region-end characters and
5040 case WB_Ex_or_FO_or_ZWJ_then_foo:
5041 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5044 case WB_DQ_then_HL + WB_BREAKABLE:
5045 case WB_DQ_then_HL + WB_NOBREAK:
5047 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5049 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5050 == WB_Hebrew_Letter)
5055 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5057 case WB_HL_then_DQ + WB_BREAKABLE:
5058 case WB_HL_then_DQ + WB_NOBREAK:
5060 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5062 if (advance_one_WB(&after_pos, strend, utf8_target,
5063 TRUE /* Do skip Extend and Format */ )
5064 == WB_Hebrew_Letter)
5069 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5071 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5072 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5074 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5075 * | Single_Quote) (ALetter | Hebrew_Letter) */
5077 next = advance_one_WB(&after_pos, strend, utf8_target,
5078 TRUE /* Do skip Extend and Format */ );
5080 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5085 return WB_table[before][after]
5086 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5088 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5089 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5091 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5092 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5094 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5095 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5100 return WB_table[before][after]
5101 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5103 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5104 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5106 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5109 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5115 return WB_table[before][after]
5116 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5118 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5119 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5121 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5123 if (advance_one_WB(&after_pos, strend, utf8_target,
5124 TRUE /* Do skip Extend and Format */ )
5130 return WB_table[before][after]
5131 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5133 case WB_RI_then_RI + WB_NOBREAK:
5134 case WB_RI_then_RI + WB_BREAKABLE:
5138 /* Do not break within emoji flag sequences. That is, do not
5139 * break between regional indicator (RI) symbols if there is an
5140 * odd number of RI characters before the potential break
5143 * WB15 ^ (RI RI)* RI × RI
5144 * WB16 [^RI] (RI RI)* RI × RI */
5146 while (backup_one_WB(&previous,
5149 utf8_target) == WB_Regional_Indicator)
5154 return RI_count % 2 != 1;
5162 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5163 before, after, WB_table[before][after]);
5170 S_advance_one_WB(pTHX_ U8 ** curpos,
5171 const U8 * const strend,
5172 const bool utf8_target,
5173 const bool skip_Extend_Format)
5177 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5179 if (*curpos >= strend) {
5185 /* Advance over Extend and Format */
5187 *curpos += UTF8SKIP(*curpos);
5188 if (*curpos >= strend) {
5191 wb = getWB_VAL_UTF8(*curpos, strend);
5192 } while ( skip_Extend_Format
5193 && (wb == WB_Extend || wb == WB_Format));
5198 if (*curpos >= strend) {
5201 wb = getWB_VAL_CP(**curpos);
5202 } while ( skip_Extend_Format
5203 && (wb == WB_Extend || wb == WB_Format));
5210 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5214 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5216 /* If we know what the previous character's break value is, don't have
5218 if (*previous != WB_UNKNOWN) {
5221 /* But we need to move backwards by one */
5223 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5225 *previous = WB_EDGE;
5226 *curpos = (U8 *) strbeg;
5229 *previous = WB_UNKNOWN;
5234 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5237 /* And we always back up over these three types */
5238 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5243 if (*curpos < strbeg) {
5248 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5249 if (! prev_char_pos) {
5253 /* Back up over Extend and Format. curpos is always just to the right
5254 * of the characater whose value we are getting */
5256 U8 * prev_prev_char_pos;
5257 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5261 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5262 *curpos = prev_char_pos;
5263 prev_char_pos = prev_prev_char_pos;
5266 *curpos = (U8 *) strbeg;
5269 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5273 if (*curpos - 2 < strbeg) {
5274 *curpos = (U8 *) strbeg;
5278 wb = getWB_VAL_CP(*(*curpos - 1));
5279 } while (wb == WB_Extend || wb == WB_Format);
5285 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5288 ( ( st )->u.eval.close_paren ) && \
5289 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5292 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5295 ( ( st )->u.eval.close_paren ) && \
5297 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5301 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5302 (st)->u.eval.close_paren = ( (expr) + 1 )
5304 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5305 (st)->u.eval.close_paren = 0
5307 /* returns -1 on failure, $+[0] on success */
5309 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5312 #if PERL_VERSION < 9 && !defined(PERL_CORE)
5316 const bool utf8_target = reginfo->is_utf8_target;
5317 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5318 REGEXP *rex_sv = reginfo->prog;
5319 regexp *rex = ReANY(rex_sv);
5320 RXi_GET_DECL(rex,rexi);
5321 /* the current state. This is a cached copy of PL_regmatch_state */
5323 /* cache heavy used fields of st in registers */
5326 U32 n = 0; /* general value; init to avoid compiler warning */
5327 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5328 char *locinput = startpos;
5329 char *pushinput; /* where to continue after a PUSH */
5330 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5332 bool result = 0; /* return value of S_regmatch */
5333 int depth = 0; /* depth of backtrack stack */
5334 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5335 const U32 max_nochange_depth =
5336 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5337 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5338 regmatch_state *yes_state = NULL; /* state to pop to on success of
5340 /* mark_state piggy backs on the yes_state logic so that when we unwind
5341 the stack on success we can update the mark_state as we go */
5342 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5343 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5344 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5346 bool no_final = 0; /* prevent failure from backtracking? */
5347 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5348 char *startpoint = locinput;
5349 SV *popmark = NULL; /* are we looking for a mark? */
5350 SV *sv_commit = NULL; /* last mark name seen in failure */
5351 SV *sv_yes_mark = NULL; /* last mark name we have seen
5352 during a successful match */
5353 U32 lastopen = 0; /* last open we saw */
5354 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
5355 SV* const oreplsv = GvSVn(PL_replgv);
5356 /* these three flags are set by various ops to signal information to
5357 * the very next op. They have a useful lifetime of exactly one loop
5358 * iteration, and are not preserved or restored by state pushes/pops
5360 bool sw = 0; /* the condition value in (?(cond)a|b) */
5361 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5362 int logical = 0; /* the following EVAL is:
5366 or the following IFMATCH/UNLESSM is:
5367 false: plain (?=foo)
5368 true: used as a condition: (?(?=foo))
5370 PAD* last_pad = NULL;
5372 U8 gimme = G_SCALAR;
5373 CV *caller_cv = NULL; /* who called us */
5374 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5375 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
5376 U32 maxopenparen = 0; /* max '(' index seen so far */
5377 int to_complement; /* Invert the result? */
5378 _char_class_number classnum;
5379 bool is_utf8_pat = reginfo->is_utf8_pat;
5382 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5383 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5384 # define SOLARIS_BAD_OPTIMIZER
5385 const U32 *pl_charclass_dup = PL_charclass;
5386 # define PL_charclass pl_charclass_dup
5390 GET_RE_DEBUG_FLAGS_DECL;
5393 /* protect against undef(*^R) */
5394 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5396 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5397 multicall_oldcatch = 0;
5398 PERL_UNUSED_VAR(multicall_cop);
5400 PERL_ARGS_ASSERT_REGMATCH;
5402 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5403 Perl_re_printf( aTHX_ "regmatch start\n");
5406 st = PL_regmatch_state;
5408 /* Note that nextchr is a byte even in UTF */
5411 while (scan != NULL) {
5414 next = scan + NEXT_OFF(scan);
5417 state_num = OP(scan);
5421 if (state_num <= REGNODE_MAX) {
5422 SV * const prop = sv_newmortal();
5423 regnode *rnext = regnext(scan);
5425 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5426 regprop(rex, prop, scan, reginfo, NULL);
5427 Perl_re_printf( aTHX_
5428 "%*s%"IVdf":%s(%"IVdf")\n",
5429 INDENT_CHARS(depth), "",
5430 (IV)(scan - rexi->program),
5432 (PL_regkind[OP(scan)] == END || !rnext) ?
5433 0 : (IV)(rnext - rexi->program));
5440 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5442 switch (state_num) {
5443 case SBOL: /* /^../ and /\A../ */
5444 if (locinput == reginfo->strbeg)
5448 case MBOL: /* /^../m */
5449 if (locinput == reginfo->strbeg ||
5450 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5457 if (locinput == reginfo->ganch)
5461 case KEEPS: /* \K */
5462 /* update the startpoint */
5463 st->u.keeper.val = rex->offs[0].start;
5464 rex->offs[0].start = locinput - reginfo->strbeg;
5465 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5466 NOT_REACHED; /* NOTREACHED */
5468 case KEEPS_next_fail:
5469 /* rollback the start point change */
5470 rex->offs[0].start = st->u.keeper.val;
5472 NOT_REACHED; /* NOTREACHED */
5474 case MEOL: /* /..$/m */
5475 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5479 case SEOL: /* /..$/ */
5480 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5482 if (reginfo->strend - locinput > 1)
5487 if (!NEXTCHR_IS_EOS)
5491 case SANY: /* /./s */
5494 goto increment_locinput;
5496 case REG_ANY: /* /./ */
5497 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5499 goto increment_locinput;
5503 #define ST st->u.trie
5504 case TRIEC: /* (ab|cd) with known charclass */
5505 /* In this case the charclass data is available inline so
5506 we can fail fast without a lot of extra overhead.
5508 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5510 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5511 depth, PL_colors[4], PL_colors[5])
5514 NOT_REACHED; /* NOTREACHED */
5517 case TRIE: /* (ab|cd) */
5518 /* the basic plan of execution of the trie is:
5519 * At the beginning, run though all the states, and
5520 * find the longest-matching word. Also remember the position
5521 * of the shortest matching word. For example, this pattern:
5524 * when matched against the string "abcde", will generate
5525 * accept states for all words except 3, with the longest
5526 * matching word being 4, and the shortest being 2 (with
5527 * the position being after char 1 of the string).
5529 * Then for each matching word, in word order (i.e. 1,2,4,5),
5530 * we run the remainder of the pattern; on each try setting
5531 * the current position to the character following the word,
5532 * returning to try the next word on failure.
5534 * We avoid having to build a list of words at runtime by
5535 * using a compile-time structure, wordinfo[].prev, which
5536 * gives, for each word, the previous accepting word (if any).
5537 * In the case above it would contain the mappings 1->2, 2->0,
5538 * 3->0, 4->5, 5->1. We can use this table to generate, from
5539 * the longest word (4 above), a list of all words, by
5540 * following the list of prev pointers; this gives us the
5541 * unordered list 4,5,1,2. Then given the current word we have
5542 * just tried, we can go through the list and find the
5543 * next-biggest word to try (so if we just failed on word 2,
5544 * the next in the list is 4).
5546 * Since at runtime we don't record the matching position in
5547 * the string for each word, we have to work that out for
5548 * each word we're about to process. The wordinfo table holds
5549 * the character length of each word; given that we recorded
5550 * at the start: the position of the shortest word and its
5551 * length in chars, we just need to move the pointer the
5552 * difference between the two char lengths. Depending on
5553 * Unicode status and folding, that's cheap or expensive.
5555 * This algorithm is optimised for the case where are only a
5556 * small number of accept states, i.e. 0,1, or maybe 2.
5557 * With lots of accepts states, and having to try all of them,
5558 * it becomes quadratic on number of accept states to find all
5563 /* what type of TRIE am I? (utf8 makes this contextual) */
5564 DECL_TRIE_TYPE(scan);
5566 /* what trie are we using right now */
5567 reg_trie_data * const trie
5568 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5569 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5570 U32 state = trie->startstate;
5572 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5573 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5575 && UTF8_IS_ABOVE_LATIN1(nextchr)
5576 && scan->flags == EXACTL)
5578 /* We only output for EXACTL, as we let the folder
5579 * output this message for EXACTFLU8 to avoid
5581 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5586 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5588 if (trie->states[ state ].wordnum) {
5590 Perl_re_exec_indentf( aTHX_ "%smatched empty string...%s\n",
5591 depth, PL_colors[4], PL_colors[5])
5597 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5598 depth, PL_colors[4], PL_colors[5])
5605 U8 *uc = ( U8* )locinput;
5609 U8 *uscan = (U8*)NULL;
5610 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5611 U32 charcount = 0; /* how many input chars we have matched */
5612 U32 accepted = 0; /* have we seen any accepting states? */
5614 ST.jump = trie->jump;
5617 ST.longfold = FALSE; /* char longer if folded => it's harder */
5620 /* fully traverse the TRIE; note the position of the
5621 shortest accept state and the wordnum of the longest
5624 while ( state && uc <= (U8*)(reginfo->strend) ) {
5625 U32 base = trie->states[ state ].trans.base;
5629 wordnum = trie->states[ state ].wordnum;
5631 if (wordnum) { /* it's an accept state */
5634 /* record first match position */
5636 ST.firstpos = (U8*)locinput;
5641 ST.firstchars = charcount;
5644 if (!ST.nextword || wordnum < ST.nextword)
5645 ST.nextword = wordnum;
5646 ST.topword = wordnum;
5649 DEBUG_TRIE_EXECUTE_r({
5650 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
5651 Perl_re_exec_indentf( aTHX_
5652 "%sState: %4"UVxf" Accepted: %c ",
5653 depth, PL_colors[4],
5654 (UV)state, (accepted ? 'Y' : 'N'));
5657 /* read a char and goto next state */
5658 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5660 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5661 uscan, len, uvc, charid, foldlen,
5668 base + charid - 1 - trie->uniquecharcount)) >= 0)
5670 && ((U32)offset < trie->lasttrans)
5671 && trie->trans[offset].check == state)
5673 state = trie->trans[offset].next;
5684 DEBUG_TRIE_EXECUTE_r(
5685 Perl_re_printf( aTHX_
5686 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5687 charid, uvc, (UV)state, PL_colors[5] );
5693 /* calculate total number of accept states */
5698 w = trie->wordinfo[w].prev;
5701 ST.accepted = accepted;
5705 Perl_re_exec_indentf( aTHX_ "%sgot %"IVdf" possible matches%s\n",
5707 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5709 goto trie_first_try; /* jump into the fail handler */
5711 NOT_REACHED; /* NOTREACHED */
5713 case TRIE_next_fail: /* we failed - try next alternative */
5717 REGCP_UNWIND(ST.cp);
5718 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5720 if (!--ST.accepted) {
5722 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
5730 /* Find next-highest word to process. Note that this code
5731 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5734 U16 const nextword = ST.nextword;
5735 reg_trie_wordinfo * const wordinfo
5736 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5737 for (word=ST.topword; word; word=wordinfo[word].prev) {
5738 if (word > nextword && (!min || word < min))
5751 ST.lastparen = rex->lastparen;
5752 ST.lastcloseparen = rex->lastcloseparen;
5756 /* find start char of end of current word */
5758 U32 chars; /* how many chars to skip */
5759 reg_trie_data * const trie
5760 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5762 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5764 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5769 /* the hard option - fold each char in turn and find
5770 * its folded length (which may be different */
5771 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5779 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5787 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5792 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5808 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5809 ? ST.jump[ST.nextword]
5813 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
5821 if (ST.accepted > 1 || has_cutgroup) {
5822 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5823 NOT_REACHED; /* NOTREACHED */
5825 /* only one choice left - just continue */
5827 AV *const trie_words
5828 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5829 SV ** const tmp = trie_words
5830 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5831 SV *sv= tmp ? sv_newmortal() : NULL;
5833 Perl_re_exec_indentf( aTHX_ "%sonly one match left, short-circuiting: #%d <%s>%s\n",
5834 depth, PL_colors[4],
5836 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5837 PL_colors[0], PL_colors[1],
5838 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5840 : "not compiled under -Dr",
5844 locinput = (char*)uc;
5845 continue; /* execute rest of RE */
5850 case EXACTL: /* /abc/l */
5851 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5853 /* Complete checking would involve going through every character
5854 * matched by the string to see if any is above latin1. But the
5855 * comparision otherwise might very well be a fast assembly
5856 * language routine, and I (khw) don't think slowing things down
5857 * just to check for this warning is worth it. So this just checks
5858 * the first character */
5859 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5860 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5863 case EXACT: { /* /abc/ */
5864 char *s = STRING(scan);
5866 if (utf8_target != is_utf8_pat) {
5867 /* The target and the pattern have differing utf8ness. */
5869 const char * const e = s + ln;
5872 /* The target is utf8, the pattern is not utf8.
5873 * Above-Latin1 code points can't match the pattern;
5874 * invariants match exactly, and the other Latin1 ones need
5875 * to be downgraded to a single byte in order to do the
5876 * comparison. (If we could be confident that the target
5877 * is not malformed, this could be refactored to have fewer
5878 * tests by just assuming that if the first bytes match, it
5879 * is an invariant, but there are tests in the test suite
5880 * dealing with (??{...}) which violate this) */
5882 if (l >= reginfo->strend
5883 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5887 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5894 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5904 /* The target is not utf8, the pattern is utf8. */
5906 if (l >= reginfo->strend
5907 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5911 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5918 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5930 /* The target and the pattern have the same utf8ness. */
5931 /* Inline the first character, for speed. */
5932 if (reginfo->strend - locinput < ln
5933 || UCHARAT(s) != nextchr
5934 || (ln > 1 && memNE(s, locinput, ln)))
5943 case EXACTFL: { /* /abc/il */
5945 const U8 * fold_array;
5947 U32 fold_utf8_flags;
5949 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5950 folder = foldEQ_locale;
5951 fold_array = PL_fold_locale;
5952 fold_utf8_flags = FOLDEQ_LOCALE;
5955 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5956 is effectively /u; hence to match, target
5958 if (! utf8_target) {
5961 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5962 | FOLDEQ_S1_FOLDS_SANE;
5963 folder = foldEQ_latin1;
5964 fold_array = PL_fold_latin1;
5967 case EXACTFU_SS: /* /\x{df}/iu */
5968 case EXACTFU: /* /abc/iu */
5969 folder = foldEQ_latin1;
5970 fold_array = PL_fold_latin1;
5971 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5974 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5976 assert(! is_utf8_pat);
5978 case EXACTFA: /* /abc/iaa */
5979 folder = foldEQ_latin1;
5980 fold_array = PL_fold_latin1;
5981 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5984 case EXACTF: /* /abc/i This node only generated for
5985 non-utf8 patterns */
5986 assert(! is_utf8_pat);
5988 fold_array = PL_fold;
5989 fold_utf8_flags = 0;
5997 || state_num == EXACTFU_SS
5998 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6000 /* Either target or the pattern are utf8, or has the issue where
6001 * the fold lengths may differ. */
6002 const char * const l = locinput;
6003 char *e = reginfo->strend;
6005 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6006 l, &e, 0, utf8_target, fold_utf8_flags))
6014 /* Neither the target nor the pattern are utf8 */
6015 if (UCHARAT(s) != nextchr
6017 && UCHARAT(s) != fold_array[nextchr])
6021 if (reginfo->strend - locinput < ln)
6023 if (ln > 1 && ! folder(s, locinput, ln))
6029 case NBOUNDL: /* /\B/l */
6033 case BOUNDL: /* /\b/l */
6036 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6038 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6039 if (! IN_UTF8_CTYPE_LOCALE) {
6040 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6041 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6047 if (locinput == reginfo->strbeg)
6048 b1 = isWORDCHAR_LC('\n');
6050 b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
6051 (U8*)(reginfo->strbeg)));
6053 b2 = (NEXTCHR_IS_EOS)
6054 ? isWORDCHAR_LC('\n')
6055 : isWORDCHAR_LC_utf8((U8*)locinput);
6057 else { /* Here the string isn't utf8 */
6058 b1 = (locinput == reginfo->strbeg)
6059 ? isWORDCHAR_LC('\n')
6060 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6061 b2 = (NEXTCHR_IS_EOS)
6062 ? isWORDCHAR_LC('\n')
6063 : isWORDCHAR_LC(nextchr);
6065 if (to_complement ^ (b1 == b2)) {
6071 case NBOUND: /* /\B/ */
6075 case BOUND: /* /\b/ */
6079 goto bound_ascii_match_only;
6081 case NBOUNDA: /* /\B/a */
6085 case BOUNDA: /* /\b/a */
6089 bound_ascii_match_only:
6090 /* Here the string isn't utf8, or is utf8 and only ascii characters
6091 * are to match \w. In the latter case looking at the byte just
6092 * prior to the current one may be just the final byte of a
6093 * multi-byte character. This is ok. There are two cases:
6094 * 1) it is a single byte character, and then the test is doing
6095 * just what it's supposed to.
6096 * 2) it is a multi-byte character, in which case the final byte is
6097 * never mistakable for ASCII, and so the test will say it is
6098 * not a word character, which is the correct answer. */
6099 b1 = (locinput == reginfo->strbeg)
6100 ? isWORDCHAR_A('\n')
6101 : isWORDCHAR_A(UCHARAT(locinput - 1));
6102 b2 = (NEXTCHR_IS_EOS)
6103 ? isWORDCHAR_A('\n')
6104 : isWORDCHAR_A(nextchr);
6105 if (to_complement ^ (b1 == b2)) {
6111 case NBOUNDU: /* /\B/u */
6115 case BOUNDU: /* /\b/u */
6118 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6121 else if (utf8_target) {
6123 switch((bound_type) FLAGS(scan)) {
6124 case TRADITIONAL_BOUND:
6127 b1 = (locinput == reginfo->strbeg)
6128 ? 0 /* isWORDCHAR_L1('\n') */
6129 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
6130 (U8*)(reginfo->strbeg)));
6131 b2 = (NEXTCHR_IS_EOS)
6132 ? 0 /* isWORDCHAR_L1('\n') */
6133 : isWORDCHAR_utf8((U8*)locinput);
6134 match = cBOOL(b1 != b2);
6138 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6139 match = TRUE; /* GCB always matches at begin and
6143 /* Find the gcb values of previous and current
6144 * chars, then see if is a break point */
6145 match = isGCB(getGCB_VAL_UTF8(
6146 reghop3((U8*)locinput,
6148 (U8*)(reginfo->strbeg)),
6149 (U8*) reginfo->strend),
6150 getGCB_VAL_UTF8((U8*) locinput,
6151 (U8*) reginfo->strend),
6152 (U8*) reginfo->strbeg,
6159 if (locinput == reginfo->strbeg) {
6162 else if (NEXTCHR_IS_EOS) {
6166 match = isLB(getLB_VAL_UTF8(
6167 reghop3((U8*)locinput,
6169 (U8*)(reginfo->strbeg)),
6170 (U8*) reginfo->strend),
6171 getLB_VAL_UTF8((U8*) locinput,
6172 (U8*) reginfo->strend),
6173 (U8*) reginfo->strbeg,
6175 (U8*) reginfo->strend,
6180 case SB_BOUND: /* Always matches at begin and end */
6181 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6185 match = isSB(getSB_VAL_UTF8(
6186 reghop3((U8*)locinput,
6188 (U8*)(reginfo->strbeg)),
6189 (U8*) reginfo->strend),
6190 getSB_VAL_UTF8((U8*) locinput,
6191 (U8*) reginfo->strend),
6192 (U8*) reginfo->strbeg,
6194 (U8*) reginfo->strend,
6200 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6204 match = isWB(WB_UNKNOWN,
6206 reghop3((U8*)locinput,
6208 (U8*)(reginfo->strbeg)),
6209 (U8*) reginfo->strend),
6210 getWB_VAL_UTF8((U8*) locinput,
6211 (U8*) reginfo->strend),
6212 (U8*) reginfo->strbeg,
6214 (U8*) reginfo->strend,
6220 else { /* Not utf8 target */
6221 switch((bound_type) FLAGS(scan)) {
6222 case TRADITIONAL_BOUND:
6225 b1 = (locinput == reginfo->strbeg)
6226 ? 0 /* isWORDCHAR_L1('\n') */
6227 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6228 b2 = (NEXTCHR_IS_EOS)
6229 ? 0 /* isWORDCHAR_L1('\n') */
6230 : isWORDCHAR_L1(nextchr);
6231 match = cBOOL(b1 != b2);
6236 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6237 match = TRUE; /* GCB always matches at begin and
6240 else { /* Only CR-LF combo isn't a GCB in 0-255
6242 match = UCHARAT(locinput - 1) != '\r'
6243 || UCHARAT(locinput) != '\n';
6248 if (locinput == reginfo->strbeg) {
6251 else if (NEXTCHR_IS_EOS) {
6255 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6256 getLB_VAL_CP(UCHARAT(locinput)),
6257 (U8*) reginfo->strbeg,
6259 (U8*) reginfo->strend,
6264 case SB_BOUND: /* Always matches at begin and end */
6265 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6269 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6270 getSB_VAL_CP(UCHARAT(locinput)),
6271 (U8*) reginfo->strbeg,
6273 (U8*) reginfo->strend,
6279 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6283 match = isWB(WB_UNKNOWN,
6284 getWB_VAL_CP(UCHARAT(locinput -1)),
6285 getWB_VAL_CP(UCHARAT(locinput)),
6286 (U8*) reginfo->strbeg,
6288 (U8*) reginfo->strend,
6295 if (to_complement ^ ! match) {
6300 case ANYOFL: /* /[abc]/l */
6301 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6303 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6305 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6308 case ANYOFD: /* /[abc]/d */
6309 case ANYOF: /* /[abc]/ */
6312 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6313 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6316 locinput += UTF8SKIP(locinput);
6319 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6325 /* The argument (FLAGS) to all the POSIX node types is the class number
6328 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6332 case POSIXL: /* \w or [:punct:] etc. under /l */
6333 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6337 /* Use isFOO_lc() for characters within Latin1. (Note that
6338 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6339 * wouldn't be invariant) */
6340 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6341 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6349 if (! UTF8_IS_DOWNGRADEABLE_START(nextchr)) { /* An above Latin-1 code point */
6350 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6351 goto utf8_posix_above_latin1;
6354 /* Here is a UTF-8 variant code point below 256 and the target is
6356 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6357 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6358 *(locinput + 1))))))
6363 goto increment_locinput;
6365 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6369 case POSIXD: /* \w or [:punct:] etc. under /d */
6375 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6377 if (NEXTCHR_IS_EOS) {
6381 /* All UTF-8 variants match */
6382 if (! UTF8_IS_INVARIANT(nextchr)) {
6383 goto increment_locinput;
6389 case POSIXA: /* \w or [:punct:] etc. under /a */
6392 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6393 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6394 * character is a single byte */
6396 if (NEXTCHR_IS_EOS) {
6402 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6408 /* Here we are either not in utf8, or we matched a utf8-invariant,
6409 * so the next char is the next byte */
6413 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6417 case POSIXU: /* \w or [:punct:] etc. under /u */
6419 if (NEXTCHR_IS_EOS) {
6423 /* Use _generic_isCC() for characters within Latin1. (Note that
6424 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6425 * wouldn't be invariant) */
6426 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6427 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6434 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6435 if (! (to_complement
6436 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6444 else { /* Handle above Latin-1 code points */
6445 utf8_posix_above_latin1:
6446 classnum = (_char_class_number) FLAGS(scan);
6447 if (classnum < _FIRST_NON_SWASH_CC) {
6449 /* Here, uses a swash to find such code points. Load if if
6450 * not done already */
6451 if (! PL_utf8_swash_ptrs[classnum]) {
6452 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6453 PL_utf8_swash_ptrs[classnum]
6454 = _core_swash_init("utf8",
6457 PL_XPosix_ptrs[classnum], &flags);
6459 if (! (to_complement
6460 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6461 (U8 *) locinput, TRUE))))
6466 else { /* Here, uses macros to find above Latin-1 code points */
6468 case _CC_ENUM_SPACE:
6469 if (! (to_complement
6470 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6475 case _CC_ENUM_BLANK:
6476 if (! (to_complement
6477 ^ cBOOL(is_HORIZWS_high(locinput))))
6482 case _CC_ENUM_XDIGIT:
6483 if (! (to_complement
6484 ^ cBOOL(is_XDIGIT_high(locinput))))
6489 case _CC_ENUM_VERTSPACE:
6490 if (! (to_complement
6491 ^ cBOOL(is_VERTWS_high(locinput))))
6496 default: /* The rest, e.g. [:cntrl:], can't match
6498 if (! to_complement) {
6504 locinput += UTF8SKIP(locinput);
6508 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6509 a Unicode extended Grapheme Cluster */
6512 if (! utf8_target) {
6514 /* Match either CR LF or '.', as all the other possibilities
6516 locinput++; /* Match the . or CR */
6517 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6519 && locinput < reginfo->strend
6520 && UCHARAT(locinput) == '\n')
6527 /* Get the gcb type for the current character */
6528 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6529 (U8*) reginfo->strend);
6531 /* Then scan through the input until we get to the first
6532 * character whose type is supposed to be a gcb with the
6533 * current character. (There is always a break at the
6535 locinput += UTF8SKIP(locinput);
6536 while (locinput < reginfo->strend) {
6537 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6538 (U8*) reginfo->strend);
6539 if (isGCB(prev_gcb, cur_gcb,
6540 (U8*) reginfo->strbeg, (U8*) locinput,
6547 locinput += UTF8SKIP(locinput);
6554 case NREFFL: /* /\g{name}/il */
6555 { /* The capture buffer cases. The ones beginning with N for the
6556 named buffers just convert to the equivalent numbered and
6557 pretend they were called as the corresponding numbered buffer
6559 /* don't initialize these in the declaration, it makes C++
6564 const U8 *fold_array;
6567 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6568 folder = foldEQ_locale;
6569 fold_array = PL_fold_locale;
6571 utf8_fold_flags = FOLDEQ_LOCALE;
6574 case NREFFA: /* /\g{name}/iaa */
6575 folder = foldEQ_latin1;
6576 fold_array = PL_fold_latin1;
6578 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6581 case NREFFU: /* /\g{name}/iu */
6582 folder = foldEQ_latin1;
6583 fold_array = PL_fold_latin1;
6585 utf8_fold_flags = 0;
6588 case NREFF: /* /\g{name}/i */
6590 fold_array = PL_fold;
6592 utf8_fold_flags = 0;
6595 case NREF: /* /\g{name}/ */
6599 utf8_fold_flags = 0;
6602 /* For the named back references, find the corresponding buffer
6604 n = reg_check_named_buff_matched(rex,scan);
6609 goto do_nref_ref_common;
6611 case REFFL: /* /\1/il */
6612 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6613 folder = foldEQ_locale;
6614 fold_array = PL_fold_locale;
6615 utf8_fold_flags = FOLDEQ_LOCALE;
6618 case REFFA: /* /\1/iaa */
6619 folder = foldEQ_latin1;
6620 fold_array = PL_fold_latin1;
6621 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6624 case REFFU: /* /\1/iu */
6625 folder = foldEQ_latin1;
6626 fold_array = PL_fold_latin1;
6627 utf8_fold_flags = 0;
6630 case REFF: /* /\1/i */
6632 fold_array = PL_fold;
6633 utf8_fold_flags = 0;
6636 case REF: /* /\1/ */
6639 utf8_fold_flags = 0;
6643 n = ARG(scan); /* which paren pair */
6646 ln = rex->offs[n].start;
6647 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6648 if (rex->lastparen < n || ln == -1)
6649 sayNO; /* Do not match unless seen CLOSEn. */
6650 if (ln == rex->offs[n].end)
6653 s = reginfo->strbeg + ln;
6654 if (type != REF /* REF can do byte comparison */
6655 && (utf8_target || type == REFFU || type == REFFL))
6657 char * limit = reginfo->strend;
6659 /* This call case insensitively compares the entire buffer
6660 * at s, with the current input starting at locinput, but
6661 * not going off the end given by reginfo->strend, and
6662 * returns in <limit> upon success, how much of the
6663 * current input was matched */
6664 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6665 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6673 /* Not utf8: Inline the first character, for speed. */
6674 if (!NEXTCHR_IS_EOS &&
6675 UCHARAT(s) != nextchr &&
6677 UCHARAT(s) != fold_array[nextchr]))
6679 ln = rex->offs[n].end - ln;
6680 if (locinput + ln > reginfo->strend)
6682 if (ln > 1 && (type == REF
6683 ? memNE(s, locinput, ln)
6684 : ! folder(s, locinput, ln)))
6690 case NOTHING: /* null op; e.g. the 'nothing' following
6691 * the '*' in m{(a+|b)*}' */
6693 case TAIL: /* placeholder while compiling (A|B|C) */
6697 #define ST st->u.eval
6698 #define CUR_EVAL cur_eval->u.eval
6704 regexp_internal *rei;
6705 regnode *startpoint;
6708 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6709 arg= (U32)ARG(scan);
6710 if (cur_eval && cur_eval->locinput == locinput) {
6711 if ( ++nochange_depth > max_nochange_depth )
6713 "Pattern subroutine nesting without pos change"
6714 " exceeded limit in regex");
6721 startpoint = scan + ARG2L(scan);
6722 EVAL_CLOSE_PAREN_SET( st, arg );
6723 /* Detect infinite recursion
6725 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
6726 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
6727 * So we track the position in the string we are at each time
6728 * we recurse and if we try to enter the same routine twice from
6729 * the same position we throw an error.
6731 if ( rex->recurse_locinput[arg] == locinput ) {
6732 /* FIXME: we should show the regop that is failing as part
6733 * of the error message. */
6734 Perl_croak(aTHX_ "Infinite recursion in regex");
6736 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
6737 rex->recurse_locinput[arg]= locinput;
6740 GET_RE_DEBUG_FLAGS_DECL;
6742 Perl_re_exec_indentf( aTHX_
6743 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
6744 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
6750 /* Save all the positions seen so far. */
6751 ST.cp = regcppush(rex, 0, maxopenparen);
6752 REGCP_SET(ST.lastcp);
6754 /* and then jump to the code we share with EVAL */
6755 goto eval_recurse_doit;
6758 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6759 if (cur_eval && cur_eval->locinput==locinput) {
6760 if ( ++nochange_depth > max_nochange_depth )
6761 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6766 /* execute the code in the {...} */
6770 OP * const oop = PL_op;
6771 COP * const ocurcop = PL_curcop;
6775 /* save *all* paren positions */
6776 regcppush(rex, 0, maxopenparen);
6777 REGCP_SET(runops_cp);
6780 caller_cv = find_runcv(NULL);
6784 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6786 (REGEXP*)(rexi->data->data[n])
6788 nop = (OP*)rexi->data->data[n+1];
6790 else if (rexi->data->what[n] == 'l') { /* literal code */
6792 nop = (OP*)rexi->data->data[n];
6793 assert(CvDEPTH(newcv));
6796 /* literal with own CV */
6797 assert(rexi->data->what[n] == 'L');
6798 newcv = rex->qr_anoncv;
6799 nop = (OP*)rexi->data->data[n];
6802 /* normally if we're about to execute code from the same
6803 * CV that we used previously, we just use the existing
6804 * CX stack entry. However, its possible that in the
6805 * meantime we may have backtracked, popped from the save
6806 * stack, and undone the SAVECOMPPAD(s) associated with
6807 * PUSH_MULTICALL; in which case PL_comppad no longer
6808 * points to newcv's pad. */
6809 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6811 U8 flags = (CXp_SUB_RE |
6812 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6813 if (last_pushed_cv) {
6814 /* PUSH/POP_MULTICALL save and restore the
6815 * caller's PL_comppad; if we call multiple subs
6816 * using the same CX block, we have to save and
6817 * unwind the varying PL_comppad's ourselves,
6818 * especially restoring the right PL_comppad on
6819 * backtrack - so save it on the save stack */
6821 CHANGE_MULTICALL_FLAGS(newcv, flags);
6824 PUSH_MULTICALL_FLAGS(newcv, flags);
6826 last_pushed_cv = newcv;
6829 /* these assignments are just to silence compiler
6831 multicall_cop = NULL;
6833 last_pad = PL_comppad;
6835 /* the initial nextstate you would normally execute
6836 * at the start of an eval (which would cause error
6837 * messages to come from the eval), may be optimised
6838 * away from the execution path in the regex code blocks;
6839 * so manually set PL_curcop to it initially */
6841 OP *o = cUNOPx(nop)->op_first;
6842 assert(o->op_type == OP_NULL);
6843 if (o->op_targ == OP_SCOPE) {
6844 o = cUNOPo->op_first;
6847 assert(o->op_targ == OP_LEAVE);
6848 o = cUNOPo->op_first;
6849 assert(o->op_type == OP_ENTER);
6853 if (o->op_type != OP_STUB) {
6854 assert( o->op_type == OP_NEXTSTATE
6855 || o->op_type == OP_DBSTATE
6856 || (o->op_type == OP_NULL
6857 && ( o->op_targ == OP_NEXTSTATE
6858 || o->op_targ == OP_DBSTATE
6862 PL_curcop = (COP*)o;
6867 DEBUG_STATE_r( Perl_re_printf( aTHX_
6868 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6870 rex->offs[0].end = locinput - reginfo->strbeg;
6871 if (reginfo->info_aux_eval->pos_magic)
6872 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6873 reginfo->sv, reginfo->strbeg,
6874 locinput - reginfo->strbeg);
6877 SV *sv_mrk = get_sv("REGMARK", 1);
6878 sv_setsv(sv_mrk, sv_yes_mark);
6881 /* we don't use MULTICALL here as we want to call the
6882 * first op of the block of interest, rather than the
6883 * first op of the sub. Also, we don't want to free
6884 * the savestack frame */
6885 before = (IV)(SP-PL_stack_base);
6887 CALLRUNOPS(aTHX); /* Scalar context. */
6889 if ((IV)(SP-PL_stack_base) == before)
6890 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6896 /* before restoring everything, evaluate the returned
6897 * value, so that 'uninit' warnings don't use the wrong
6898 * PL_op or pad. Also need to process any magic vars
6899 * (e.g. $1) *before* parentheses are restored */
6904 if (logical == 0) /* (?{})/ */
6905 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6906 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6907 sw = cBOOL(SvTRUE(ret));
6910 else { /* /(??{}) */
6911 /* if its overloaded, let the regex compiler handle
6912 * it; otherwise extract regex, or stringify */
6913 if (SvGMAGICAL(ret))
6914 ret = sv_mortalcopy(ret);
6915 if (!SvAMAGIC(ret)) {
6919 if (SvTYPE(sv) == SVt_REGEXP)
6920 re_sv = (REGEXP*) sv;
6921 else if (SvSMAGICAL(ret)) {
6922 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6924 re_sv = (REGEXP *) mg->mg_obj;
6927 /* force any undef warnings here */
6928 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6929 ret = sv_mortalcopy(ret);
6930 (void) SvPV_force_nolen(ret);
6936 /* *** Note that at this point we don't restore
6937 * PL_comppad, (or pop the CxSUB) on the assumption it may
6938 * be used again soon. This is safe as long as nothing
6939 * in the regexp code uses the pad ! */
6941 PL_curcop = ocurcop;
6942 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6943 PL_curpm = PL_reg_curpm;
6949 /* only /(??{})/ from now on */
6952 /* extract RE object from returned value; compiling if
6956 re_sv = reg_temp_copy(NULL, re_sv);
6961 if (SvUTF8(ret) && IN_BYTES) {
6962 /* In use 'bytes': make a copy of the octet
6963 * sequence, but without the flag on */
6965 const char *const p = SvPV(ret, len);
6966 ret = newSVpvn_flags(p, len, SVs_TEMP);
6968 if (rex->intflags & PREGf_USE_RE_EVAL)
6969 pm_flags |= PMf_USE_RE_EVAL;
6971 /* if we got here, it should be an engine which
6972 * supports compiling code blocks and stuff */
6973 assert(rex->engine && rex->engine->op_comp);
6974 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6975 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6976 rex->engine, NULL, NULL,
6977 /* copy /msixn etc to inner pattern */
6982 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6983 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6984 /* This isn't a first class regexp. Instead, it's
6985 caching a regexp onto an existing, Perl visible
6987 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6993 RXp_MATCH_COPIED_off(re);
6994 re->subbeg = rex->subbeg;
6995 re->sublen = rex->sublen;
6996 re->suboffset = rex->suboffset;
6997 re->subcoffset = rex->subcoffset;
6999 re->lastcloseparen = 0;
7002 debug_start_match(re_sv, utf8_target, locinput,
7003 reginfo->strend, "Matching embedded");
7005 startpoint = rei->program + 1;
7006 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7007 * close_paren only for GOSUB */
7008 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7009 /* Save all the seen positions so far. */
7010 ST.cp = regcppush(rex, 0, maxopenparen);
7011 REGCP_SET(ST.lastcp);
7012 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7014 /* run the pattern returned from (??{...}) */
7016 eval_recurse_doit: /* Share code with GOSUB below this line
7017 * At this point we expect the stack context to be
7018 * set up correctly */
7020 /* invalidate the S-L poscache. We're now executing a
7021 * different set of WHILEM ops (and their associated
7022 * indexes) against the same string, so the bits in the
7023 * cache are meaningless. Setting maxiter to zero forces
7024 * the cache to be invalidated and zeroed before reuse.
7025 * XXX This is too dramatic a measure. Ideally we should
7026 * save the old cache and restore when running the outer
7028 reginfo->poscache_maxiter = 0;
7030 /* the new regexp might have a different is_utf8_pat than we do */
7031 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7033 ST.prev_rex = rex_sv;
7034 ST.prev_curlyx = cur_curlyx;
7036 SET_reg_curpm(rex_sv);
7041 ST.prev_eval = cur_eval;
7043 /* now continue from first node in postoned RE */
7044 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
7045 NOT_REACHED; /* NOTREACHED */
7048 case EVAL_AB: /* cleanup after a successful (??{A})B */
7049 /* note: this is called twice; first after popping B, then A */
7051 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7052 depth, cur_eval, ST.prev_eval);
7055 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7056 if ( cur_eval && CUR_EVAL.close_paren ) {\
7058 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7060 CUR_EVAL.close_paren - 1,\
7064 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7067 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7069 rex_sv = ST.prev_rex;
7070 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7071 SET_reg_curpm(rex_sv);
7072 rex = ReANY(rex_sv);
7073 rexi = RXi_GET(rex);
7075 /* preserve $^R across LEAVE's. See Bug 121070. */
7076 SV *save_sv= GvSV(PL_replgv);
7077 SvREFCNT_inc(save_sv);
7078 regcpblow(ST.cp); /* LEAVE in disguise */
7079 sv_setsv(GvSV(PL_replgv), save_sv);
7080 SvREFCNT_dec(save_sv);
7082 cur_eval = ST.prev_eval;
7083 cur_curlyx = ST.prev_curlyx;
7085 /* Invalidate cache. See "invalidate" comment above. */
7086 reginfo->poscache_maxiter = 0;
7087 if ( nochange_depth )
7090 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7094 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7095 /* note: this is called twice; first after popping B, then A */
7097 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7098 depth, cur_eval, ST.prev_eval);
7101 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7103 rex_sv = ST.prev_rex;
7104 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7105 SET_reg_curpm(rex_sv);
7106 rex = ReANY(rex_sv);
7107 rexi = RXi_GET(rex);
7109 REGCP_UNWIND(ST.lastcp);
7110 regcppop(rex, &maxopenparen);
7111 cur_eval = ST.prev_eval;
7112 cur_curlyx = ST.prev_curlyx;
7114 /* Invalidate cache. See "invalidate" comment above. */
7115 reginfo->poscache_maxiter = 0;
7116 if ( nochange_depth )
7119 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7124 n = ARG(scan); /* which paren pair */
7125 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7126 if (n > maxopenparen)
7128 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
7129 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
7133 (IV)rex->offs[n].start_tmp,
7139 /* XXX really need to log other places start/end are set too */
7140 #define CLOSE_CAPTURE \
7141 rex->offs[n].start = rex->offs[n].start_tmp; \
7142 rex->offs[n].end = locinput - reginfo->strbeg; \
7143 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_ \
7144 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
7146 PTR2UV(rex->offs), \
7148 (IV)rex->offs[n].start, \
7149 (IV)rex->offs[n].end \
7153 n = ARG(scan); /* which paren pair */
7155 if (n > rex->lastparen)
7157 rex->lastcloseparen = n;
7158 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7163 case ACCEPT: /* (*ACCEPT) */
7165 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7169 cursor && OP(cursor)!=END;
7170 cursor=regnext(cursor))
7172 if ( OP(cursor)==CLOSE ){
7174 if ( n <= lastopen ) {
7176 if (n > rex->lastparen)
7178 rex->lastcloseparen = n;
7179 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7188 case GROUPP: /* (?(1)) */
7189 n = ARG(scan); /* which paren pair */
7190 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7193 case NGROUPP: /* (?(<name>)) */
7194 /* reg_check_named_buff_matched returns 0 for no match */
7195 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7198 case INSUBP: /* (?(R)) */
7200 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7201 * of SCAN is already set up as matches a eval.close_paren */
7202 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7205 case DEFINEP: /* (?(DEFINE)) */
7209 case IFTHEN: /* (?(cond)A|B) */
7210 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7212 next = NEXTOPER(NEXTOPER(scan));
7214 next = scan + ARG(scan);
7215 if (OP(next) == IFTHEN) /* Fake one. */
7216 next = NEXTOPER(NEXTOPER(next));
7220 case LOGICAL: /* modifier for EVAL and IFMATCH */
7221 logical = scan->flags;
7224 /*******************************************************************
7226 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7227 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7228 STAR/PLUS/CURLY/CURLYN are used instead.)
7230 A*B is compiled as <CURLYX><A><WHILEM><B>
7232 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7233 state, which contains the current count, initialised to -1. It also sets
7234 cur_curlyx to point to this state, with any previous value saved in the
7237 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7238 since the pattern may possibly match zero times (i.e. it's a while {} loop
7239 rather than a do {} while loop).
7241 Each entry to WHILEM represents a successful match of A. The count in the
7242 CURLYX block is incremented, another WHILEM state is pushed, and execution
7243 passes to A or B depending on greediness and the current count.
7245 For example, if matching against the string a1a2a3b (where the aN are
7246 substrings that match /A/), then the match progresses as follows: (the
7247 pushed states are interspersed with the bits of strings matched so far):
7250 <CURLYX cnt=0><WHILEM>
7251 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7252 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7253 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7254 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7256 (Contrast this with something like CURLYM, which maintains only a single
7260 a1 <CURLYM cnt=1> a2
7261 a1 a2 <CURLYM cnt=2> a3
7262 a1 a2 a3 <CURLYM cnt=3> b
7265 Each WHILEM state block marks a point to backtrack to upon partial failure
7266 of A or B, and also contains some minor state data related to that
7267 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7268 overall state, such as the count, and pointers to the A and B ops.
7270 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7271 must always point to the *current* CURLYX block, the rules are:
7273 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7274 and set cur_curlyx to point the new block.
7276 When popping the CURLYX block after a successful or unsuccessful match,
7277 restore the previous cur_curlyx.
7279 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7280 to the outer one saved in the CURLYX block.
7282 When popping the WHILEM block after a successful or unsuccessful B match,
7283 restore the previous cur_curlyx.
7285 Here's an example for the pattern (AI* BI)*BO
7286 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7289 curlyx backtrack stack
7290 ------ ---------------
7292 CO <CO prev=NULL> <WO>
7293 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7294 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7295 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7297 At this point the pattern succeeds, and we work back down the stack to
7298 clean up, restoring as we go:
7300 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7301 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7302 CO <CO prev=NULL> <WO>
7305 *******************************************************************/
7307 #define ST st->u.curlyx
7309 case CURLYX: /* start of /A*B/ (for complex A) */
7311 /* No need to save/restore up to this paren */
7312 I32 parenfloor = scan->flags;
7314 assert(next); /* keep Coverity happy */
7315 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7318 /* XXXX Probably it is better to teach regpush to support
7319 parenfloor > maxopenparen ... */
7320 if (parenfloor > (I32)rex->lastparen)
7321 parenfloor = rex->lastparen; /* Pessimization... */
7323 ST.prev_curlyx= cur_curlyx;
7325 ST.cp = PL_savestack_ix;
7327 /* these fields contain the state of the current curly.
7328 * they are accessed by subsequent WHILEMs */
7329 ST.parenfloor = parenfloor;
7334 ST.count = -1; /* this will be updated by WHILEM */
7335 ST.lastloc = NULL; /* this will be updated by WHILEM */
7337 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7338 NOT_REACHED; /* NOTREACHED */
7341 case CURLYX_end: /* just finished matching all of A*B */
7342 cur_curlyx = ST.prev_curlyx;
7344 NOT_REACHED; /* NOTREACHED */
7346 case CURLYX_end_fail: /* just failed to match all of A*B */
7348 cur_curlyx = ST.prev_curlyx;
7350 NOT_REACHED; /* NOTREACHED */
7354 #define ST st->u.whilem
7356 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7358 /* see the discussion above about CURLYX/WHILEM */
7363 assert(cur_curlyx); /* keep Coverity happy */
7365 min = ARG1(cur_curlyx->u.curlyx.me);
7366 max = ARG2(cur_curlyx->u.curlyx.me);
7367 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7368 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7369 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7370 ST.cache_offset = 0;
7374 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: matched %ld out of %d..%d\n",
7375 depth, (long)n, min, max)
7378 /* First just match a string of min A's. */
7381 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7383 cur_curlyx->u.curlyx.lastloc = locinput;
7384 REGCP_SET(ST.lastcp);
7386 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7387 NOT_REACHED; /* NOTREACHED */
7390 /* If degenerate A matches "", assume A done. */
7392 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7393 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: empty match detected, trying continuation...\n",
7396 goto do_whilem_B_max;
7399 /* super-linear cache processing.
7401 * The idea here is that for certain types of CURLYX/WHILEM -
7402 * principally those whose upper bound is infinity (and
7403 * excluding regexes that have things like \1 and other very
7404 * non-regular expresssiony things), then if a pattern like
7405 * /....A*.../ fails and we backtrack to the WHILEM, then we
7406 * make a note that this particular WHILEM op was at string
7407 * position 47 (say) when the rest of pattern failed. Then, if
7408 * we ever find ourselves back at that WHILEM, and at string
7409 * position 47 again, we can just fail immediately rather than
7410 * running the rest of the pattern again.
7412 * This is very handy when patterns start to go
7413 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7414 * with a combinatorial explosion of backtracking.
7416 * The cache is implemented as a bit array, with one bit per
7417 * string byte position per WHILEM op (up to 16) - so its
7418 * between 0.25 and 2x the string size.
7420 * To avoid allocating a poscache buffer every time, we do an
7421 * initially countdown; only after we have executed a WHILEM
7422 * op (string-length x #WHILEMs) times do we allocate the
7425 * The top 4 bits of scan->flags byte say how many different
7426 * relevant CURLLYX/WHILEM op pairs there are, while the
7427 * bottom 4-bits is the identifying index number of this
7433 if (!reginfo->poscache_maxiter) {
7434 /* start the countdown: Postpone detection until we
7435 * know the match is not *that* much linear. */
7436 reginfo->poscache_maxiter
7437 = (reginfo->strend - reginfo->strbeg + 1)
7439 /* possible overflow for long strings and many CURLYX's */
7440 if (reginfo->poscache_maxiter < 0)
7441 reginfo->poscache_maxiter = I32_MAX;
7442 reginfo->poscache_iter = reginfo->poscache_maxiter;
7445 if (reginfo->poscache_iter-- == 0) {
7446 /* initialise cache */
7447 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7448 regmatch_info_aux *const aux = reginfo->info_aux;
7449 if (aux->poscache) {
7450 if ((SSize_t)reginfo->poscache_size < size) {
7451 Renew(aux->poscache, size, char);
7452 reginfo->poscache_size = size;
7454 Zero(aux->poscache, size, char);
7457 reginfo->poscache_size = size;
7458 Newxz(aux->poscache, size, char);
7460 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7461 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7462 PL_colors[4], PL_colors[5])
7466 if (reginfo->poscache_iter < 0) {
7467 /* have we already failed at this position? */
7468 SSize_t offset, mask;
7470 reginfo->poscache_iter = -1; /* stop eventual underflow */
7471 offset = (scan->flags & 0xf) - 1
7472 + (locinput - reginfo->strbeg)
7474 mask = 1 << (offset % 8);
7476 if (reginfo->info_aux->poscache[offset] & mask) {
7477 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: (cache) already tried at this position...\n",
7480 sayNO; /* cache records failure */
7482 ST.cache_offset = offset;
7483 ST.cache_mask = mask;
7487 /* Prefer B over A for minimal matching. */
7489 if (cur_curlyx->u.curlyx.minmod) {
7490 ST.save_curlyx = cur_curlyx;
7491 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7492 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
7494 REGCP_SET(ST.lastcp);
7495 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7497 NOT_REACHED; /* NOTREACHED */
7500 /* Prefer A over B for maximal matching. */
7502 if (n < max) { /* More greed allowed? */
7503 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7505 cur_curlyx->u.curlyx.lastloc = locinput;
7506 REGCP_SET(ST.lastcp);
7507 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7508 NOT_REACHED; /* NOTREACHED */
7510 goto do_whilem_B_max;
7512 NOT_REACHED; /* NOTREACHED */
7514 case WHILEM_B_min: /* just matched B in a minimal match */
7515 case WHILEM_B_max: /* just matched B in a maximal match */
7516 cur_curlyx = ST.save_curlyx;
7518 NOT_REACHED; /* NOTREACHED */
7520 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7521 cur_curlyx = ST.save_curlyx;
7522 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7523 cur_curlyx->u.curlyx.count--;
7525 NOT_REACHED; /* NOTREACHED */
7527 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7529 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7530 REGCP_UNWIND(ST.lastcp);
7531 regcppop(rex, &maxopenparen);
7532 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7533 cur_curlyx->u.curlyx.count--;
7535 NOT_REACHED; /* NOTREACHED */
7537 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7538 REGCP_UNWIND(ST.lastcp);
7539 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7540 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "whilem: failed, trying continuation...\n",
7544 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7545 && ckWARN(WARN_REGEXP)
7546 && !reginfo->warned)
7548 reginfo->warned = TRUE;
7549 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7550 "Complex regular subexpression recursion limit (%d) "
7556 ST.save_curlyx = cur_curlyx;
7557 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7558 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7560 NOT_REACHED; /* NOTREACHED */
7562 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7563 cur_curlyx = ST.save_curlyx;
7564 REGCP_UNWIND(ST.lastcp);
7565 regcppop(rex, &maxopenparen);
7567 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7568 /* Maximum greed exceeded */
7569 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7570 && ckWARN(WARN_REGEXP)
7571 && !reginfo->warned)
7573 reginfo->warned = TRUE;
7574 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7575 "Complex regular subexpression recursion "
7576 "limit (%d) exceeded",
7579 cur_curlyx->u.curlyx.count--;
7583 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "trying longer...\n", depth)
7585 /* Try grabbing another A and see if it helps. */
7586 cur_curlyx->u.curlyx.lastloc = locinput;
7587 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7589 REGCP_SET(ST.lastcp);
7590 PUSH_STATE_GOTO(WHILEM_A_min,
7591 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7593 NOT_REACHED; /* NOTREACHED */
7596 #define ST st->u.branch
7598 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7599 next = scan + ARG(scan);
7602 scan = NEXTOPER(scan);
7605 case BRANCH: /* /(...|A|...)/ */
7606 scan = NEXTOPER(scan); /* scan now points to inner node */
7607 ST.lastparen = rex->lastparen;
7608 ST.lastcloseparen = rex->lastcloseparen;
7609 ST.next_branch = next;
7612 /* Now go into the branch */
7614 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7616 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7618 NOT_REACHED; /* NOTREACHED */
7620 case CUTGROUP: /* /(*THEN)/ */
7621 sv_yes_mark = st->u.mark.mark_name = scan->flags
7622 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7624 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7625 NOT_REACHED; /* NOTREACHED */
7627 case CUTGROUP_next_fail:
7630 if (st->u.mark.mark_name)
7631 sv_commit = st->u.mark.mark_name;
7633 NOT_REACHED; /* NOTREACHED */
7637 NOT_REACHED; /* NOTREACHED */
7639 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7644 REGCP_UNWIND(ST.cp);
7645 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7646 scan = ST.next_branch;
7647 /* no more branches? */
7648 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7650 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
7657 continue; /* execute next BRANCH[J] op */
7660 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7665 #define ST st->u.curlym
7667 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7669 /* This is an optimisation of CURLYX that enables us to push
7670 * only a single backtracking state, no matter how many matches
7671 * there are in {m,n}. It relies on the pattern being constant
7672 * length, with no parens to influence future backrefs
7676 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7678 ST.lastparen = rex->lastparen;
7679 ST.lastcloseparen = rex->lastcloseparen;
7681 /* if paren positive, emulate an OPEN/CLOSE around A */
7683 U32 paren = ST.me->flags;
7684 if (paren > maxopenparen)
7685 maxopenparen = paren;
7686 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7694 ST.c1 = CHRTEST_UNINIT;
7697 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7700 curlym_do_A: /* execute the A in /A{m,n}B/ */
7701 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7702 NOT_REACHED; /* NOTREACHED */
7704 case CURLYM_A: /* we've just matched an A */
7706 /* after first match, determine A's length: u.curlym.alen */
7707 if (ST.count == 1) {
7708 if (reginfo->is_utf8_target) {
7709 char *s = st->locinput;
7710 while (s < locinput) {
7716 ST.alen = locinput - st->locinput;
7719 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7722 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7723 depth, (IV) ST.count, (IV)ST.alen)
7726 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7730 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7731 if ( max == REG_INFTY || ST.count < max )
7732 goto curlym_do_A; /* try to match another A */
7734 goto curlym_do_B; /* try to match B */
7736 case CURLYM_A_fail: /* just failed to match an A */
7737 REGCP_UNWIND(ST.cp);
7740 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7741 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7744 curlym_do_B: /* execute the B in /A{m,n}B/ */
7745 if (ST.c1 == CHRTEST_UNINIT) {
7746 /* calculate c1 and c2 for possible match of 1st char
7747 * following curly */
7748 ST.c1 = ST.c2 = CHRTEST_VOID;
7750 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7751 regnode *text_node = ST.B;
7752 if (! HAS_TEXT(text_node))
7753 FIND_NEXT_IMPT(text_node);
7756 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7758 But the former is redundant in light of the latter.
7760 if this changes back then the macro for
7761 IS_TEXT and friends need to change.
7763 if (PL_regkind[OP(text_node)] == EXACT) {
7764 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7765 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7775 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%"IVdf"...\n",
7776 depth, (IV)ST.count)
7778 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7779 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7780 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7781 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7783 /* simulate B failing */
7785 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7787 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7788 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7789 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7791 state_num = CURLYM_B_fail;
7792 goto reenter_switch;
7795 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7796 /* simulate B failing */
7798 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7800 (int) nextchr, ST.c1, ST.c2)
7802 state_num = CURLYM_B_fail;
7803 goto reenter_switch;
7808 /* emulate CLOSE: mark current A as captured */
7809 I32 paren = ST.me->flags;
7811 rex->offs[paren].start
7812 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7813 rex->offs[paren].end = locinput - reginfo->strbeg;
7814 if ((U32)paren > rex->lastparen)
7815 rex->lastparen = paren;
7816 rex->lastcloseparen = paren;
7819 rex->offs[paren].end = -1;
7821 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7830 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7831 NOT_REACHED; /* NOTREACHED */
7833 case CURLYM_B_fail: /* just failed to match a B */
7834 REGCP_UNWIND(ST.cp);
7835 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7837 I32 max = ARG2(ST.me);
7838 if (max != REG_INFTY && ST.count == max)
7840 goto curlym_do_A; /* try to match a further A */
7842 /* backtrack one A */
7843 if (ST.count == ARG1(ST.me) /* min */)
7846 SET_locinput(HOPc(locinput, -ST.alen));
7847 goto curlym_do_B; /* try to match B */
7850 #define ST st->u.curly
7852 #define CURLY_SETPAREN(paren, success) \
7855 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7856 rex->offs[paren].end = locinput - reginfo->strbeg; \
7857 if (paren > rex->lastparen) \
7858 rex->lastparen = paren; \
7859 rex->lastcloseparen = paren; \
7862 rex->offs[paren].end = -1; \
7863 rex->lastparen = ST.lastparen; \
7864 rex->lastcloseparen = ST.lastcloseparen; \
7868 case STAR: /* /A*B/ where A is width 1 char */
7872 scan = NEXTOPER(scan);
7875 case PLUS: /* /A+B/ where A is width 1 char */
7879 scan = NEXTOPER(scan);
7882 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7883 ST.paren = scan->flags; /* Which paren to set */
7884 ST.lastparen = rex->lastparen;
7885 ST.lastcloseparen = rex->lastcloseparen;
7886 if (ST.paren > maxopenparen)
7887 maxopenparen = ST.paren;
7888 ST.min = ARG1(scan); /* min to match */
7889 ST.max = ARG2(scan); /* max to match */
7890 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
7895 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7898 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7900 ST.min = ARG1(scan); /* min to match */
7901 ST.max = ARG2(scan); /* max to match */
7902 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7905 * Lookahead to avoid useless match attempts
7906 * when we know what character comes next.
7908 * Used to only do .*x and .*?x, but now it allows
7909 * for )'s, ('s and (?{ ... })'s to be in the way
7910 * of the quantifier and the EXACT-like node. -- japhy
7913 assert(ST.min <= ST.max);
7914 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7915 ST.c1 = ST.c2 = CHRTEST_VOID;
7918 regnode *text_node = next;
7920 if (! HAS_TEXT(text_node))
7921 FIND_NEXT_IMPT(text_node);
7923 if (! HAS_TEXT(text_node))
7924 ST.c1 = ST.c2 = CHRTEST_VOID;
7926 if ( PL_regkind[OP(text_node)] != EXACT ) {
7927 ST.c1 = ST.c2 = CHRTEST_VOID;
7931 /* Currently we only get here when
7933 PL_rekind[OP(text_node)] == EXACT
7935 if this changes back then the macro for IS_TEXT and
7936 friends need to change. */
7937 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7938 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7950 char *li = locinput;
7953 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7959 if (ST.c1 == CHRTEST_VOID)
7960 goto curly_try_B_min;
7962 ST.oldloc = locinput;
7964 /* set ST.maxpos to the furthest point along the
7965 * string that could possibly match */
7966 if (ST.max == REG_INFTY) {
7967 ST.maxpos = reginfo->strend - 1;
7969 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7972 else if (utf8_target) {
7973 int m = ST.max - ST.min;
7974 for (ST.maxpos = locinput;
7975 m >0 && ST.maxpos < reginfo->strend; m--)
7976 ST.maxpos += UTF8SKIP(ST.maxpos);
7979 ST.maxpos = locinput + ST.max - ST.min;
7980 if (ST.maxpos >= reginfo->strend)
7981 ST.maxpos = reginfo->strend - 1;
7983 goto curly_try_B_min_known;
7987 /* avoid taking address of locinput, so it can remain
7989 char *li = locinput;
7990 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7991 if (ST.count < ST.min)
7994 if ((ST.count > ST.min)
7995 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7997 /* A{m,n} must come at the end of the string, there's
7998 * no point in backing off ... */
8000 /* ...except that $ and \Z can match before *and* after
8001 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8002 We may back off by one in this case. */
8003 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8007 goto curly_try_B_max;
8009 NOT_REACHED; /* NOTREACHED */
8011 case CURLY_B_min_known_fail:
8012 /* failed to find B in a non-greedy match where c1,c2 valid */
8014 REGCP_UNWIND(ST.cp);
8016 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8018 /* Couldn't or didn't -- move forward. */
8019 ST.oldloc = locinput;
8021 locinput += UTF8SKIP(locinput);
8025 curly_try_B_min_known:
8026 /* find the next place where 'B' could work, then call B */
8030 n = (ST.oldloc == locinput) ? 0 : 1;
8031 if (ST.c1 == ST.c2) {
8032 /* set n to utf8_distance(oldloc, locinput) */
8033 while (locinput <= ST.maxpos
8034 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8036 locinput += UTF8SKIP(locinput);
8041 /* set n to utf8_distance(oldloc, locinput) */
8042 while (locinput <= ST.maxpos
8043 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8044 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8046 locinput += UTF8SKIP(locinput);
8051 else { /* Not utf8_target */
8052 if (ST.c1 == ST.c2) {
8053 while (locinput <= ST.maxpos &&
8054 UCHARAT(locinput) != ST.c1)
8058 while (locinput <= ST.maxpos
8059 && UCHARAT(locinput) != ST.c1
8060 && UCHARAT(locinput) != ST.c2)
8063 n = locinput - ST.oldloc;
8065 if (locinput > ST.maxpos)
8068 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8069 * at b; check that everything between oldloc and
8070 * locinput matches */
8071 char *li = ST.oldloc;
8073 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
8075 assert(n == REG_INFTY || locinput == li);
8077 CURLY_SETPAREN(ST.paren, ST.count);
8078 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8080 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8082 NOT_REACHED; /* NOTREACHED */
8084 case CURLY_B_min_fail:
8085 /* failed to find B in a non-greedy match where c1,c2 invalid */
8087 REGCP_UNWIND(ST.cp);
8089 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8091 /* failed -- move forward one */
8093 char *li = locinput;
8094 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
8101 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8102 ST.count > 0)) /* count overflow ? */
8105 CURLY_SETPAREN(ST.paren, ST.count);
8106 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8108 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8112 NOT_REACHED; /* NOTREACHED */
8115 /* a successful greedy match: now try to match B */
8116 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8119 bool could_match = locinput < reginfo->strend;
8121 /* If it could work, try it. */
8122 if (ST.c1 != CHRTEST_VOID && could_match) {
8123 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8125 could_match = memEQ(locinput,
8130 UTF8SKIP(locinput));
8133 could_match = UCHARAT(locinput) == ST.c1
8134 || UCHARAT(locinput) == ST.c2;
8137 if (ST.c1 == CHRTEST_VOID || could_match) {
8138 CURLY_SETPAREN(ST.paren, ST.count);
8139 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8140 NOT_REACHED; /* NOTREACHED */
8145 case CURLY_B_max_fail:
8146 /* failed to find B in a greedy match */
8148 REGCP_UNWIND(ST.cp);
8150 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8153 if (--ST.count < ST.min)
8155 locinput = HOPc(locinput, -1);
8156 goto curly_try_B_max;
8160 case END: /* last op of main pattern */
8163 /* we've just finished A in /(??{A})B/; now continue with B */
8164 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8165 st->u.eval.prev_rex = rex_sv; /* inner */
8167 /* Save *all* the positions. */
8168 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8169 rex_sv = CUR_EVAL.prev_rex;
8170 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8171 SET_reg_curpm(rex_sv);
8172 rex = ReANY(rex_sv);
8173 rexi = RXi_GET(rex);
8175 st->u.eval.prev_curlyx = cur_curlyx;
8176 cur_curlyx = CUR_EVAL.prev_curlyx;
8178 REGCP_SET(st->u.eval.lastcp);
8180 /* Restore parens of the outer rex without popping the
8182 S_regcp_restore(aTHX_ rex, CUR_EVAL.lastcp,
8185 st->u.eval.prev_eval = cur_eval;
8186 cur_eval = CUR_EVAL.prev_eval;
8188 Perl_re_exec_indentf( aTHX_ "EVAL trying tail ... (cur_eval=%p)\n",
8190 if ( nochange_depth )
8193 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8195 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
8196 locinput); /* match B */
8199 if (locinput < reginfo->till) {
8200 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8201 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8203 (long)(locinput - startpos),
8204 (long)(reginfo->till - startpos),
8207 sayNO_SILENT; /* Cannot match: too short. */
8209 sayYES; /* Success! */
8211 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8213 Perl_re_exec_indentf( aTHX_ "%ssubpattern success...%s\n",
8214 depth, PL_colors[4], PL_colors[5]));
8215 sayYES; /* Success! */
8218 #define ST st->u.ifmatch
8223 case SUSPEND: /* (?>A) */
8225 newstart = locinput;
8228 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8230 goto ifmatch_trivial_fail_test;
8232 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8234 ifmatch_trivial_fail_test:
8236 char * const s = HOPBACKc(locinput, scan->flags);
8241 sw = 1 - cBOOL(ST.wanted);
8245 next = scan + ARG(scan);
8253 newstart = locinput;
8257 ST.logical = logical;
8258 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8260 /* execute body of (?...A) */
8261 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8262 NOT_REACHED; /* NOTREACHED */
8265 case IFMATCH_A_fail: /* body of (?...A) failed */
8266 ST.wanted = !ST.wanted;
8269 case IFMATCH_A: /* body of (?...A) succeeded */
8271 sw = cBOOL(ST.wanted);
8273 else if (!ST.wanted)
8276 if (OP(ST.me) != SUSPEND) {
8277 /* restore old position except for (?>...) */
8278 locinput = st->locinput;
8280 scan = ST.me + ARG(ST.me);
8283 continue; /* execute B */
8287 case LONGJMP: /* alternative with many branches compiles to
8288 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8289 next = scan + ARG(scan);
8294 case COMMIT: /* (*COMMIT) */
8295 reginfo->cutpoint = reginfo->strend;
8298 case PRUNE: /* (*PRUNE) */
8300 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8301 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8302 NOT_REACHED; /* NOTREACHED */
8304 case COMMIT_next_fail:
8308 NOT_REACHED; /* NOTREACHED */
8310 case OPFAIL: /* (*FAIL) */
8312 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8314 /* deal with (?(?!)X|Y) properly,
8315 * make sure we trigger the no branch
8316 * of the trailing IFTHEN structure*/
8322 NOT_REACHED; /* NOTREACHED */
8324 #define ST st->u.mark
8325 case MARKPOINT: /* (*MARK:foo) */
8326 ST.prev_mark = mark_state;
8327 ST.mark_name = sv_commit = sv_yes_mark
8328 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8330 ST.mark_loc = locinput;
8331 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8332 NOT_REACHED; /* NOTREACHED */
8334 case MARKPOINT_next:
8335 mark_state = ST.prev_mark;
8337 NOT_REACHED; /* NOTREACHED */
8339 case MARKPOINT_next_fail:
8340 if (popmark && sv_eq(ST.mark_name,popmark))
8342 if (ST.mark_loc > startpoint)
8343 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8344 popmark = NULL; /* we found our mark */
8345 sv_commit = ST.mark_name;
8348 Perl_re_exec_indentf( aTHX_ "%ssetting cutpoint to mark:%"SVf"...%s\n",
8350 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8353 mark_state = ST.prev_mark;
8354 sv_yes_mark = mark_state ?
8355 mark_state->u.mark.mark_name : NULL;
8357 NOT_REACHED; /* NOTREACHED */
8359 case SKIP: /* (*SKIP) */
8361 /* (*SKIP) : if we fail we cut here*/
8362 ST.mark_name = NULL;
8363 ST.mark_loc = locinput;
8364 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8366 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8367 otherwise do nothing. Meaning we need to scan
8369 regmatch_state *cur = mark_state;
8370 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8373 if ( sv_eq( cur->u.mark.mark_name,
8376 ST.mark_name = find;
8377 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8379 cur = cur->u.mark.prev_mark;
8382 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8385 case SKIP_next_fail:
8387 /* (*CUT:NAME) - Set up to search for the name as we
8388 collapse the stack*/
8389 popmark = ST.mark_name;
8391 /* (*CUT) - No name, we cut here.*/
8392 if (ST.mark_loc > startpoint)
8393 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8394 /* but we set sv_commit to latest mark_name if there
8395 is one so they can test to see how things lead to this
8398 sv_commit=mark_state->u.mark.mark_name;
8402 NOT_REACHED; /* NOTREACHED */
8405 case LNBREAK: /* \R */
8406 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8413 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
8414 PTR2UV(scan), OP(scan));
8415 Perl_croak(aTHX_ "regexp memory corruption");
8417 /* this is a point to jump to in order to increment
8418 * locinput by one character */
8420 assert(!NEXTCHR_IS_EOS);
8422 locinput += PL_utf8skip[nextchr];
8423 /* locinput is allowed to go 1 char off the end, but not 2+ */
8424 if (locinput > reginfo->strend)
8433 /* switch break jumps here */
8434 scan = next; /* prepare to execute the next op and ... */
8435 continue; /* ... jump back to the top, reusing st */
8439 /* push a state that backtracks on success */
8440 st->u.yes.prev_yes_state = yes_state;
8444 /* push a new regex state, then continue at scan */
8446 regmatch_state *newst;
8449 regmatch_state *cur = st;
8450 regmatch_state *curyes = yes_state;
8452 regmatch_slab *slab = PL_regmatch_slab;
8453 for (;curd > -1 && (depth-curd < 3);cur--,curd--) {
8454 if (cur < SLAB_FIRST(slab)) {
8456 cur = SLAB_LAST(slab);
8458 Perl_re_exec_indentf( aTHX_ "#%-3d %-10s %s\n",
8460 curd, PL_reg_name[cur->resume_state],
8461 (curyes == cur) ? "yes" : ""
8464 curyes = cur->u.yes.prev_yes_state;
8467 DEBUG_STATE_pp("push")
8470 st->locinput = locinput;
8472 if (newst > SLAB_LAST(PL_regmatch_slab))
8473 newst = S_push_slab(aTHX);
8474 PL_regmatch_state = newst;
8476 locinput = pushinput;
8482 #ifdef SOLARIS_BAD_OPTIMIZER
8483 # undef PL_charclass
8487 * We get here only if there's trouble -- normally "case END" is
8488 * the terminating point.
8490 Perl_croak(aTHX_ "corrupted regexp pointers");
8491 NOT_REACHED; /* NOTREACHED */
8495 /* we have successfully completed a subexpression, but we must now
8496 * pop to the state marked by yes_state and continue from there */
8497 assert(st != yes_state);
8499 while (st != yes_state) {
8501 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8502 PL_regmatch_slab = PL_regmatch_slab->prev;
8503 st = SLAB_LAST(PL_regmatch_slab);
8507 DEBUG_STATE_pp("pop (no final)");
8509 DEBUG_STATE_pp("pop (yes)");
8515 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8516 || yes_state > SLAB_LAST(PL_regmatch_slab))
8518 /* not in this slab, pop slab */
8519 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8520 PL_regmatch_slab = PL_regmatch_slab->prev;
8521 st = SLAB_LAST(PL_regmatch_slab);
8523 depth -= (st - yes_state);
8526 yes_state = st->u.yes.prev_yes_state;
8527 PL_regmatch_state = st;
8530 locinput= st->locinput;
8531 state_num = st->resume_state + no_final;
8532 goto reenter_switch;
8535 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
8536 PL_colors[4], PL_colors[5]));
8538 if (reginfo->info_aux_eval) {
8539 /* each successfully executed (?{...}) block does the equivalent of
8540 * local $^R = do {...}
8541 * When popping the save stack, all these locals would be undone;
8542 * bypass this by setting the outermost saved $^R to the latest
8544 /* I dont know if this is needed or works properly now.
8545 * see code related to PL_replgv elsewhere in this file.
8548 if (oreplsv != GvSV(PL_replgv))
8549 sv_setsv(oreplsv, GvSV(PL_replgv));
8556 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
8558 PL_colors[4], PL_colors[5])
8570 /* there's a previous state to backtrack to */
8572 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8573 PL_regmatch_slab = PL_regmatch_slab->prev;
8574 st = SLAB_LAST(PL_regmatch_slab);
8576 PL_regmatch_state = st;
8577 locinput= st->locinput;
8579 DEBUG_STATE_pp("pop");
8581 if (yes_state == st)
8582 yes_state = st->u.yes.prev_yes_state;
8584 state_num = st->resume_state + 1; /* failure = success + 1 */
8586 goto reenter_switch;
8591 if (rex->intflags & PREGf_VERBARG_SEEN) {
8592 SV *sv_err = get_sv("REGERROR", 1);
8593 SV *sv_mrk = get_sv("REGMARK", 1);
8595 sv_commit = &PL_sv_no;
8597 sv_yes_mark = &PL_sv_yes;
8600 sv_commit = &PL_sv_yes;
8601 sv_yes_mark = &PL_sv_no;
8605 sv_setsv(sv_err, sv_commit);
8606 sv_setsv(sv_mrk, sv_yes_mark);
8610 if (last_pushed_cv) {
8613 PERL_UNUSED_VAR(SP);
8616 assert(!result || locinput - reginfo->strbeg >= 0);
8617 return result ? locinput - reginfo->strbeg : -1;
8621 - regrepeat - repeatedly match something simple, report how many
8623 * What 'simple' means is a node which can be the operand of a quantifier like
8626 * startposp - pointer a pointer to the start position. This is updated
8627 * to point to the byte following the highest successful
8629 * p - the regnode to be repeatedly matched against.
8630 * reginfo - struct holding match state, such as strend
8631 * max - maximum number of things to match.
8632 * depth - (for debugging) backtracking depth.
8635 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8636 regmatch_info *const reginfo, I32 max, int depth)
8638 char *scan; /* Pointer to current position in target string */
8640 char *loceol = reginfo->strend; /* local version */
8641 I32 hardcount = 0; /* How many matches so far */
8642 bool utf8_target = reginfo->is_utf8_target;
8643 unsigned int to_complement = 0; /* Invert the result? */
8645 _char_class_number classnum;
8647 PERL_UNUSED_ARG(depth);
8650 PERL_ARGS_ASSERT_REGREPEAT;
8653 if (max == REG_INFTY)
8655 else if (! utf8_target && loceol - scan > max)
8656 loceol = scan + max;
8658 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8659 * to the maximum of how far we should go in it (leaving it set to the real
8660 * end, if the maximum permissible would take us beyond that). This allows
8661 * us to make the loop exit condition that we haven't gone past <loceol> to
8662 * also mean that we haven't exceeded the max permissible count, saving a
8663 * test each time through the loop. But it assumes that the OP matches a
8664 * single byte, which is true for most of the OPs below when applied to a
8665 * non-UTF-8 target. Those relatively few OPs that don't have this
8666 * characteristic will have to compensate.
8668 * There is no adjustment for UTF-8 targets, as the number of bytes per
8669 * character varies. OPs will have to test both that the count is less
8670 * than the max permissible (using <hardcount> to keep track), and that we
8671 * are still within the bounds of the string (using <loceol>. A few OPs
8672 * match a single byte no matter what the encoding. They can omit the max
8673 * test if, for the UTF-8 case, they do the adjustment that was skipped
8676 * Thus, the code above sets things up for the common case; and exceptional
8677 * cases need extra work; the common case is to make sure <scan> doesn't
8678 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8679 * count doesn't exceed the maximum permissible */
8684 while (scan < loceol && hardcount < max && *scan != '\n') {
8685 scan += UTF8SKIP(scan);
8689 while (scan < loceol && *scan != '\n')
8695 while (scan < loceol && hardcount < max) {
8696 scan += UTF8SKIP(scan);
8704 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8705 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8706 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8710 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8714 /* Can use a simple loop if the pattern char to match on is invariant
8715 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8716 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8717 * true iff it doesn't matter if the argument is in UTF-8 or not */
8718 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8719 if (utf8_target && loceol - scan > max) {
8720 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8721 * since here, to match at all, 1 char == 1 byte */
8722 loceol = scan + max;
8724 while (scan < loceol && UCHARAT(scan) == c) {
8728 else if (reginfo->is_utf8_pat) {
8730 STRLEN scan_char_len;
8732 /* When both target and pattern are UTF-8, we have to do
8734 while (hardcount < max
8736 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8737 && memEQ(scan, STRING(p), scan_char_len))
8739 scan += scan_char_len;
8743 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8745 /* Target isn't utf8; convert the character in the UTF-8
8746 * pattern to non-UTF8, and do a simple loop */
8747 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8748 while (scan < loceol && UCHARAT(scan) == c) {
8751 } /* else pattern char is above Latin1, can't possibly match the
8756 /* Here, the string must be utf8; pattern isn't, and <c> is
8757 * different in utf8 than not, so can't compare them directly.
8758 * Outside the loop, find the two utf8 bytes that represent c, and
8759 * then look for those in sequence in the utf8 string */
8760 U8 high = UTF8_TWO_BYTE_HI(c);
8761 U8 low = UTF8_TWO_BYTE_LO(c);
8763 while (hardcount < max
8764 && scan + 1 < loceol
8765 && UCHARAT(scan) == high
8766 && UCHARAT(scan + 1) == low)
8774 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8775 assert(! reginfo->is_utf8_pat);
8778 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8782 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8783 utf8_flags = FOLDEQ_LOCALE;
8786 case EXACTF: /* This node only generated for non-utf8 patterns */
8787 assert(! reginfo->is_utf8_pat);
8792 if (! utf8_target) {
8795 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8796 | FOLDEQ_S2_FOLDS_SANE;
8801 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8805 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8807 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8809 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8812 if (c1 == CHRTEST_VOID) {
8813 /* Use full Unicode fold matching */
8814 char *tmpeol = reginfo->strend;
8815 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8816 while (hardcount < max
8817 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8818 STRING(p), NULL, pat_len,
8819 reginfo->is_utf8_pat, utf8_flags))
8822 tmpeol = reginfo->strend;
8826 else if (utf8_target) {
8828 while (scan < loceol
8830 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8832 scan += UTF8SKIP(scan);
8837 while (scan < loceol
8839 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8840 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8842 scan += UTF8SKIP(scan);
8847 else if (c1 == c2) {
8848 while (scan < loceol && UCHARAT(scan) == c1) {
8853 while (scan < loceol &&
8854 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8863 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8865 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8866 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8872 while (hardcount < max
8874 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8876 scan += UTF8SKIP(scan);
8880 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan, 0))
8885 /* The argument (FLAGS) to all the POSIX node types is the class number */
8892 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8893 if (! utf8_target) {
8894 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8900 while (hardcount < max && scan < loceol
8901 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8904 scan += UTF8SKIP(scan);
8917 if (utf8_target && loceol - scan > max) {
8919 /* We didn't adjust <loceol> at the beginning of this routine
8920 * because is UTF-8, but it is actually ok to do so, since here, to
8921 * match, 1 char == 1 byte. */
8922 loceol = scan + max;
8924 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8937 if (! utf8_target) {
8938 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8944 /* The complement of something that matches only ASCII matches all
8945 * non-ASCII, plus everything in ASCII that isn't in the class. */
8946 while (hardcount < max && scan < loceol
8947 && (! isASCII_utf8(scan)
8948 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8950 scan += UTF8SKIP(scan);
8961 if (! utf8_target) {
8962 while (scan < loceol && to_complement
8963 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8970 classnum = (_char_class_number) FLAGS(p);
8971 if (classnum < _FIRST_NON_SWASH_CC) {
8973 /* Here, a swash is needed for above-Latin1 code points.
8974 * Process as many Latin1 code points using the built-in rules.
8975 * Go to another loop to finish processing upon encountering
8976 * the first Latin1 code point. We could do that in this loop
8977 * as well, but the other way saves having to test if the swash
8978 * has been loaded every time through the loop: extra space to
8980 while (hardcount < max && scan < loceol) {
8981 if (UTF8_IS_INVARIANT(*scan)) {
8982 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8989 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8990 if (! (to_complement
8991 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
9000 goto found_above_latin1;
9007 /* For these character classes, the knowledge of how to handle
9008 * every code point is compiled in to Perl via a macro. This
9009 * code is written for making the loops as tight as possible.
9010 * It could be refactored to save space instead */
9012 case _CC_ENUM_SPACE:
9013 while (hardcount < max
9015 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
9017 scan += UTF8SKIP(scan);
9021 case _CC_ENUM_BLANK:
9022 while (hardcount < max
9024 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
9026 scan += UTF8SKIP(scan);
9030 case _CC_ENUM_XDIGIT:
9031 while (hardcount < max
9033 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
9035 scan += UTF8SKIP(scan);
9039 case _CC_ENUM_VERTSPACE:
9040 while (hardcount < max
9042 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
9044 scan += UTF8SKIP(scan);
9048 case _CC_ENUM_CNTRL:
9049 while (hardcount < max
9051 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
9053 scan += UTF8SKIP(scan);
9058 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
9064 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
9066 /* Load the swash if not already present */
9067 if (! PL_utf8_swash_ptrs[classnum]) {
9068 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
9069 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
9073 PL_XPosix_ptrs[classnum], &flags);
9076 while (hardcount < max && scan < loceol
9077 && to_complement ^ cBOOL(_generic_utf8(
9080 swash_fetch(PL_utf8_swash_ptrs[classnum],
9084 scan += UTF8SKIP(scan);
9091 while (hardcount < max && scan < loceol &&
9092 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9097 /* LNBREAK can match one or two latin chars, which is ok, but we
9098 * have to use hardcount in this situation, and throw away the
9099 * adjustment to <loceol> done before the switch statement */
9100 loceol = reginfo->strend;
9101 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9110 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9124 /* These are all 0 width, so match right here or not at all. */
9128 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9129 NOT_REACHED; /* NOTREACHED */
9136 c = scan - *startposp;
9140 GET_RE_DEBUG_FLAGS_DECL;
9142 SV * const prop = sv_newmortal();
9143 regprop(prog, prop, p, reginfo, NULL);
9144 Perl_re_exec_indentf( aTHX_ "%s can match %"IVdf" times out of %"IVdf"...\n",
9145 depth, SvPVX_const(prop),(IV)c,(IV)max);
9153 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9155 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9156 create a copy so that changes the caller makes won't change the shared one.
9157 If <altsvp> is non-null, will return NULL in it, for back-compat.
9160 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9162 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9168 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9171 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9174 - reginclass - determine if a character falls into a character class
9176 n is the ANYOF-type regnode
9177 p is the target string
9178 p_end points to one byte beyond the end of the target string
9179 utf8_target tells whether p is in UTF-8.
9181 Returns true if matched; false otherwise.
9183 Note that this can be a synthetic start class, a combination of various
9184 nodes, so things you think might be mutually exclusive, such as locale,
9185 aren't. It can match both locale and non-locale
9190 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9193 const char flags = ANYOF_FLAGS(n);
9197 PERL_ARGS_ASSERT_REGINCLASS;
9199 /* If c is not already the code point, get it. Note that
9200 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9201 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9203 c = utf8n_to_uvchr(p, p_end - p, &c_len,
9204 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
9205 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
9206 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
9207 * UTF8_ALLOW_FFFF */
9208 if (c_len == (STRLEN)-1)
9209 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
9210 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9211 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9215 /* If this character is potentially in the bitmap, check it */
9216 if (c < NUM_ANYOF_CODE_POINTS) {
9217 if (ANYOF_BITMAP_TEST(n, c))
9220 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9227 else if (flags & ANYOF_LOCALE_FLAGS) {
9228 if ((flags & ANYOFL_FOLD)
9230 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9234 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9238 /* The data structure is arranged so bits 0, 2, 4, ... are set
9239 * if the class includes the Posix character class given by
9240 * bit/2; and 1, 3, 5, ... are set if the class includes the
9241 * complemented Posix class given by int(bit/2). So we loop
9242 * through the bits, each time changing whether we complement
9243 * the result or not. Suppose for the sake of illustration
9244 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9245 * is set, it means there is a match for this ANYOF node if the
9246 * character is in the class given by the expression (0 / 2 = 0
9247 * = \w). If it is in that class, isFOO_lc() will return 1,
9248 * and since 'to_complement' is 0, the result will stay TRUE,
9249 * and we exit the loop. Suppose instead that bit 0 is 0, but
9250 * bit 1 is 1. That means there is a match if the character
9251 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9252 * but will on bit 1. On the second iteration 'to_complement'
9253 * will be 1, so the exclusive or will reverse things, so we
9254 * are testing for \W. On the third iteration, 'to_complement'
9255 * will be 0, and we would be testing for \s; the fourth
9256 * iteration would test for \S, etc.
9258 * Note that this code assumes that all the classes are closed
9259 * under folding. For example, if a character matches \w, then
9260 * its fold does too; and vice versa. This should be true for
9261 * any well-behaved locale for all the currently defined Posix
9262 * classes, except for :lower: and :upper:, which are handled
9263 * by the pseudo-class :cased: which matches if either of the
9264 * other two does. To get rid of this assumption, an outer
9265 * loop could be used below to iterate over both the source
9266 * character, and its fold (if different) */
9269 int to_complement = 0;
9271 while (count < ANYOF_MAX) {
9272 if (ANYOF_POSIXL_TEST(n, count)
9273 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9286 /* If the bitmap didn't (or couldn't) match, and something outside the
9287 * bitmap could match, try that. */
9289 if (c >= NUM_ANYOF_CODE_POINTS
9290 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9292 match = TRUE; /* Everything above the bitmap matches */
9294 /* Here doesn't match everything above the bitmap. If there is
9295 * some information available beyond the bitmap, we may find a
9296 * match in it. If so, this is most likely because the code point
9297 * is outside the bitmap range. But rarely, it could be because of
9298 * some other reason. If so, various flags are set to indicate
9299 * this possibility. On ANYOFD nodes, there may be matches that
9300 * happen only when the target string is UTF-8; or for other node
9301 * types, because runtime lookup is needed, regardless of the
9302 * UTF-8ness of the target string. Finally, under /il, there may
9303 * be some matches only possible if the locale is a UTF-8 one. */
9304 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9305 && ( c >= NUM_ANYOF_CODE_POINTS
9306 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9307 && ( UNLIKELY(OP(n) != ANYOFD)
9308 || (utf8_target && ! isASCII_uni(c)
9309 # if NUM_ANYOF_CODE_POINTS > 256
9313 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9314 && IN_UTF8_CTYPE_LOCALE)))
9316 SV* only_utf8_locale = NULL;
9317 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9318 &only_utf8_locale, NULL);
9324 } else { /* Convert to utf8 */
9325 utf8_p = utf8_buffer;
9326 append_utf8_from_native_byte(*p, &utf8_p);
9327 utf8_p = utf8_buffer;
9330 if (swash_fetch(sw, utf8_p, TRUE)) {
9334 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9335 match = _invlist_contains_cp(only_utf8_locale, c);
9339 if (UNICODE_IS_SUPER(c)
9341 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9343 && ckWARN_d(WARN_NON_UNICODE))
9345 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9346 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
9350 #if ANYOF_INVERT != 1
9351 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9353 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9356 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9357 return (flags & ANYOF_INVERT) ^ match;
9361 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9363 /* return the position 'off' UTF-8 characters away from 's', forward if
9364 * 'off' >= 0, backwards if negative. But don't go outside of position
9365 * 'lim', which better be < s if off < 0 */
9367 PERL_ARGS_ASSERT_REGHOP3;
9370 while (off-- && s < lim) {
9371 /* XXX could check well-formedness here */
9376 while (off++ && s > lim) {
9378 if (UTF8_IS_CONTINUED(*s)) {
9379 while (s > lim && UTF8_IS_CONTINUATION(*s))
9381 if (! UTF8_IS_START(*s)) {
9382 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9385 /* XXX could check well-formedness here */
9392 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9394 PERL_ARGS_ASSERT_REGHOP4;
9397 while (off-- && s < rlim) {
9398 /* XXX could check well-formedness here */
9403 while (off++ && s > llim) {
9405 if (UTF8_IS_CONTINUED(*s)) {
9406 while (s > llim && UTF8_IS_CONTINUATION(*s))
9408 if (! UTF8_IS_START(*s)) {
9409 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9412 /* XXX could check well-formedness here */
9418 /* like reghop3, but returns NULL on overrun, rather than returning last
9422 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9424 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9427 while (off-- && s < lim) {
9428 /* XXX could check well-formedness here */
9435 while (off++ && s > lim) {
9437 if (UTF8_IS_CONTINUED(*s)) {
9438 while (s > lim && UTF8_IS_CONTINUATION(*s))
9440 if (! UTF8_IS_START(*s)) {
9441 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9444 /* XXX could check well-formedness here */
9453 /* when executing a regex that may have (?{}), extra stuff needs setting
9454 up that will be visible to the called code, even before the current
9455 match has finished. In particular:
9457 * $_ is localised to the SV currently being matched;
9458 * pos($_) is created if necessary, ready to be updated on each call-out
9460 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9461 isn't set until the current pattern is successfully finished), so that
9462 $1 etc of the match-so-far can be seen;
9463 * save the old values of subbeg etc of the current regex, and set then
9464 to the current string (again, this is normally only done at the end
9469 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9472 regexp *const rex = ReANY(reginfo->prog);
9473 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9475 eval_state->rex = rex;
9478 /* Make $_ available to executed code. */
9479 if (reginfo->sv != DEFSV) {
9481 DEFSV_set(reginfo->sv);
9484 if (!(mg = mg_find_mglob(reginfo->sv))) {
9485 /* prepare for quick setting of pos */
9486 mg = sv_magicext_mglob(reginfo->sv);
9489 eval_state->pos_magic = mg;
9490 eval_state->pos = mg->mg_len;
9491 eval_state->pos_flags = mg->mg_flags;
9494 eval_state->pos_magic = NULL;
9496 if (!PL_reg_curpm) {
9497 /* PL_reg_curpm is a fake PMOP that we can attach the current
9498 * regex to and point PL_curpm at, so that $1 et al are visible
9499 * within a /(?{})/. It's just allocated once per interpreter the
9500 * first time its needed */
9501 Newxz(PL_reg_curpm, 1, PMOP);
9504 SV* const repointer = &PL_sv_undef;
9505 /* this regexp is also owned by the new PL_reg_curpm, which
9506 will try to free it. */
9507 av_push(PL_regex_padav, repointer);
9508 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9509 PL_regex_pad = AvARRAY(PL_regex_padav);
9513 SET_reg_curpm(reginfo->prog);
9514 eval_state->curpm = PL_curpm;
9515 PL_curpm = PL_reg_curpm;
9516 if (RXp_MATCH_COPIED(rex)) {
9517 /* Here is a serious problem: we cannot rewrite subbeg,
9518 since it may be needed if this match fails. Thus
9519 $` inside (?{}) could fail... */
9520 eval_state->subbeg = rex->subbeg;
9521 eval_state->sublen = rex->sublen;
9522 eval_state->suboffset = rex->suboffset;
9523 eval_state->subcoffset = rex->subcoffset;
9525 eval_state->saved_copy = rex->saved_copy;
9527 RXp_MATCH_COPIED_off(rex);
9530 eval_state->subbeg = NULL;
9531 rex->subbeg = (char *)reginfo->strbeg;
9533 rex->subcoffset = 0;
9534 rex->sublen = reginfo->strend - reginfo->strbeg;
9538 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9541 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9543 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9544 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9547 Safefree(aux->poscache);
9551 /* undo the effects of S_setup_eval_state() */
9553 if (eval_state->subbeg) {
9554 regexp * const rex = eval_state->rex;
9555 rex->subbeg = eval_state->subbeg;
9556 rex->sublen = eval_state->sublen;
9557 rex->suboffset = eval_state->suboffset;
9558 rex->subcoffset = eval_state->subcoffset;
9560 rex->saved_copy = eval_state->saved_copy;
9562 RXp_MATCH_COPIED_on(rex);
9564 if (eval_state->pos_magic)
9566 eval_state->pos_magic->mg_len = eval_state->pos;
9567 eval_state->pos_magic->mg_flags =
9568 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9569 | (eval_state->pos_flags & MGf_BYTES);
9572 PL_curpm = eval_state->curpm;
9575 PL_regmatch_state = aux->old_regmatch_state;
9576 PL_regmatch_slab = aux->old_regmatch_slab;
9578 /* free all slabs above current one - this must be the last action
9579 * of this function, as aux and eval_state are allocated within
9580 * slabs and may be freed here */
9582 s = PL_regmatch_slab->next;
9584 PL_regmatch_slab->next = NULL;
9586 regmatch_slab * const osl = s;
9595 S_to_utf8_substr(pTHX_ regexp *prog)
9597 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9598 * on the converted value */
9602 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9605 if (prog->substrs->data[i].substr
9606 && !prog->substrs->data[i].utf8_substr) {
9607 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9608 prog->substrs->data[i].utf8_substr = sv;
9609 sv_utf8_upgrade(sv);
9610 if (SvVALID(prog->substrs->data[i].substr)) {
9611 if (SvTAIL(prog->substrs->data[i].substr)) {
9612 /* Trim the trailing \n that fbm_compile added last
9614 SvCUR_set(sv, SvCUR(sv) - 1);
9615 /* Whilst this makes the SV technically "invalid" (as its
9616 buffer is no longer followed by "\0") when fbm_compile()
9617 adds the "\n" back, a "\0" is restored. */
9618 fbm_compile(sv, FBMcf_TAIL);
9622 if (prog->substrs->data[i].substr == prog->check_substr)
9623 prog->check_utf8 = sv;
9629 S_to_byte_substr(pTHX_ regexp *prog)
9631 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9632 * on the converted value; returns FALSE if can't be converted. */
9636 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9639 if (prog->substrs->data[i].utf8_substr
9640 && !prog->substrs->data[i].substr) {
9641 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9642 if (! sv_utf8_downgrade(sv, TRUE)) {
9645 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9646 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9647 /* Trim the trailing \n that fbm_compile added last
9649 SvCUR_set(sv, SvCUR(sv) - 1);
9650 fbm_compile(sv, FBMcf_TAIL);
9654 prog->substrs->data[i].substr = sv;
9655 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9656 prog->check_substr = sv;
9664 * ex: set ts=8 sts=4 sw=4 et: