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);
1056 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1057 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1058 (IV)(from - strbeg),
1064 (unsigned char*)from,
1067 multiline ? FBMrf_MULTILINE : 0
1069 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1070 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1071 (IV)(from - strbeg),
1073 (IV)(s ? s - strbeg : -1)
1079 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1080 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1081 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1082 s ? "Found" : "Contradicts",
1083 other_ix ? "floating" : "anchored",
1084 quoted, RE_SV_TAIL(must));
1089 /* last1 is latest possible substr location. If we didn't
1090 * find it before there, we never will */
1091 if (last >= last1) {
1092 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1093 "; giving up...\n"));
1097 /* try to find the check substr again at a later
1098 * position. Maybe next time we'll find the "other" substr
1100 other_last = HOP3c(last, 1, strend) /* highest failure */;
1102 other_ix /* i.e. if other-is-float */
1103 ? HOP3c(rx_origin, 1, strend)
1104 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1105 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1106 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1107 (other_ix ? "floating" : "anchored"),
1108 (long)(HOP3c(check_at, 1, strend) - strbeg),
1109 (IV)(rx_origin - strbeg)
1114 if (other_ix) { /* if (other-is-float) */
1115 /* other_last is set to s, not s+1, since its possible for
1116 * a floating substr to fail first time, then succeed
1117 * second time at the same floating position; e.g.:
1118 * "-AB--AABZ" =~ /\wAB\d*Z/
1119 * The first time round, anchored and float match at
1120 * "-(AB)--AAB(Z)" then fail on the initial \w character
1121 * class. Second time round, they match at "-AB--A(AB)(Z)".
1126 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1127 other_last = HOP3c(s, 1, strend);
1129 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1130 " at offset %ld (rx_origin now %"IVdf")...\n",
1132 (IV)(rx_origin - strbeg)
1138 DEBUG_OPTIMISE_MORE_r(
1139 Perl_re_printf( aTHX_
1140 " Check-only match: offset min:%"IVdf" max:%"IVdf
1141 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1142 " strend:%"IVdf"\n",
1143 (IV)prog->check_offset_min,
1144 (IV)prog->check_offset_max,
1145 (IV)(check_at-strbeg),
1146 (IV)(rx_origin-strbeg),
1147 (IV)(rx_origin-check_at),
1153 postprocess_substr_matches:
1155 /* handle the extra constraint of /^.../m if present */
1157 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1160 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1161 " looking for /^/m anchor"));
1163 /* we have failed the constraint of a \n before rx_origin.
1164 * Find the next \n, if any, even if it's beyond the current
1165 * anchored and/or floating substrings. Whether we should be
1166 * scanning ahead for the next \n or the next substr is debatable.
1167 * On the one hand you'd expect rare substrings to appear less
1168 * often than \n's. On the other hand, searching for \n means
1169 * we're effectively flipping between check_substr and "\n" on each
1170 * iteration as the current "rarest" string candidate, which
1171 * means for example that we'll quickly reject the whole string if
1172 * hasn't got a \n, rather than trying every substr position
1176 s = HOP3c(strend, - prog->minlen, strpos);
1177 if (s <= rx_origin ||
1178 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1180 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1181 " Did not find /%s^%s/m...\n",
1182 PL_colors[0], PL_colors[1]));
1186 /* earliest possible origin is 1 char after the \n.
1187 * (since *rx_origin == '\n', it's safe to ++ here rather than
1188 * HOP(rx_origin, 1)) */
1191 if (prog->substrs->check_ix == 0 /* check is anchored */
1192 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1194 /* Position contradicts check-string; either because
1195 * check was anchored (and thus has no wiggle room),
1196 * or check was float and rx_origin is above the float range */
1197 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1198 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1199 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1203 /* if we get here, the check substr must have been float,
1204 * is in range, and we may or may not have had an anchored
1205 * "other" substr which still contradicts */
1206 assert(prog->substrs->check_ix); /* check is float */
1208 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1209 /* whoops, the anchored "other" substr exists, so we still
1210 * contradict. On the other hand, the float "check" substr
1211 * didn't contradict, so just retry the anchored "other"
1213 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1214 " Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1215 PL_colors[0], PL_colors[1],
1216 (IV)(rx_origin - strbeg + prog->anchored_offset),
1217 (IV)(rx_origin - strbeg)
1219 goto do_other_substr;
1222 /* success: we don't contradict the found floating substring
1223 * (and there's no anchored substr). */
1224 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1225 " Found /%s^%s/m with rx_origin %ld...\n",
1226 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1229 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1230 " (multiline anchor test skipped)\n"));
1236 /* if we have a starting character class, then test that extra constraint.
1237 * (trie stclasses are too expensive to use here, we are better off to
1238 * leave it to regmatch itself) */
1240 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1241 const U8* const str = (U8*)STRING(progi->regstclass);
1243 /* XXX this value could be pre-computed */
1244 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1245 ? (reginfo->is_utf8_pat
1246 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1247 : STR_LEN(progi->regstclass))
1251 /* latest pos that a matching float substr constrains rx start to */
1252 char *rx_max_float = NULL;
1254 /* if the current rx_origin is anchored, either by satisfying an
1255 * anchored substring constraint, or a /^.../m constraint, then we
1256 * can reject the current origin if the start class isn't found
1257 * at the current position. If we have a float-only match, then
1258 * rx_origin is constrained to a range; so look for the start class
1259 * in that range. if neither, then look for the start class in the
1260 * whole rest of the string */
1262 /* XXX DAPM it's not clear what the minlen test is for, and why
1263 * it's not used in the floating case. Nothing in the test suite
1264 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1265 * Here are some old comments, which may or may not be correct:
1267 * minlen == 0 is possible if regstclass is \b or \B,
1268 * and the fixed substr is ''$.
1269 * Since minlen is already taken into account, rx_origin+1 is
1270 * before strend; accidentally, minlen >= 1 guaranties no false
1271 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1272 * 0) below assumes that regstclass does not come from lookahead...
1273 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1274 * This leaves EXACTF-ish only, which are dealt with in
1278 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1279 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1280 else if (prog->float_substr || prog->float_utf8) {
1281 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1282 endpos= HOP3c(rx_max_float, cl_l, strend);
1287 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1288 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1289 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1290 (IV)start_shift, (IV)(check_at - strbeg),
1291 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1293 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1296 if (endpos == strend) {
1297 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1298 " Could not match STCLASS...\n") );
1301 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1302 " This position contradicts STCLASS...\n") );
1303 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1304 && !(prog->intflags & PREGf_IMPLICIT))
1307 /* Contradict one of substrings */
1308 if (prog->anchored_substr || prog->anchored_utf8) {
1309 if (prog->substrs->check_ix == 1) { /* check is float */
1310 /* Have both, check_string is floating */
1311 assert(rx_origin + start_shift <= check_at);
1312 if (rx_origin + start_shift != check_at) {
1313 /* not at latest position float substr could match:
1314 * Recheck anchored substring, but not floating.
1315 * The condition above is in bytes rather than
1316 * chars for efficiency. It's conservative, in
1317 * that it errs on the side of doing 'goto
1318 * do_other_substr'. In this case, at worst,
1319 * an extra anchored search may get done, but in
1320 * practice the extra fbm_instr() is likely to
1321 * get skipped anyway. */
1322 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1323 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1324 (long)(other_last - strbeg),
1325 (IV)(rx_origin - strbeg)
1327 goto do_other_substr;
1335 /* In the presence of ml_anch, we might be able to
1336 * find another \n without breaking the current float
1339 /* strictly speaking this should be HOP3c(..., 1, ...),
1340 * but since we goto a block of code that's going to
1341 * search for the next \n if any, its safe here */
1343 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1344 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1345 PL_colors[0], PL_colors[1],
1346 (long)(rx_origin - strbeg)) );
1347 goto postprocess_substr_matches;
1350 /* strictly speaking this can never be true; but might
1351 * be if we ever allow intuit without substrings */
1352 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1355 rx_origin = rx_max_float;
1358 /* at this point, any matching substrings have been
1359 * contradicted. Start again... */
1361 rx_origin = HOP3c(rx_origin, 1, strend);
1363 /* uses bytes rather than char calculations for efficiency.
1364 * It's conservative: it errs on the side of doing 'goto restart',
1365 * where there is code that does a proper char-based test */
1366 if (rx_origin + start_shift + end_shift > strend) {
1367 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1368 " Could not match STCLASS...\n") );
1371 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1372 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1373 (prog->substrs->check_ix ? "floating" : "anchored"),
1374 (long)(rx_origin + start_shift - strbeg),
1375 (IV)(rx_origin - strbeg)
1382 if (rx_origin != s) {
1383 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1384 " By STCLASS: moving %ld --> %ld\n",
1385 (long)(rx_origin - strbeg), (long)(s - strbeg))
1389 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1390 " Does not contradict STCLASS...\n");
1395 /* Decide whether using the substrings helped */
1397 if (rx_origin != strpos) {
1398 /* Fixed substring is found far enough so that the match
1399 cannot start at strpos. */
1401 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1402 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1405 /* The found rx_origin position does not prohibit matching at
1406 * strpos, so calling intuit didn't gain us anything. Decrement
1407 * the BmUSEFUL() count on the check substring, and if we reach
1409 if (!(prog->intflags & PREGf_NAUGHTY)
1411 prog->check_utf8 /* Could be deleted already */
1412 && --BmUSEFUL(prog->check_utf8) < 0
1413 && (prog->check_utf8 == prog->float_utf8)
1415 prog->check_substr /* Could be deleted already */
1416 && --BmUSEFUL(prog->check_substr) < 0
1417 && (prog->check_substr == prog->float_substr)
1420 /* If flags & SOMETHING - do not do it many times on the same match */
1421 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1422 /* XXX Does the destruction order has to change with utf8_target? */
1423 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1424 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1425 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1426 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1427 check = NULL; /* abort */
1428 /* XXXX This is a remnant of the old implementation. It
1429 looks wasteful, since now INTUIT can use many
1430 other heuristics. */
1431 prog->extflags &= ~RXf_USE_INTUIT;
1435 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1436 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1437 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1441 fail_finish: /* Substring not found */
1442 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1443 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1445 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1446 PL_colors[4], PL_colors[5]));
1451 #define DECL_TRIE_TYPE(scan) \
1452 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1453 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1454 trie_utf8l, trie_flu8 } \
1455 trie_type = ((scan->flags == EXACT) \
1456 ? (utf8_target ? trie_utf8 : trie_plain) \
1457 : (scan->flags == EXACTL) \
1458 ? (utf8_target ? trie_utf8l : trie_plain) \
1459 : (scan->flags == EXACTFA) \
1461 ? trie_utf8_exactfa_fold \
1462 : trie_latin_utf8_exactfa_fold) \
1463 : (scan->flags == EXACTFLU8 \
1467 : trie_latin_utf8_fold)))
1469 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1472 U8 flags = FOLD_FLAGS_FULL; \
1473 switch (trie_type) { \
1475 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1476 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1477 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1479 goto do_trie_utf8_fold; \
1480 case trie_utf8_exactfa_fold: \
1481 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1483 case trie_utf8_fold: \
1484 do_trie_utf8_fold: \
1485 if ( foldlen>0 ) { \
1486 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1491 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1492 len = UTF8SKIP(uc); \
1493 skiplen = UVCHR_SKIP( uvc ); \
1494 foldlen -= skiplen; \
1495 uscan = foldbuf + skiplen; \
1498 case trie_latin_utf8_exactfa_fold: \
1499 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1501 case trie_latin_utf8_fold: \
1502 if ( foldlen>0 ) { \
1503 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1509 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1510 skiplen = UVCHR_SKIP( uvc ); \
1511 foldlen -= skiplen; \
1512 uscan = foldbuf + skiplen; \
1516 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1517 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1518 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1522 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1529 charid = trie->charmap[ uvc ]; \
1533 if (widecharmap) { \
1534 SV** const svpp = hv_fetch(widecharmap, \
1535 (char*)&uvc, sizeof(UV), 0); \
1537 charid = (U16)SvIV(*svpp); \
1542 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1543 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1544 startpos, doutf8, depth)
1546 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1550 && (ln == 1 || folder(s, pat_string, ln)) \
1551 && (reginfo->intuit || regtry(reginfo, &s)) )\
1557 #define REXEC_FBC_UTF8_SCAN(CODE) \
1559 while (s < strend) { \
1565 #define REXEC_FBC_SCAN(CODE) \
1567 while (s < strend) { \
1573 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1574 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1576 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1585 #define REXEC_FBC_CLASS_SCAN(COND) \
1586 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1588 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1597 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1598 if (utf8_target) { \
1599 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1602 REXEC_FBC_CLASS_SCAN(COND); \
1605 /* The three macros below are slightly different versions of the same logic.
1607 * The first is for /a and /aa when the target string is UTF-8. This can only
1608 * match ascii, but it must advance based on UTF-8. The other two handle the
1609 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1610 * for the boundary (or non-boundary) between a word and non-word character.
1611 * The utf8 and non-utf8 cases have the same logic, but the details must be
1612 * different. Find the "wordness" of the character just prior to this one, and
1613 * compare it with the wordness of this one. If they differ, we have a
1614 * boundary. At the beginning of the string, pretend that the previous
1615 * character was a new-line.
1617 * All these macros uncleanly have side-effects with each other and outside
1618 * variables. So far it's been too much trouble to clean-up
1620 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1621 * a word character or not.
1622 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1624 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1626 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1627 * are looking for a boundary or for a non-boundary. If we are looking for a
1628 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1629 * see if this tentative match actually works, and if so, to quit the loop
1630 * here. And vice-versa if we are looking for a non-boundary.
1632 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1633 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1634 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1635 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1636 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1637 * complement. But in that branch we complement tmp, meaning that at the
1638 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1639 * which means at the top of the loop in the next iteration, it is
1640 * TEST_NON_UTF8(s-1) */
1641 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1642 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1643 tmp = TEST_NON_UTF8(tmp); \
1644 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1645 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1647 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1654 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1655 * TEST_UTF8 is a macro that for the same input code points returns identically
1656 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1657 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1658 if (s == reginfo->strbeg) { \
1661 else { /* Back-up to the start of the previous character */ \
1662 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1663 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1664 0, UTF8_ALLOW_DEFAULT); \
1666 tmp = TEST_UV(tmp); \
1667 LOAD_UTF8_CHARCLASS_ALNUM(); \
1668 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1669 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1678 /* Like the above two macros. UTF8_CODE is the complete code for handling
1679 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1681 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1682 if (utf8_target) { \
1685 else { /* Not utf8 */ \
1686 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1687 tmp = TEST_NON_UTF8(tmp); \
1688 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1689 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1698 /* Here, things have been set up by the previous code so that tmp is the \
1699 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1700 * utf8ness of the target). We also have to check if this matches against \
1701 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1702 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1704 if (tmp == ! TEST_NON_UTF8('\n')) { \
1711 /* This is the macro to use when we want to see if something that looks like it
1712 * could match, actually does, and if so exits the loop */
1713 #define REXEC_FBC_TRYIT \
1714 if ((reginfo->intuit || regtry(reginfo, &s))) \
1717 /* The only difference between the BOUND and NBOUND cases is that
1718 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1719 * NBOUND. This is accomplished by passing it as either the if or else clause,
1720 * with the other one being empty (PLACEHOLDER is defined as empty).
1722 * The TEST_FOO parameters are for operating on different forms of input, but
1723 * all should be ones that return identically for the same underlying code
1725 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1727 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1728 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1730 #define FBC_BOUND_A(TEST_NON_UTF8) \
1732 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1733 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1735 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1737 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1738 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1740 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1742 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1743 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1747 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1748 IV cp_out = Perl__invlist_search(invlist, cp_in);
1749 assert(cp_out >= 0);
1752 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1753 invmap[S_get_break_val_cp_checked(invlist, cp)]
1755 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1756 invmap[_invlist_search(invlist, cp)]
1759 /* Takes a pointer to an inversion list, a pointer to its corresponding
1760 * inversion map, and a code point, and returns the code point's value
1761 * according to the two arrays. It assumes that all code points have a value.
1762 * This is used as the base macro for macros for particular properties */
1763 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1764 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1766 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1767 * of a code point, returning the value for the first code point in the string.
1768 * And it takes the particular macro name that finds the desired value given a
1769 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1770 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1771 (__ASSERT_(pos < strend) \
1772 /* Note assumes is valid UTF-8 */ \
1773 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1775 /* Returns the GCB value for the input code point */
1776 #define getGCB_VAL_CP(cp) \
1777 _generic_GET_BREAK_VAL_CP( \
1782 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1783 * bounded by pos and strend */
1784 #define getGCB_VAL_UTF8(pos, strend) \
1785 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1787 /* Returns the LB value for the input code point */
1788 #define getLB_VAL_CP(cp) \
1789 _generic_GET_BREAK_VAL_CP( \
1794 /* Returns the LB value for the first code point in the UTF-8 encoded string
1795 * bounded by pos and strend */
1796 #define getLB_VAL_UTF8(pos, strend) \
1797 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1800 /* Returns the SB value for the input code point */
1801 #define getSB_VAL_CP(cp) \
1802 _generic_GET_BREAK_VAL_CP( \
1807 /* Returns the SB value for the first code point in the UTF-8 encoded string
1808 * bounded by pos and strend */
1809 #define getSB_VAL_UTF8(pos, strend) \
1810 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1812 /* Returns the WB value for the input code point */
1813 #define getWB_VAL_CP(cp) \
1814 _generic_GET_BREAK_VAL_CP( \
1819 /* Returns the WB value for the first code point in the UTF-8 encoded string
1820 * bounded by pos and strend */
1821 #define getWB_VAL_UTF8(pos, strend) \
1822 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1824 /* We know what class REx starts with. Try to find this position... */
1825 /* if reginfo->intuit, its a dryrun */
1826 /* annoyingly all the vars in this routine have different names from their counterparts
1827 in regmatch. /grrr */
1829 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1830 const char *strend, regmatch_info *reginfo)
1833 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1834 char *pat_string; /* The pattern's exactish string */
1835 char *pat_end; /* ptr to end char of pat_string */
1836 re_fold_t folder; /* Function for computing non-utf8 folds */
1837 const U8 *fold_array; /* array for folding ords < 256 */
1843 I32 tmp = 1; /* Scratch variable? */
1844 const bool utf8_target = reginfo->is_utf8_target;
1845 UV utf8_fold_flags = 0;
1846 const bool is_utf8_pat = reginfo->is_utf8_pat;
1847 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1848 with a result inverts that result, as 0^1 =
1850 _char_class_number classnum;
1852 RXi_GET_DECL(prog,progi);
1854 PERL_ARGS_ASSERT_FIND_BYCLASS;
1856 /* We know what class it must start with. */
1859 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1861 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1862 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1869 REXEC_FBC_UTF8_CLASS_SCAN(
1870 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1873 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s, 0));
1877 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1878 assert(! is_utf8_pat);
1881 if (is_utf8_pat || utf8_target) {
1882 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1883 goto do_exactf_utf8;
1885 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1886 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1887 goto do_exactf_non_utf8; /* isn't dealt with by these */
1889 case EXACTF: /* This node only generated for non-utf8 patterns */
1890 assert(! is_utf8_pat);
1892 utf8_fold_flags = 0;
1893 goto do_exactf_utf8;
1895 fold_array = PL_fold;
1897 goto do_exactf_non_utf8;
1900 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1901 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1902 utf8_fold_flags = FOLDEQ_LOCALE;
1903 goto do_exactf_utf8;
1905 fold_array = PL_fold_locale;
1906 folder = foldEQ_locale;
1907 goto do_exactf_non_utf8;
1911 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1913 goto do_exactf_utf8;
1916 if (! utf8_target) { /* All code points in this node require
1917 UTF-8 to express. */
1920 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1921 | FOLDEQ_S2_FOLDS_SANE;
1922 goto do_exactf_utf8;
1925 if (is_utf8_pat || utf8_target) {
1926 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1927 goto do_exactf_utf8;
1930 /* Any 'ss' in the pattern should have been replaced by regcomp,
1931 * so we don't have to worry here about this single special case
1932 * in the Latin1 range */
1933 fold_array = PL_fold_latin1;
1934 folder = foldEQ_latin1;
1938 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1939 are no glitches with fold-length differences
1940 between the target string and pattern */
1942 /* The idea in the non-utf8 EXACTF* cases is to first find the
1943 * first character of the EXACTF* node and then, if necessary,
1944 * case-insensitively compare the full text of the node. c1 is the
1945 * first character. c2 is its fold. This logic will not work for
1946 * Unicode semantics and the german sharp ss, which hence should
1947 * not be compiled into a node that gets here. */
1948 pat_string = STRING(c);
1949 ln = STR_LEN(c); /* length to match in octets/bytes */
1951 /* We know that we have to match at least 'ln' bytes (which is the
1952 * same as characters, since not utf8). If we have to match 3
1953 * characters, and there are only 2 availabe, we know without
1954 * trying that it will fail; so don't start a match past the
1955 * required minimum number from the far end */
1956 e = HOP3c(strend, -((SSize_t)ln), s);
1958 if (reginfo->intuit && e < s) {
1959 e = s; /* Due to minlen logic of intuit() */
1963 c2 = fold_array[c1];
1964 if (c1 == c2) { /* If char and fold are the same */
1965 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1968 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1976 /* If one of the operands is in utf8, we can't use the simpler folding
1977 * above, due to the fact that many different characters can have the
1978 * same fold, or portion of a fold, or different- length fold */
1979 pat_string = STRING(c);
1980 ln = STR_LEN(c); /* length to match in octets/bytes */
1981 pat_end = pat_string + ln;
1982 lnc = is_utf8_pat /* length to match in characters */
1983 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1986 /* We have 'lnc' characters to match in the pattern, but because of
1987 * multi-character folding, each character in the target can match
1988 * up to 3 characters (Unicode guarantees it will never exceed
1989 * this) if it is utf8-encoded; and up to 2 if not (based on the
1990 * fact that the Latin 1 folds are already determined, and the
1991 * only multi-char fold in that range is the sharp-s folding to
1992 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1993 * string character. Adjust lnc accordingly, rounding up, so that
1994 * if we need to match at least 4+1/3 chars, that really is 5. */
1995 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1996 lnc = (lnc + expansion - 1) / expansion;
1998 /* As in the non-UTF8 case, if we have to match 3 characters, and
1999 * only 2 are left, it's guaranteed to fail, so don't start a
2000 * match that would require us to go beyond the end of the string
2002 e = HOP3c(strend, -((SSize_t)lnc), s);
2004 if (reginfo->intuit && e < s) {
2005 e = s; /* Due to minlen logic of intuit() */
2008 /* XXX Note that we could recalculate e to stop the loop earlier,
2009 * as the worst case expansion above will rarely be met, and as we
2010 * go along we would usually find that e moves further to the left.
2011 * This would happen only after we reached the point in the loop
2012 * where if there were no expansion we should fail. Unclear if
2013 * worth the expense */
2016 char *my_strend= (char *)strend;
2017 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2018 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2019 && (reginfo->intuit || regtry(reginfo, &s)) )
2023 s += (utf8_target) ? UTF8SKIP(s) : 1;
2029 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2030 if (FLAGS(c) != TRADITIONAL_BOUND) {
2031 if (! IN_UTF8_CTYPE_LOCALE) {
2032 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2033 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2038 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2042 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2043 if (FLAGS(c) != TRADITIONAL_BOUND) {
2044 if (! IN_UTF8_CTYPE_LOCALE) {
2045 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2046 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2051 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2054 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2056 assert(FLAGS(c) == TRADITIONAL_BOUND);
2058 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2061 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2063 assert(FLAGS(c) == TRADITIONAL_BOUND);
2065 FBC_BOUND_A(isWORDCHAR_A);
2068 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2070 assert(FLAGS(c) == TRADITIONAL_BOUND);
2072 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2075 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2077 assert(FLAGS(c) == TRADITIONAL_BOUND);
2079 FBC_NBOUND_A(isWORDCHAR_A);
2083 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2084 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2095 switch((bound_type) FLAGS(c)) {
2096 case TRADITIONAL_BOUND:
2097 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2100 if (s == reginfo->strbeg) {
2101 if (reginfo->intuit || regtry(reginfo, &s))
2106 /* Didn't match. Try at the next position (if there is one) */
2107 s += (utf8_target) ? UTF8SKIP(s) : 1;
2108 if (UNLIKELY(s >= reginfo->strend)) {
2114 GCB_enum before = getGCB_VAL_UTF8(
2116 (U8*)(reginfo->strbeg)),
2117 (U8*) reginfo->strend);
2118 while (s < strend) {
2119 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2120 (U8*) reginfo->strend);
2121 if ( (to_complement ^ isGCB(before,
2123 (U8*) reginfo->strbeg,
2126 && (reginfo->intuit || regtry(reginfo, &s)))
2134 else { /* Not utf8. Everything is a GCB except between CR and
2136 while (s < strend) {
2137 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2138 || UCHARAT(s) != '\n'))
2139 && (reginfo->intuit || regtry(reginfo, &s)))
2147 /* And, since this is a bound, it can match after the final
2148 * character in the string */
2149 if ((reginfo->intuit || regtry(reginfo, &s))) {
2155 if (s == reginfo->strbeg) {
2156 if (reginfo->intuit || regtry(reginfo, &s)) {
2159 s += (utf8_target) ? UTF8SKIP(s) : 1;
2160 if (UNLIKELY(s >= reginfo->strend)) {
2166 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2168 (U8*)(reginfo->strbeg)),
2169 (U8*) reginfo->strend);
2170 while (s < strend) {
2171 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2172 if (to_complement ^ isLB(before,
2174 (U8*) reginfo->strbeg,
2176 (U8*) reginfo->strend,
2178 && (reginfo->intuit || regtry(reginfo, &s)))
2186 else { /* Not utf8. */
2187 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2188 while (s < strend) {
2189 LB_enum after = getLB_VAL_CP((U8) *s);
2190 if (to_complement ^ isLB(before,
2192 (U8*) reginfo->strbeg,
2194 (U8*) reginfo->strend,
2196 && (reginfo->intuit || regtry(reginfo, &s)))
2205 if (reginfo->intuit || regtry(reginfo, &s)) {
2212 if (s == reginfo->strbeg) {
2213 if (reginfo->intuit || regtry(reginfo, &s)) {
2216 s += (utf8_target) ? UTF8SKIP(s) : 1;
2217 if (UNLIKELY(s >= reginfo->strend)) {
2223 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2225 (U8*)(reginfo->strbeg)),
2226 (U8*) reginfo->strend);
2227 while (s < strend) {
2228 SB_enum after = getSB_VAL_UTF8((U8*) s,
2229 (U8*) reginfo->strend);
2230 if ((to_complement ^ isSB(before,
2232 (U8*) reginfo->strbeg,
2234 (U8*) reginfo->strend,
2236 && (reginfo->intuit || regtry(reginfo, &s)))
2244 else { /* Not utf8. */
2245 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2246 while (s < strend) {
2247 SB_enum after = getSB_VAL_CP((U8) *s);
2248 if ((to_complement ^ isSB(before,
2250 (U8*) reginfo->strbeg,
2252 (U8*) reginfo->strend,
2254 && (reginfo->intuit || regtry(reginfo, &s)))
2263 /* Here are at the final position in the target string. The SB
2264 * value is always true here, so matches, depending on other
2266 if (reginfo->intuit || regtry(reginfo, &s)) {
2273 if (s == reginfo->strbeg) {
2274 if (reginfo->intuit || regtry(reginfo, &s)) {
2277 s += (utf8_target) ? UTF8SKIP(s) : 1;
2278 if (UNLIKELY(s >= reginfo->strend)) {
2284 /* We are at a boundary between char_sub_0 and char_sub_1.
2285 * We also keep track of the value for char_sub_-1 as we
2286 * loop through the line. Context may be needed to make a
2287 * determination, and if so, this can save having to
2289 WB_enum previous = WB_UNKNOWN;
2290 WB_enum before = getWB_VAL_UTF8(
2293 (U8*)(reginfo->strbeg)),
2294 (U8*) reginfo->strend);
2295 while (s < strend) {
2296 WB_enum after = getWB_VAL_UTF8((U8*) s,
2297 (U8*) reginfo->strend);
2298 if ((to_complement ^ isWB(previous,
2301 (U8*) reginfo->strbeg,
2303 (U8*) reginfo->strend,
2305 && (reginfo->intuit || regtry(reginfo, &s)))
2314 else { /* Not utf8. */
2315 WB_enum previous = WB_UNKNOWN;
2316 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2317 while (s < strend) {
2318 WB_enum after = getWB_VAL_CP((U8) *s);
2319 if ((to_complement ^ isWB(previous,
2322 (U8*) reginfo->strbeg,
2324 (U8*) reginfo->strend,
2326 && (reginfo->intuit || regtry(reginfo, &s)))
2336 if (reginfo->intuit || regtry(reginfo, &s)) {
2343 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2344 is_LNBREAK_latin1_safe(s, strend)
2348 /* The argument to all the POSIX node types is the class number to pass to
2349 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2356 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2357 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2358 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2373 /* The complement of something that matches only ASCII matches all
2374 * non-ASCII, plus everything in ASCII that isn't in the class. */
2375 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2376 || ! _generic_isCC_A(*s, FLAGS(c)));
2385 /* Don't need to worry about utf8, as it can match only a single
2386 * byte invariant character. */
2387 REXEC_FBC_CLASS_SCAN(
2388 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2396 if (! utf8_target) {
2397 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2403 classnum = (_char_class_number) FLAGS(c);
2404 if (classnum < _FIRST_NON_SWASH_CC) {
2405 while (s < strend) {
2407 /* We avoid loading in the swash as long as possible, but
2408 * should we have to, we jump to a separate loop. This
2409 * extra 'if' statement is what keeps this code from being
2410 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2411 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2412 goto found_above_latin1;
2414 if ((UTF8_IS_INVARIANT(*s)
2415 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2417 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2418 && to_complement ^ cBOOL(
2419 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2423 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2435 else switch (classnum) { /* These classes are implemented as
2437 case _CC_ENUM_SPACE:
2438 REXEC_FBC_UTF8_CLASS_SCAN(
2439 to_complement ^ cBOOL(isSPACE_utf8(s)));
2442 case _CC_ENUM_BLANK:
2443 REXEC_FBC_UTF8_CLASS_SCAN(
2444 to_complement ^ cBOOL(isBLANK_utf8(s)));
2447 case _CC_ENUM_XDIGIT:
2448 REXEC_FBC_UTF8_CLASS_SCAN(
2449 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2452 case _CC_ENUM_VERTSPACE:
2453 REXEC_FBC_UTF8_CLASS_SCAN(
2454 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2457 case _CC_ENUM_CNTRL:
2458 REXEC_FBC_UTF8_CLASS_SCAN(
2459 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2463 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2464 NOT_REACHED; /* NOTREACHED */
2469 found_above_latin1: /* Here we have to load a swash to get the result
2470 for the current code point */
2471 if (! PL_utf8_swash_ptrs[classnum]) {
2472 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2473 PL_utf8_swash_ptrs[classnum] =
2474 _core_swash_init("utf8",
2477 PL_XPosix_ptrs[classnum], &flags);
2480 /* This is a copy of the loop above for swash classes, though using the
2481 * FBC macro instead of being expanded out. Since we've loaded the
2482 * swash, we don't have to check for that each time through the loop */
2483 REXEC_FBC_UTF8_CLASS_SCAN(
2484 to_complement ^ cBOOL(_generic_utf8(
2487 swash_fetch(PL_utf8_swash_ptrs[classnum],
2495 /* what trie are we using right now */
2496 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2497 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2498 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2500 const char *last_start = strend - trie->minlen;
2502 const char *real_start = s;
2504 STRLEN maxlen = trie->maxlen;
2506 U8 **points; /* map of where we were in the input string
2507 when reading a given char. For ASCII this
2508 is unnecessary overhead as the relationship
2509 is always 1:1, but for Unicode, especially
2510 case folded Unicode this is not true. */
2511 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2515 GET_RE_DEBUG_FLAGS_DECL;
2517 /* We can't just allocate points here. We need to wrap it in
2518 * an SV so it gets freed properly if there is a croak while
2519 * running the match */
2522 sv_points=newSV(maxlen * sizeof(U8 *));
2523 SvCUR_set(sv_points,
2524 maxlen * sizeof(U8 *));
2525 SvPOK_on(sv_points);
2526 sv_2mortal(sv_points);
2527 points=(U8**)SvPV_nolen(sv_points );
2528 if ( trie_type != trie_utf8_fold
2529 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2532 bitmap=(U8*)trie->bitmap;
2534 bitmap=(U8*)ANYOF_BITMAP(c);
2536 /* this is the Aho-Corasick algorithm modified a touch
2537 to include special handling for long "unknown char" sequences.
2538 The basic idea being that we use AC as long as we are dealing
2539 with a possible matching char, when we encounter an unknown char
2540 (and we have not encountered an accepting state) we scan forward
2541 until we find a legal starting char.
2542 AC matching is basically that of trie matching, except that when
2543 we encounter a failing transition, we fall back to the current
2544 states "fail state", and try the current char again, a process
2545 we repeat until we reach the root state, state 1, or a legal
2546 transition. If we fail on the root state then we can either
2547 terminate if we have reached an accepting state previously, or
2548 restart the entire process from the beginning if we have not.
2551 while (s <= last_start) {
2552 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2560 U8 *uscan = (U8*)NULL;
2561 U8 *leftmost = NULL;
2563 U32 accepted_word= 0;
2567 while ( state && uc <= (U8*)strend ) {
2569 U32 word = aho->states[ state ].wordnum;
2573 DEBUG_TRIE_EXECUTE_r(
2574 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2575 dump_exec_pos( (char *)uc, c, strend, real_start,
2576 (char *)uc, utf8_target, 0 );
2577 Perl_re_printf( aTHX_
2578 " Scanning for legal start char...\n");
2582 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2586 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2592 if (uc >(U8*)last_start) break;
2596 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2597 if (!leftmost || lpos < leftmost) {
2598 DEBUG_r(accepted_word=word);
2604 points[pointpos++ % maxlen]= uc;
2605 if (foldlen || uc < (U8*)strend) {
2606 REXEC_TRIE_READ_CHAR(trie_type, trie,
2608 uscan, len, uvc, charid, foldlen,
2610 DEBUG_TRIE_EXECUTE_r({
2611 dump_exec_pos( (char *)uc, c, strend,
2612 real_start, s, utf8_target, 0);
2613 Perl_re_printf( aTHX_
2614 " Charid:%3u CP:%4"UVxf" ",
2626 word = aho->states[ state ].wordnum;
2628 base = aho->states[ state ].trans.base;
2630 DEBUG_TRIE_EXECUTE_r({
2632 dump_exec_pos( (char *)uc, c, strend, real_start,
2633 s, utf8_target, 0 );
2634 Perl_re_printf( aTHX_
2635 "%sState: %4"UVxf", word=%"UVxf,
2636 failed ? " Fail transition to " : "",
2637 (UV)state, (UV)word);
2643 ( ((offset = base + charid
2644 - 1 - trie->uniquecharcount)) >= 0)
2645 && ((U32)offset < trie->lasttrans)
2646 && trie->trans[offset].check == state
2647 && (tmp=trie->trans[offset].next))
2649 DEBUG_TRIE_EXECUTE_r(
2650 Perl_re_printf( aTHX_ " - legal\n"));
2655 DEBUG_TRIE_EXECUTE_r(
2656 Perl_re_printf( aTHX_ " - fail\n"));
2658 state = aho->fail[state];
2662 /* we must be accepting here */
2663 DEBUG_TRIE_EXECUTE_r(
2664 Perl_re_printf( aTHX_ " - accepting\n"));
2673 if (!state) state = 1;
2676 if ( aho->states[ state ].wordnum ) {
2677 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2678 if (!leftmost || lpos < leftmost) {
2679 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2684 s = (char*)leftmost;
2685 DEBUG_TRIE_EXECUTE_r({
2686 Perl_re_printf( aTHX_ "Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2687 (UV)accepted_word, (IV)(s - real_start)
2690 if (reginfo->intuit || regtry(reginfo, &s)) {
2696 DEBUG_TRIE_EXECUTE_r({
2697 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2700 DEBUG_TRIE_EXECUTE_r(
2701 Perl_re_printf( aTHX_ "No match.\n"));
2710 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2717 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2718 * flags have same meanings as with regexec_flags() */
2721 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2728 struct regexp *const prog = ReANY(rx);
2730 if (flags & REXEC_COPY_STR) {
2733 DEBUG_C(Perl_re_printf( aTHX_
2734 "Copy on write: regexp capture, type %d\n",
2736 /* Create a new COW SV to share the match string and store
2737 * in saved_copy, unless the current COW SV in saved_copy
2738 * is valid and suitable for our purpose */
2739 if (( prog->saved_copy
2740 && SvIsCOW(prog->saved_copy)
2741 && SvPOKp(prog->saved_copy)
2744 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2746 /* just reuse saved_copy SV */
2747 if (RXp_MATCH_COPIED(prog)) {
2748 Safefree(prog->subbeg);
2749 RXp_MATCH_COPIED_off(prog);
2753 /* create new COW SV to share string */
2754 RX_MATCH_COPY_FREE(rx);
2755 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2757 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2758 assert (SvPOKp(prog->saved_copy));
2759 prog->sublen = strend - strbeg;
2760 prog->suboffset = 0;
2761 prog->subcoffset = 0;
2766 SSize_t max = strend - strbeg;
2769 if ( (flags & REXEC_COPY_SKIP_POST)
2770 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2771 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2772 ) { /* don't copy $' part of string */
2775 /* calculate the right-most part of the string covered
2776 * by a capture. Due to lookahead, this may be to
2777 * the right of $&, so we have to scan all captures */
2778 while (n <= prog->lastparen) {
2779 if (prog->offs[n].end > max)
2780 max = prog->offs[n].end;
2784 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2785 ? prog->offs[0].start
2787 assert(max >= 0 && max <= strend - strbeg);
2790 if ( (flags & REXEC_COPY_SKIP_PRE)
2791 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2792 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2793 ) { /* don't copy $` part of string */
2796 /* calculate the left-most part of the string covered
2797 * by a capture. Due to lookbehind, this may be to
2798 * the left of $&, so we have to scan all captures */
2799 while (min && n <= prog->lastparen) {
2800 if ( prog->offs[n].start != -1
2801 && prog->offs[n].start < min)
2803 min = prog->offs[n].start;
2807 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2808 && min > prog->offs[0].end
2810 min = prog->offs[0].end;
2814 assert(min >= 0 && min <= max && min <= strend - strbeg);
2817 if (RX_MATCH_COPIED(rx)) {
2818 if (sublen > prog->sublen)
2820 (char*)saferealloc(prog->subbeg, sublen+1);
2823 prog->subbeg = (char*)safemalloc(sublen+1);
2824 Copy(strbeg + min, prog->subbeg, sublen, char);
2825 prog->subbeg[sublen] = '\0';
2826 prog->suboffset = min;
2827 prog->sublen = sublen;
2828 RX_MATCH_COPIED_on(rx);
2830 prog->subcoffset = prog->suboffset;
2831 if (prog->suboffset && utf8_target) {
2832 /* Convert byte offset to chars.
2833 * XXX ideally should only compute this if @-/@+
2834 * has been seen, a la PL_sawampersand ??? */
2836 /* If there's a direct correspondence between the
2837 * string which we're matching and the original SV,
2838 * then we can use the utf8 len cache associated with
2839 * the SV. In particular, it means that under //g,
2840 * sv_pos_b2u() will use the previously cached
2841 * position to speed up working out the new length of
2842 * subcoffset, rather than counting from the start of
2843 * the string each time. This stops
2844 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2845 * from going quadratic */
2846 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2847 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2848 SV_GMAGIC|SV_CONST_RETURN);
2850 prog->subcoffset = utf8_length((U8*)strbeg,
2851 (U8*)(strbeg+prog->suboffset));
2855 RX_MATCH_COPY_FREE(rx);
2856 prog->subbeg = strbeg;
2857 prog->suboffset = 0;
2858 prog->subcoffset = 0;
2859 prog->sublen = strend - strbeg;
2867 - regexec_flags - match a regexp against a string
2870 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2871 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2872 /* stringarg: the point in the string at which to begin matching */
2873 /* strend: pointer to null at end of string */
2874 /* strbeg: real beginning of string */
2875 /* minend: end of match must be >= minend bytes after stringarg. */
2876 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2877 * itself is accessed via the pointers above */
2878 /* data: May be used for some additional optimizations.
2879 Currently unused. */
2880 /* flags: For optimizations. See REXEC_* in regexp.h */
2883 struct regexp *const prog = ReANY(rx);
2887 SSize_t minlen; /* must match at least this many chars */
2888 SSize_t dontbother = 0; /* how many characters not to try at end */
2889 const bool utf8_target = cBOOL(DO_UTF8(sv));
2891 RXi_GET_DECL(prog,progi);
2892 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2893 regmatch_info *const reginfo = ®info_buf;
2894 regexp_paren_pair *swap = NULL;
2896 GET_RE_DEBUG_FLAGS_DECL;
2898 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2899 PERL_UNUSED_ARG(data);
2901 /* Be paranoid... */
2903 Perl_croak(aTHX_ "NULL regexp parameter");
2907 debug_start_match(rx, utf8_target, stringarg, strend,
2911 startpos = stringarg;
2913 /* set these early as they may be used by the HOP macros below */
2914 reginfo->strbeg = strbeg;
2915 reginfo->strend = strend;
2916 reginfo->is_utf8_target = cBOOL(utf8_target);
2918 if (prog->intflags & PREGf_GPOS_SEEN) {
2921 /* set reginfo->ganch, the position where \G can match */
2924 (flags & REXEC_IGNOREPOS)
2925 ? stringarg /* use start pos rather than pos() */
2926 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2927 /* Defined pos(): */
2928 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2929 : strbeg; /* pos() not defined; use start of string */
2931 DEBUG_GPOS_r(Perl_re_printf( aTHX_
2932 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2934 /* in the presence of \G, we may need to start looking earlier in
2935 * the string than the suggested start point of stringarg:
2936 * if prog->gofs is set, then that's a known, fixed minimum
2939 * /ab|c\G/: gofs = 1
2940 * or if the minimum offset isn't known, then we have to go back
2941 * to the start of the string, e.g. /w+\G/
2944 if (prog->intflags & PREGf_ANCH_GPOS) {
2946 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2948 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2950 DEBUG_r(Perl_re_printf( aTHX_
2951 "fail: ganch-gofs before earliest possible start\n"));
2956 startpos = reginfo->ganch;
2958 else if (prog->gofs) {
2959 startpos = HOPBACKc(startpos, prog->gofs);
2963 else if (prog->intflags & PREGf_GPOS_FLOAT)
2967 minlen = prog->minlen;
2968 if ((startpos + minlen) > strend || startpos < strbeg) {
2969 DEBUG_r(Perl_re_printf( aTHX_
2970 "Regex match can't succeed, so not even tried\n"));
2974 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2975 * which will call destuctors to reset PL_regmatch_state, free higher
2976 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2977 * regmatch_info_aux_eval */
2979 oldsave = PL_savestack_ix;
2983 if ((prog->extflags & RXf_USE_INTUIT)
2984 && !(flags & REXEC_CHECKED))
2986 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2991 if (prog->extflags & RXf_CHECK_ALL) {
2992 /* we can match based purely on the result of INTUIT.
2993 * Set up captures etc just for $& and $-[0]
2994 * (an intuit-only match wont have $1,$2,..) */
2995 assert(!prog->nparens);
2997 /* s/// doesn't like it if $& is earlier than where we asked it to
2998 * start searching (which can happen on something like /.\G/) */
2999 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3002 /* this should only be possible under \G */
3003 assert(prog->intflags & PREGf_GPOS_SEEN);
3004 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3005 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3009 /* match via INTUIT shouldn't have any captures.
3010 * Let @-, @+, $^N know */
3011 prog->lastparen = prog->lastcloseparen = 0;
3012 RX_MATCH_UTF8_set(rx, utf8_target);
3013 prog->offs[0].start = s - strbeg;
3014 prog->offs[0].end = utf8_target
3015 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3016 : s - strbeg + prog->minlenret;
3017 if ( !(flags & REXEC_NOT_FIRST) )
3018 S_reg_set_capture_string(aTHX_ rx,
3020 sv, flags, utf8_target);
3026 multiline = prog->extflags & RXf_PMf_MULTILINE;
3028 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3029 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3030 "String too short [regexec_flags]...\n"));
3034 /* Check validity of program. */
3035 if (UCHARAT(progi->program) != REG_MAGIC) {
3036 Perl_croak(aTHX_ "corrupted regexp program");
3039 RX_MATCH_TAINTED_off(rx);
3040 RX_MATCH_UTF8_set(rx, utf8_target);
3042 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3043 reginfo->intuit = 0;
3044 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3045 reginfo->warned = FALSE;
3047 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3048 /* see how far we have to get to not match where we matched before */
3049 reginfo->till = stringarg + minend;
3051 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3052 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3053 S_cleanup_regmatch_info_aux has executed (registered by
3054 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3055 magic belonging to this SV.
3056 Not newSVsv, either, as it does not COW.
3058 reginfo->sv = newSV(0);
3059 SvSetSV_nosteal(reginfo->sv, sv);
3060 SAVEFREESV(reginfo->sv);
3063 /* reserve next 2 or 3 slots in PL_regmatch_state:
3064 * slot N+0: may currently be in use: skip it
3065 * slot N+1: use for regmatch_info_aux struct
3066 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3067 * slot N+3: ready for use by regmatch()
3071 regmatch_state *old_regmatch_state;
3072 regmatch_slab *old_regmatch_slab;
3073 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3075 /* on first ever match, allocate first slab */
3076 if (!PL_regmatch_slab) {
3077 Newx(PL_regmatch_slab, 1, regmatch_slab);
3078 PL_regmatch_slab->prev = NULL;
3079 PL_regmatch_slab->next = NULL;
3080 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3083 old_regmatch_state = PL_regmatch_state;
3084 old_regmatch_slab = PL_regmatch_slab;
3086 for (i=0; i <= max; i++) {
3088 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3090 reginfo->info_aux_eval =
3091 reginfo->info_aux->info_aux_eval =
3092 &(PL_regmatch_state->u.info_aux_eval);
3094 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3095 PL_regmatch_state = S_push_slab(aTHX);
3098 /* note initial PL_regmatch_state position; at end of match we'll
3099 * pop back to there and free any higher slabs */
3101 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3102 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3103 reginfo->info_aux->poscache = NULL;
3105 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3107 if ((prog->extflags & RXf_EVAL_SEEN))
3108 S_setup_eval_state(aTHX_ reginfo);
3110 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3113 /* If there is a "must appear" string, look for it. */
3115 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3116 /* We have to be careful. If the previous successful match
3117 was from this regex we don't want a subsequent partially
3118 successful match to clobber the old results.
3119 So when we detect this possibility we add a swap buffer
3120 to the re, and switch the buffer each match. If we fail,
3121 we switch it back; otherwise we leave it swapped.
3124 /* do we need a save destructor here for eval dies? */
3125 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3126 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
3127 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3134 if (prog->recurse_locinput)
3135 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3137 /* Simplest case: anchored match need be tried only once, or with
3138 * MBOL, only at the beginning of each line.
3140 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3141 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3142 * match at the start of the string then it won't match anywhere else
3143 * either; while with /.*.../, if it doesn't match at the beginning,
3144 * the earliest it could match is at the start of the next line */
3146 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3149 if (regtry(reginfo, &s))
3152 if (!(prog->intflags & PREGf_ANCH_MBOL))
3155 /* didn't match at start, try at other newline positions */
3158 dontbother = minlen - 1;
3159 end = HOP3c(strend, -dontbother, strbeg) - 1;
3161 /* skip to next newline */
3163 while (s <= end) { /* note it could be possible to match at the end of the string */
3164 /* NB: newlines are the same in unicode as they are in latin */
3167 if (prog->check_substr || prog->check_utf8) {
3168 /* note that with PREGf_IMPLICIT, intuit can only fail
3169 * or return the start position, so it's of limited utility.
3170 * Nevertheless, I made the decision that the potential for
3171 * quick fail was still worth it - DAPM */
3172 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3176 if (regtry(reginfo, &s))
3180 } /* end anchored search */
3182 if (prog->intflags & PREGf_ANCH_GPOS)
3184 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3185 assert(prog->intflags & PREGf_GPOS_SEEN);
3186 /* For anchored \G, the only position it can match from is
3187 * (ganch-gofs); we already set startpos to this above; if intuit
3188 * moved us on from there, we can't possibly succeed */
3189 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3190 if (s == startpos && regtry(reginfo, &s))
3195 /* Messy cases: unanchored match. */
3196 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3197 /* we have /x+whatever/ */
3198 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3204 if (! prog->anchored_utf8) {
3205 to_utf8_substr(prog);
3207 ch = SvPVX_const(prog->anchored_utf8)[0];
3210 DEBUG_EXECUTE_r( did_match = 1 );
3211 if (regtry(reginfo, &s)) goto got_it;
3213 while (s < strend && *s == ch)
3220 if (! prog->anchored_substr) {
3221 if (! to_byte_substr(prog)) {
3222 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3225 ch = SvPVX_const(prog->anchored_substr)[0];
3228 DEBUG_EXECUTE_r( did_match = 1 );
3229 if (regtry(reginfo, &s)) goto got_it;
3231 while (s < strend && *s == ch)
3236 DEBUG_EXECUTE_r(if (!did_match)
3237 Perl_re_printf( aTHX_
3238 "Did not find anchored character...\n")
3241 else if (prog->anchored_substr != NULL
3242 || prog->anchored_utf8 != NULL
3243 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3244 && prog->float_max_offset < strend - s)) {
3249 char *last1; /* Last position checked before */
3253 if (prog->anchored_substr || prog->anchored_utf8) {
3255 if (! prog->anchored_utf8) {
3256 to_utf8_substr(prog);
3258 must = prog->anchored_utf8;
3261 if (! prog->anchored_substr) {
3262 if (! to_byte_substr(prog)) {
3263 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3266 must = prog->anchored_substr;
3268 back_max = back_min = prog->anchored_offset;
3271 if (! prog->float_utf8) {
3272 to_utf8_substr(prog);
3274 must = prog->float_utf8;
3277 if (! prog->float_substr) {
3278 if (! to_byte_substr(prog)) {
3279 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3282 must = prog->float_substr;
3284 back_max = prog->float_max_offset;
3285 back_min = prog->float_min_offset;
3291 last = HOP3c(strend, /* Cannot start after this */
3292 -(SSize_t)(CHR_SVLEN(must)
3293 - (SvTAIL(must) != 0) + back_min), strbeg);
3295 if (s > reginfo->strbeg)
3296 last1 = HOPc(s, -1);
3298 last1 = s - 1; /* bogus */
3300 /* XXXX check_substr already used to find "s", can optimize if
3301 check_substr==must. */
3303 strend = HOPc(strend, -dontbother);
3304 while ( (s <= last) &&
3305 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3306 (unsigned char*)strend, must,
3307 multiline ? FBMrf_MULTILINE : 0)) ) {
3308 DEBUG_EXECUTE_r( did_match = 1 );
3309 if (HOPc(s, -back_max) > last1) {
3310 last1 = HOPc(s, -back_min);
3311 s = HOPc(s, -back_max);
3314 char * const t = (last1 >= reginfo->strbeg)
3315 ? HOPc(last1, 1) : last1 + 1;
3317 last1 = HOPc(s, -back_min);
3321 while (s <= last1) {
3322 if (regtry(reginfo, &s))
3325 s++; /* to break out of outer loop */
3332 while (s <= last1) {
3333 if (regtry(reginfo, &s))
3339 DEBUG_EXECUTE_r(if (!did_match) {
3340 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3341 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3342 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3343 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3344 ? "anchored" : "floating"),
3345 quoted, RE_SV_TAIL(must));
3349 else if ( (c = progi->regstclass) ) {
3351 const OPCODE op = OP(progi->regstclass);
3352 /* don't bother with what can't match */
3353 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3354 strend = HOPc(strend, -(minlen - 1));
3357 SV * const prop = sv_newmortal();
3358 regprop(prog, prop, c, reginfo, NULL);
3360 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3362 Perl_re_printf( aTHX_
3363 "Matching stclass %.*s against %s (%d bytes)\n",
3364 (int)SvCUR(prop), SvPVX_const(prop),
3365 quoted, (int)(strend - s));
3368 if (find_byclass(prog, c, s, strend, reginfo))
3370 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3374 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3382 if (! prog->float_utf8) {
3383 to_utf8_substr(prog);
3385 float_real = prog->float_utf8;
3388 if (! prog->float_substr) {
3389 if (! to_byte_substr(prog)) {
3390 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3393 float_real = prog->float_substr;
3396 little = SvPV_const(float_real, len);
3397 if (SvTAIL(float_real)) {
3398 /* This means that float_real contains an artificial \n on
3399 * the end due to the presence of something like this:
3400 * /foo$/ where we can match both "foo" and "foo\n" at the
3401 * end of the string. So we have to compare the end of the
3402 * string first against the float_real without the \n and
3403 * then against the full float_real with the string. We
3404 * have to watch out for cases where the string might be
3405 * smaller than the float_real or the float_real without
3407 char *checkpos= strend - len;
3409 Perl_re_printf( aTHX_
3410 "%sChecking for float_real.%s\n",
3411 PL_colors[4], PL_colors[5]));
3412 if (checkpos + 1 < strbeg) {
3413 /* can't match, even if we remove the trailing \n
3414 * string is too short to match */
3416 Perl_re_printf( aTHX_
3417 "%sString shorter than required trailing substring, cannot match.%s\n",
3418 PL_colors[4], PL_colors[5]));
3420 } else if (memEQ(checkpos + 1, little, len - 1)) {
3421 /* can match, the end of the string matches without the
3423 last = checkpos + 1;
3424 } else if (checkpos < strbeg) {
3425 /* cant match, string is too short when the "\n" is
3428 Perl_re_printf( aTHX_
3429 "%sString does not contain required trailing substring, cannot match.%s\n",
3430 PL_colors[4], PL_colors[5]));
3432 } else if (!multiline) {
3433 /* non multiline match, so compare with the "\n" at the
3434 * end of the string */
3435 if (memEQ(checkpos, little, len)) {
3439 Perl_re_printf( aTHX_
3440 "%sString does not contain required trailing substring, cannot match.%s\n",
3441 PL_colors[4], PL_colors[5]));
3445 /* multiline match, so we have to search for a place
3446 * where the full string is located */
3452 last = rninstr(s, strend, little, little + len);
3454 last = strend; /* matching "$" */
3457 /* at one point this block contained a comment which was
3458 * probably incorrect, which said that this was a "should not
3459 * happen" case. Even if it was true when it was written I am
3460 * pretty sure it is not anymore, so I have removed the comment
3461 * and replaced it with this one. Yves */
3463 Perl_re_printf( aTHX_
3464 "%sString does not contain required substring, cannot match.%s\n",
3465 PL_colors[4], PL_colors[5]
3469 dontbother = strend - last + prog->float_min_offset;
3471 if (minlen && (dontbother < minlen))
3472 dontbother = minlen - 1;
3473 strend -= dontbother; /* this one's always in bytes! */
3474 /* We don't know much -- general case. */
3477 if (regtry(reginfo, &s))
3486 if (regtry(reginfo, &s))
3488 } while (s++ < strend);
3496 /* s/// doesn't like it if $& is earlier than where we asked it to
3497 * start searching (which can happen on something like /.\G/) */
3498 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3499 && (prog->offs[0].start < stringarg - strbeg))
3501 /* this should only be possible under \G */
3502 assert(prog->intflags & PREGf_GPOS_SEEN);
3503 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3504 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3510 Perl_re_printf( aTHX_
3511 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3518 /* clean up; this will trigger destructors that will free all slabs
3519 * above the current one, and cleanup the regmatch_info_aux
3520 * and regmatch_info_aux_eval sructs */
3522 LEAVE_SCOPE(oldsave);
3524 if (RXp_PAREN_NAMES(prog))
3525 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3527 /* make sure $`, $&, $', and $digit will work later */
3528 if ( !(flags & REXEC_NOT_FIRST) )
3529 S_reg_set_capture_string(aTHX_ rx,
3530 strbeg, reginfo->strend,
3531 sv, flags, utf8_target);
3536 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3537 PL_colors[4], PL_colors[5]));
3539 /* clean up; this will trigger destructors that will free all slabs
3540 * above the current one, and cleanup the regmatch_info_aux
3541 * and regmatch_info_aux_eval sructs */
3543 LEAVE_SCOPE(oldsave);
3546 /* we failed :-( roll it back */
3547 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
3548 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3553 Safefree(prog->offs);
3560 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3561 * Do inc before dec, in case old and new rex are the same */
3562 #define SET_reg_curpm(Re2) \
3563 if (reginfo->info_aux_eval) { \
3564 (void)ReREFCNT_inc(Re2); \
3565 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3566 PM_SETRE((PL_reg_curpm), (Re2)); \
3571 - regtry - try match at specific point
3573 STATIC bool /* 0 failure, 1 success */
3574 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3577 REGEXP *const rx = reginfo->prog;
3578 regexp *const prog = ReANY(rx);
3581 U32 depth = 0; /* used by REGCP_SET */
3583 RXi_GET_DECL(prog,progi);
3584 GET_RE_DEBUG_FLAGS_DECL;
3586 PERL_ARGS_ASSERT_REGTRY;
3588 reginfo->cutpoint=NULL;
3590 prog->offs[0].start = *startposp - reginfo->strbeg;
3591 prog->lastparen = 0;
3592 prog->lastcloseparen = 0;
3594 /* XXXX What this code is doing here?!!! There should be no need
3595 to do this again and again, prog->lastparen should take care of
3598 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3599 * Actually, the code in regcppop() (which Ilya may be meaning by
3600 * prog->lastparen), is not needed at all by the test suite
3601 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3602 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3603 * Meanwhile, this code *is* needed for the
3604 * above-mentioned test suite tests to succeed. The common theme
3605 * on those tests seems to be returning null fields from matches.
3606 * --jhi updated by dapm */
3608 if (prog->nparens) {
3609 regexp_paren_pair *pp = prog->offs;
3611 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3619 result = regmatch(reginfo, *startposp, progi->program + 1);
3621 prog->offs[0].end = result;
3624 if (reginfo->cutpoint)
3625 *startposp= reginfo->cutpoint;
3626 REGCP_UNWIND(lastcp);
3631 #define sayYES goto yes
3632 #define sayNO goto no
3633 #define sayNO_SILENT goto no_silent
3635 /* we dont use STMT_START/END here because it leads to
3636 "unreachable code" warnings, which are bogus, but distracting. */
3637 #define CACHEsayNO \
3638 if (ST.cache_mask) \
3639 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3642 /* this is used to determine how far from the left messages like
3643 'failed...' are printed in regexec.c. It should be set such that
3644 messages are inline with the regop output that created them.
3646 #define REPORT_CODE_OFF 29
3647 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3650 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3654 PerlIO *f= Perl_debug_log;
3655 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3656 va_start(ap, depth);
3657 PerlIO_printf(f, "%*s|%4"UVuf"| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3658 result = PerlIO_vprintf(f, fmt, ap);
3662 #endif /* DEBUGGING */
3665 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3666 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3667 #define CHRTEST_NOT_A_CP_1 -999
3668 #define CHRTEST_NOT_A_CP_2 -998
3670 /* grab a new slab and return the first slot in it */
3672 STATIC regmatch_state *
3675 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3678 regmatch_slab *s = PL_regmatch_slab->next;
3680 Newx(s, 1, regmatch_slab);
3681 s->prev = PL_regmatch_slab;
3683 PL_regmatch_slab->next = s;
3685 PL_regmatch_slab = s;
3686 return SLAB_FIRST(s);
3690 /* push a new state then goto it */
3692 #define PUSH_STATE_GOTO(state, node, input) \
3693 pushinput = input; \
3695 st->resume_state = state; \
3698 /* push a new state with success backtracking, then goto it */
3700 #define PUSH_YES_STATE_GOTO(state, node, input) \
3701 pushinput = input; \
3703 st->resume_state = state; \
3704 goto push_yes_state;
3711 regmatch() - main matching routine
3713 This is basically one big switch statement in a loop. We execute an op,
3714 set 'next' to point the next op, and continue. If we come to a point which
3715 we may need to backtrack to on failure such as (A|B|C), we push a
3716 backtrack state onto the backtrack stack. On failure, we pop the top
3717 state, and re-enter the loop at the state indicated. If there are no more
3718 states to pop, we return failure.
3720 Sometimes we also need to backtrack on success; for example /A+/, where
3721 after successfully matching one A, we need to go back and try to
3722 match another one; similarly for lookahead assertions: if the assertion
3723 completes successfully, we backtrack to the state just before the assertion
3724 and then carry on. In these cases, the pushed state is marked as
3725 'backtrack on success too'. This marking is in fact done by a chain of
3726 pointers, each pointing to the previous 'yes' state. On success, we pop to
3727 the nearest yes state, discarding any intermediate failure-only states.
3728 Sometimes a yes state is pushed just to force some cleanup code to be
3729 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3730 it to free the inner regex.
3732 Note that failure backtracking rewinds the cursor position, while
3733 success backtracking leaves it alone.
3735 A pattern is complete when the END op is executed, while a subpattern
3736 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3737 ops trigger the "pop to last yes state if any, otherwise return true"
3740 A common convention in this function is to use A and B to refer to the two
3741 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3742 the subpattern to be matched possibly multiple times, while B is the entire
3743 rest of the pattern. Variable and state names reflect this convention.
3745 The states in the main switch are the union of ops and failure/success of
3746 substates associated with with that op. For example, IFMATCH is the op
3747 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3748 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3749 successfully matched A and IFMATCH_A_fail is a state saying that we have
3750 just failed to match A. Resume states always come in pairs. The backtrack
3751 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3752 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3753 on success or failure.
3755 The struct that holds a backtracking state is actually a big union, with
3756 one variant for each major type of op. The variable st points to the
3757 top-most backtrack struct. To make the code clearer, within each
3758 block of code we #define ST to alias the relevant union.
3760 Here's a concrete example of a (vastly oversimplified) IFMATCH
3766 #define ST st->u.ifmatch
3768 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3769 ST.foo = ...; // some state we wish to save
3771 // push a yes backtrack state with a resume value of
3772 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3774 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3777 case IFMATCH_A: // we have successfully executed A; now continue with B
3779 bar = ST.foo; // do something with the preserved value
3782 case IFMATCH_A_fail: // A failed, so the assertion failed
3783 ...; // do some housekeeping, then ...
3784 sayNO; // propagate the failure
3791 For any old-timers reading this who are familiar with the old recursive
3792 approach, the code above is equivalent to:
3794 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3803 ...; // do some housekeeping, then ...
3804 sayNO; // propagate the failure
3807 The topmost backtrack state, pointed to by st, is usually free. If you
3808 want to claim it, populate any ST.foo fields in it with values you wish to
3809 save, then do one of
3811 PUSH_STATE_GOTO(resume_state, node, newinput);
3812 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3814 which sets that backtrack state's resume value to 'resume_state', pushes a
3815 new free entry to the top of the backtrack stack, then goes to 'node'.
3816 On backtracking, the free slot is popped, and the saved state becomes the
3817 new free state. An ST.foo field in this new top state can be temporarily
3818 accessed to retrieve values, but once the main loop is re-entered, it
3819 becomes available for reuse.
3821 Note that the depth of the backtrack stack constantly increases during the
3822 left-to-right execution of the pattern, rather than going up and down with
3823 the pattern nesting. For example the stack is at its maximum at Z at the
3824 end of the pattern, rather than at X in the following:
3826 /(((X)+)+)+....(Y)+....Z/
3828 The only exceptions to this are lookahead/behind assertions and the cut,
3829 (?>A), which pop all the backtrack states associated with A before
3832 Backtrack state structs are allocated in slabs of about 4K in size.
3833 PL_regmatch_state and st always point to the currently active state,
3834 and PL_regmatch_slab points to the slab currently containing
3835 PL_regmatch_state. The first time regmatch() is called, the first slab is
3836 allocated, and is never freed until interpreter destruction. When the slab
3837 is full, a new one is allocated and chained to the end. At exit from
3838 regmatch(), slabs allocated since entry are freed.
3843 #define DEBUG_STATE_pp(pp) \
3845 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
3846 Perl_re_printf( aTHX_ \
3847 "%*s" pp " %s%s%s%s%s\n", \
3848 INDENT_CHARS(depth), "", \
3849 PL_reg_name[st->resume_state], \
3850 ((st==yes_state||st==mark_state) ? "[" : ""), \
3851 ((st==yes_state) ? "Y" : ""), \
3852 ((st==mark_state) ? "M" : ""), \
3853 ((st==yes_state||st==mark_state) ? "]" : "") \
3858 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3863 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3864 const char *start, const char *end, const char *blurb)
3866 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3868 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3873 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3874 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3876 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3877 start, end - start, 60);
3879 Perl_re_printf( aTHX_
3880 "%s%s REx%s %s against %s\n",
3881 PL_colors[4], blurb, PL_colors[5], s0, s1);
3883 if (utf8_target||utf8_pat)
3884 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
3885 utf8_pat ? "pattern" : "",
3886 utf8_pat && utf8_target ? " and " : "",
3887 utf8_target ? "string" : ""
3893 S_dump_exec_pos(pTHX_ const char *locinput,
3894 const regnode *scan,
3895 const char *loc_regeol,
3896 const char *loc_bostr,
3897 const char *loc_reg_starttry,
3898 const bool utf8_target,
3902 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3903 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3904 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3905 /* The part of the string before starttry has one color
3906 (pref0_len chars), between starttry and current
3907 position another one (pref_len - pref0_len chars),
3908 after the current position the third one.
3909 We assume that pref0_len <= pref_len, otherwise we
3910 decrease pref0_len. */
3911 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3912 ? (5 + taill) - l : locinput - loc_bostr;
3915 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3917 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3919 pref0_len = pref_len - (locinput - loc_reg_starttry);
3920 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3921 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3922 ? (5 + taill) - pref_len : loc_regeol - locinput);
3923 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3927 if (pref0_len > pref_len)
3928 pref0_len = pref_len;
3930 const int is_uni = utf8_target ? 1 : 0;
3932 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3933 (locinput - pref_len),pref0_len, 60, 4, 5);
3935 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3936 (locinput - pref_len + pref0_len),
3937 pref_len - pref0_len, 60, 2, 3);
3939 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3940 locinput, loc_regeol - locinput, 10, 0, 1);
3942 const STRLEN tlen=len0+len1+len2;
3943 Perl_re_printf( aTHX_
3944 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|%4u| ",
3945 (IV)(locinput - loc_bostr),
3948 (docolor ? "" : "> <"),
3950 (int)(tlen > 19 ? 0 : 19 - tlen),
3958 /* reg_check_named_buff_matched()
3959 * Checks to see if a named buffer has matched. The data array of
3960 * buffer numbers corresponding to the buffer is expected to reside
3961 * in the regexp->data->data array in the slot stored in the ARG() of
3962 * node involved. Note that this routine doesn't actually care about the
3963 * name, that information is not preserved from compilation to execution.
3964 * Returns the index of the leftmost defined buffer with the given name
3965 * or 0 if non of the buffers matched.
3968 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3971 RXi_GET_DECL(rex,rexi);
3972 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3973 I32 *nums=(I32*)SvPVX(sv_dat);
3975 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3977 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3978 if ((I32)rex->lastparen >= nums[n] &&
3979 rex->offs[nums[n]].end != -1)
3989 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3990 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3992 /* This function determines if there are one or two characters that match
3993 * the first character of the passed-in EXACTish node <text_node>, and if
3994 * so, returns them in the passed-in pointers.
3996 * If it determines that no possible character in the target string can
3997 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3998 * the first character in <text_node> requires UTF-8 to represent, and the
3999 * target string isn't in UTF-8.)
4001 * If there are more than two characters that could match the beginning of
4002 * <text_node>, or if more context is required to determine a match or not,
4003 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4005 * The motiviation behind this function is to allow the caller to set up
4006 * tight loops for matching. If <text_node> is of type EXACT, there is
4007 * only one possible character that can match its first character, and so
4008 * the situation is quite simple. But things get much more complicated if
4009 * folding is involved. It may be that the first character of an EXACTFish
4010 * node doesn't participate in any possible fold, e.g., punctuation, so it
4011 * can be matched only by itself. The vast majority of characters that are
4012 * in folds match just two things, their lower and upper-case equivalents.
4013 * But not all are like that; some have multiple possible matches, or match
4014 * sequences of more than one character. This function sorts all that out.
4016 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4017 * loop of trying to match A*, we know we can't exit where the thing
4018 * following it isn't a B. And something can't be a B unless it is the
4019 * beginning of B. By putting a quick test for that beginning in a tight
4020 * loop, we can rule out things that can't possibly be B without having to
4021 * break out of the loop, thus avoiding work. Similarly, if A is a single
4022 * character, we can make a tight loop matching A*, using the outputs of
4025 * If the target string to match isn't in UTF-8, and there aren't
4026 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4027 * the one or two possible octets (which are characters in this situation)
4028 * that can match. In all cases, if there is only one character that can
4029 * match, *<c1p> and *<c2p> will be identical.
4031 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4032 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4033 * can match the beginning of <text_node>. They should be declared with at
4034 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4035 * undefined what these contain.) If one or both of the buffers are
4036 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4037 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4038 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4039 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4040 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4042 const bool utf8_target = reginfo->is_utf8_target;
4044 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4045 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4046 bool use_chrtest_void = FALSE;
4047 const bool is_utf8_pat = reginfo->is_utf8_pat;
4049 /* Used when we have both utf8 input and utf8 output, to avoid converting
4050 * to/from code points */
4051 bool utf8_has_been_setup = FALSE;
4055 U8 *pat = (U8*)STRING(text_node);
4056 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4058 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4060 /* In an exact node, only one thing can be matched, that first
4061 * character. If both the pat and the target are UTF-8, we can just
4062 * copy the input to the output, avoiding finding the code point of
4067 else if (utf8_target) {
4068 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4069 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4070 utf8_has_been_setup = TRUE;
4073 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4076 else { /* an EXACTFish node */
4077 U8 *pat_end = pat + STR_LEN(text_node);
4079 /* An EXACTFL node has at least some characters unfolded, because what
4080 * they match is not known until now. So, now is the time to fold
4081 * the first few of them, as many as are needed to determine 'c1' and
4082 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4083 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4084 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4085 * need to fold as many characters as a single character can fold to,
4086 * so that later we can check if the first ones are such a multi-char
4087 * fold. But, in such a pattern only locale-problematic characters
4088 * aren't folded, so we can skip this completely if the first character
4089 * in the node isn't one of the tricky ones */
4090 if (OP(text_node) == EXACTFL) {
4092 if (! is_utf8_pat) {
4093 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4095 folded[0] = folded[1] = 's';
4097 pat_end = folded + 2;
4100 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4105 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4107 *(d++) = (U8) toFOLD_LC(*s);
4112 _to_utf8_fold_flags(s,
4115 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4126 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4127 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4129 /* Multi-character folds require more context to sort out. Also
4130 * PL_utf8_foldclosures used below doesn't handle them, so have to
4131 * be handled outside this routine */
4132 use_chrtest_void = TRUE;
4134 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4135 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4137 /* Load the folds hash, if not already done */
4139 if (! PL_utf8_foldclosures) {
4140 _load_PL_utf8_foldclosures();
4143 /* The fold closures data structure is a hash with the keys
4144 * being the UTF-8 of every character that is folded to, like
4145 * 'k', and the values each an array of all code points that
4146 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4147 * Multi-character folds are not included */
4148 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4153 /* Not found in the hash, therefore there are no folds
4154 * containing it, so there is only a single character that
4158 else { /* Does participate in folds */
4159 AV* list = (AV*) *listp;
4160 if (av_tindex_nomg(list) != 1) {
4162 /* If there aren't exactly two folds to this, it is
4163 * outside the scope of this function */
4164 use_chrtest_void = TRUE;
4166 else { /* There are two. Get them */
4167 SV** c_p = av_fetch(list, 0, FALSE);
4169 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4173 c_p = av_fetch(list, 1, FALSE);
4175 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4179 /* Folds that cross the 255/256 boundary are forbidden
4180 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4181 * one is ASCIII. Since the pattern character is above
4182 * 255, and its only other match is below 256, the only
4183 * legal match will be to itself. We have thrown away
4184 * the original, so have to compute which is the one
4186 if ((c1 < 256) != (c2 < 256)) {
4187 if ((OP(text_node) == EXACTFL
4188 && ! IN_UTF8_CTYPE_LOCALE)
4189 || ((OP(text_node) == EXACTFA
4190 || OP(text_node) == EXACTFA_NO_TRIE)
4191 && (isASCII(c1) || isASCII(c2))))
4204 else /* Here, c1 is <= 255 */
4206 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4207 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4208 && ((OP(text_node) != EXACTFA
4209 && OP(text_node) != EXACTFA_NO_TRIE)
4212 /* Here, there could be something above Latin1 in the target
4213 * which folds to this character in the pattern. All such
4214 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4215 * than two characters involved in their folds, so are outside
4216 * the scope of this function */
4217 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4218 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4221 use_chrtest_void = TRUE;
4224 else { /* Here nothing above Latin1 can fold to the pattern
4226 switch (OP(text_node)) {
4228 case EXACTFL: /* /l rules */
4229 c2 = PL_fold_locale[c1];
4232 case EXACTF: /* This node only generated for non-utf8
4234 assert(! is_utf8_pat);
4235 if (! utf8_target) { /* /d rules */
4240 /* /u rules for all these. This happens to work for
4241 * EXACTFA as nothing in Latin1 folds to ASCII */
4242 case EXACTFA_NO_TRIE: /* This node only generated for
4243 non-utf8 patterns */
4244 assert(! is_utf8_pat);
4249 c2 = PL_fold_latin1[c1];
4253 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4254 NOT_REACHED; /* NOTREACHED */
4260 /* Here have figured things out. Set up the returns */
4261 if (use_chrtest_void) {
4262 *c2p = *c1p = CHRTEST_VOID;
4264 else if (utf8_target) {
4265 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4266 uvchr_to_utf8(c1_utf8, c1);
4267 uvchr_to_utf8(c2_utf8, c2);
4270 /* Invariants are stored in both the utf8 and byte outputs; Use
4271 * negative numbers otherwise for the byte ones. Make sure that the
4272 * byte ones are the same iff the utf8 ones are the same */
4273 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4274 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4277 ? CHRTEST_NOT_A_CP_1
4278 : CHRTEST_NOT_A_CP_2;
4280 else if (c1 > 255) {
4281 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4286 *c1p = *c2p = c2; /* c2 is the only representable value */
4288 else { /* c1 is representable; see about c2 */
4290 *c2p = (c2 < 256) ? c2 : c1;
4297 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4299 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4300 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4302 PERL_ARGS_ASSERT_ISGCB;
4304 switch (GCB_table[before][after]) {
4311 case GCB_RI_then_RI:
4314 U8 * temp_pos = (U8 *) curpos;
4316 /* Do not break within emoji flag sequences. That is, do not
4317 * break between regional indicator (RI) symbols if there is an
4318 * odd number of RI characters before the break point.
4319 * GB12 ^ (RI RI)* RI × RI
4320 * GB13 [^RI] (RI RI)* RI × RI */
4322 while (backup_one_GCB(strbeg,
4324 utf8_target) == GCB_Regional_Indicator)
4329 return RI_count % 2 != 1;
4332 case GCB_EX_then_EM:
4334 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4336 U8 * temp_pos = (U8 *) curpos;
4340 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4342 while (prev == GCB_Extend);
4344 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4352 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4353 before, after, GCB_table[before][after]);
4360 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4364 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4366 if (*curpos < strbeg) {
4371 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4372 U8 * prev_prev_char_pos;
4374 if (! prev_char_pos) {
4378 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4379 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4380 *curpos = prev_char_pos;
4381 prev_char_pos = prev_prev_char_pos;
4384 *curpos = (U8 *) strbeg;
4389 if (*curpos - 2 < strbeg) {
4390 *curpos = (U8 *) strbeg;
4394 gcb = getGCB_VAL_CP(*(*curpos - 1));
4400 /* Combining marks attach to most classes that precede them, but this defines
4401 * the exceptions (from TR14) */
4402 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4403 || prev == LB_Mandatory_Break \
4404 || prev == LB_Carriage_Return \
4405 || prev == LB_Line_Feed \
4406 || prev == LB_Next_Line \
4407 || prev == LB_Space \
4408 || prev == LB_ZWSpace))
4411 S_isLB(pTHX_ LB_enum before,
4413 const U8 * const strbeg,
4414 const U8 * const curpos,
4415 const U8 * const strend,
4416 const bool utf8_target)
4418 U8 * temp_pos = (U8 *) curpos;
4419 LB_enum prev = before;
4421 /* Is the boundary between 'before' and 'after' line-breakable?
4422 * Most of this is just a table lookup of a generated table from Unicode
4423 * rules. But some rules require context to decide, and so have to be
4424 * implemented in code */
4426 PERL_ARGS_ASSERT_ISLB;
4428 /* Rule numbers in the comments below are as of Unicode 9.0 */
4432 switch (LB_table[before][after]) {
4437 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4440 case LB_SP_foo + LB_BREAKABLE:
4441 case LB_SP_foo + LB_NOBREAK:
4442 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4444 /* When we have something following a SP, we have to look at the
4445 * context in order to know what to do.
4447 * SP SP should not reach here because LB7: Do not break before
4448 * spaces. (For two spaces in a row there is nothing that
4449 * overrides that) */
4450 assert(after != LB_Space);
4452 /* Here we have a space followed by a non-space. Mostly this is a
4453 * case of LB18: "Break after spaces". But there are complications
4454 * as the handling of spaces is somewhat tricky. They are in a
4455 * number of rules, which have to be applied in priority order, but
4456 * something earlier in the string can cause a rule to be skipped
4457 * and a lower priority rule invoked. A prime example is LB7 which
4458 * says don't break before a space. But rule LB8 (lower priority)
4459 * says that the first break opportunity after a ZW is after any
4460 * span of spaces immediately after it. If a ZW comes before a SP
4461 * in the input, rule LB8 applies, and not LB7. Other such rules
4462 * involve combining marks which are rules 9 and 10, but they may
4463 * override higher priority rules if they come earlier in the
4464 * string. Since we're doing random access into the middle of the
4465 * string, we have to look for rules that should get applied based
4466 * on both string position and priority. Combining marks do not
4467 * attach to either ZW nor SP, so we don't have to consider them
4470 * To check for LB8, we have to find the first non-space character
4471 * before this span of spaces */
4473 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4475 while (prev == LB_Space);
4477 /* LB8 Break before any character following a zero-width space,
4478 * even if one or more spaces intervene.
4480 * So if we have a ZW just before this span, and to get here this
4481 * is the final space in the span. */
4482 if (prev == LB_ZWSpace) {
4486 /* Here, not ZW SP+. There are several rules that have higher
4487 * priority than LB18 and can be resolved now, as they don't depend
4488 * on anything earlier in the string (except ZW, which we have
4489 * already handled). One of these rules is LB11 Do not break
4490 * before Word joiner, but we have specially encoded that in the
4491 * lookup table so it is caught by the single test below which
4492 * catches the other ones. */
4493 if (LB_table[LB_Space][after] - LB_SP_foo
4494 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4499 /* If we get here, we have to XXX consider combining marks. */
4500 if (prev == LB_Combining_Mark) {
4502 /* What happens with these depends on the character they
4505 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4507 while (prev == LB_Combining_Mark);
4509 /* Most times these attach to and inherit the characteristics
4510 * of that character, but not always, and when not, they are to
4511 * be treated as AL by rule LB10. */
4512 if (! LB_CM_ATTACHES_TO(prev)) {
4513 prev = LB_Alphabetic;
4517 /* Here, we have the character preceding the span of spaces all set
4518 * up. We follow LB18: "Break after spaces" unless the table shows
4519 * that is overriden */
4520 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4524 /* We don't know how to treat the CM except by looking at the first
4525 * non-CM character preceding it. ZWJ is treated as CM */
4527 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4529 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4531 /* Here, 'prev' is that first earlier non-CM character. If the CM
4532 * attatches to it, then it inherits the behavior of 'prev'. If it
4533 * doesn't attach, it is to be treated as an AL */
4534 if (! LB_CM_ATTACHES_TO(prev)) {
4535 prev = LB_Alphabetic;
4540 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4541 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4543 /* LB21a Don't break after Hebrew + Hyphen.
4544 * HL (HY | BA) × */
4546 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4547 == LB_Hebrew_Letter)
4552 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4554 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4555 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4557 /* LB25a (PR | PO) × ( OP | HY )? NU */
4558 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4562 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4565 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4566 case LB_SY_or_IS_then_various + LB_NOBREAK:
4568 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4570 LB_enum temp = prev;
4572 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4574 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4575 if (temp == LB_Numeric) {
4579 return LB_table[prev][after] - LB_SY_or_IS_then_various
4583 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4584 case LB_various_then_PO_or_PR + LB_NOBREAK:
4586 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4588 LB_enum temp = prev;
4589 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4591 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4593 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4594 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4596 if (temp == LB_Numeric) {
4599 return LB_various_then_PO_or_PR;
4602 case LB_RI_then_RI + LB_NOBREAK:
4603 case LB_RI_then_RI + LB_BREAKABLE:
4607 /* LB30a Break between two regional indicator symbols if and
4608 * only if there are an even number of regional indicators
4609 * preceding the position of the break.
4611 * sot (RI RI)* RI × RI
4612 * [^RI] (RI RI)* RI × RI */
4614 while (backup_one_LB(strbeg,
4616 utf8_target) == LB_Regional_Indicator)
4621 return RI_count % 2 == 0;
4629 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4630 before, after, LB_table[before][after]);
4637 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4641 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4643 if (*curpos >= strend) {
4648 *curpos += UTF8SKIP(*curpos);
4649 if (*curpos >= strend) {
4652 lb = getLB_VAL_UTF8(*curpos, strend);
4656 if (*curpos >= strend) {
4659 lb = getLB_VAL_CP(**curpos);
4666 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4670 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4672 if (*curpos < strbeg) {
4677 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4678 U8 * prev_prev_char_pos;
4680 if (! prev_char_pos) {
4684 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4685 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4686 *curpos = prev_char_pos;
4687 prev_char_pos = prev_prev_char_pos;
4690 *curpos = (U8 *) strbeg;
4695 if (*curpos - 2 < strbeg) {
4696 *curpos = (U8 *) strbeg;
4700 lb = getLB_VAL_CP(*(*curpos - 1));
4707 S_isSB(pTHX_ SB_enum before,
4709 const U8 * const strbeg,
4710 const U8 * const curpos,
4711 const U8 * const strend,
4712 const bool utf8_target)
4714 /* returns a boolean indicating if there is a Sentence Boundary Break
4715 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4717 U8 * lpos = (U8 *) curpos;
4718 bool has_para_sep = FALSE;
4719 bool has_sp = FALSE;
4721 PERL_ARGS_ASSERT_ISSB;
4723 /* Break at the start and end of text.
4726 But unstated in Unicode is don't break if the text is empty */
4727 if (before == SB_EDGE || after == SB_EDGE) {
4728 return before != after;
4731 /* SB 3: Do not break within CRLF. */
4732 if (before == SB_CR && after == SB_LF) {
4736 /* Break after paragraph separators. CR and LF are considered
4737 * so because Unicode views text as like word processing text where there
4738 * are no newlines except between paragraphs, and the word processor takes
4739 * care of wrapping without there being hard line-breaks in the text *./
4740 SB4. Sep | CR | LF ÷ */
4741 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4745 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4746 * (See Section 6.2, Replacing Ignore Rules.)
4747 SB5. X (Extend | Format)* → X */
4748 if (after == SB_Extend || after == SB_Format) {
4750 /* Implied is that the these characters attach to everything
4751 * immediately prior to them except for those separator-type
4752 * characters. And the rules earlier have already handled the case
4753 * when one of those immediately precedes the extend char */
4757 if (before == SB_Extend || before == SB_Format) {
4758 U8 * temp_pos = lpos;
4759 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4760 if ( backup != SB_EDGE
4769 /* Here, both 'before' and 'backup' are these types; implied is that we
4770 * don't break between them */
4771 if (backup == SB_Extend || backup == SB_Format) {
4776 /* Do not break after ambiguous terminators like period, if they are
4777 * immediately followed by a number or lowercase letter, if they are
4778 * between uppercase letters, if the first following letter (optionally
4779 * after certain punctuation) is lowercase, or if they are followed by
4780 * "continuation" punctuation such as comma, colon, or semicolon. For
4781 * example, a period may be an abbreviation or numeric period, and thus may
4782 * not mark the end of a sentence.
4784 * SB6. ATerm × Numeric */
4785 if (before == SB_ATerm && after == SB_Numeric) {
4789 /* SB7. (Upper | Lower) ATerm × Upper */
4790 if (before == SB_ATerm && after == SB_Upper) {
4791 U8 * temp_pos = lpos;
4792 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4793 if (backup == SB_Upper || backup == SB_Lower) {
4798 /* The remaining rules that aren't the final one, all require an STerm or
4799 * an ATerm after having backed up over some Close* Sp*, and in one case an
4800 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4801 * So do that backup now, setting flags if either Sp or a paragraph
4802 * separator are found */
4804 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4805 has_para_sep = TRUE;
4806 before = backup_one_SB(strbeg, &lpos, utf8_target);
4809 if (before == SB_Sp) {
4812 before = backup_one_SB(strbeg, &lpos, utf8_target);
4814 while (before == SB_Sp);
4817 while (before == SB_Close) {
4818 before = backup_one_SB(strbeg, &lpos, utf8_target);
4821 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4822 * most cases an STerm */
4823 if (before == SB_STerm || before == SB_ATerm) {
4825 /* So, here the lhs matches
4826 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4827 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4828 * The rules that apply here are:
4830 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4831 | LF | STerm | ATerm) )* Lower
4832 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4833 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4834 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4835 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4838 /* And all but SB11 forbid having seen a paragraph separator */
4839 if (! has_para_sep) {
4840 if (before == SB_ATerm) { /* SB8 */
4841 U8 * rpos = (U8 *) curpos;
4842 SB_enum later = after;
4844 while ( later != SB_OLetter
4845 && later != SB_Upper
4846 && later != SB_Lower
4850 && later != SB_STerm
4851 && later != SB_ATerm
4852 && later != SB_EDGE)
4854 later = advance_one_SB(&rpos, strend, utf8_target);
4856 if (later == SB_Lower) {
4861 if ( after == SB_SContinue /* SB8a */
4862 || after == SB_STerm
4863 || after == SB_ATerm)
4868 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4869 if ( after == SB_Close
4879 /* SB10. This and SB9 could probably be combined some way, but khw
4880 * has decided to follow the Unicode rule book precisely for
4881 * simplified maintenance */
4895 /* Otherwise, do not break.
4902 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4906 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4908 if (*curpos >= strend) {
4914 *curpos += UTF8SKIP(*curpos);
4915 if (*curpos >= strend) {
4918 sb = getSB_VAL_UTF8(*curpos, strend);
4919 } while (sb == SB_Extend || sb == SB_Format);
4924 if (*curpos >= strend) {
4927 sb = getSB_VAL_CP(**curpos);
4928 } while (sb == SB_Extend || sb == SB_Format);
4935 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4939 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4941 if (*curpos < strbeg) {
4946 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4947 if (! prev_char_pos) {
4951 /* Back up over Extend and Format. curpos is always just to the right
4952 * of the characater whose value we are getting */
4954 U8 * prev_prev_char_pos;
4955 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4958 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4959 *curpos = prev_char_pos;
4960 prev_char_pos = prev_prev_char_pos;
4963 *curpos = (U8 *) strbeg;
4966 } while (sb == SB_Extend || sb == SB_Format);
4970 if (*curpos - 2 < strbeg) {
4971 *curpos = (U8 *) strbeg;
4975 sb = getSB_VAL_CP(*(*curpos - 1));
4976 } while (sb == SB_Extend || sb == SB_Format);
4983 S_isWB(pTHX_ WB_enum previous,
4986 const U8 * const strbeg,
4987 const U8 * const curpos,
4988 const U8 * const strend,
4989 const bool utf8_target)
4991 /* Return a boolean as to if the boundary between 'before' and 'after' is
4992 * a Unicode word break, using their published algorithm, but tailored for
4993 * Perl by treating spans of white space as one unit. Context may be
4994 * needed to make this determination. If the value for the character
4995 * before 'before' is known, it is passed as 'previous'; otherwise that
4996 * should be set to WB_UNKNOWN. The other input parameters give the
4997 * boundaries and current position in the matching of the string. That
4998 * is, 'curpos' marks the position where the character whose wb value is
4999 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5001 U8 * before_pos = (U8 *) curpos;
5002 U8 * after_pos = (U8 *) curpos;
5003 WB_enum prev = before;
5006 PERL_ARGS_ASSERT_ISWB;
5008 /* Rule numbers in the comments below are as of Unicode 9.0 */
5012 switch (WB_table[before][after]) {
5019 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5020 next = advance_one_WB(&after_pos, strend, utf8_target,
5021 FALSE /* Don't skip Extend nor Format */ );
5022 /* A space immediately preceeding an Extend or Format is attached
5023 * to by them, and hence gets separated from previous spaces.
5024 * Otherwise don't break between horizontal white space */
5025 return next == WB_Extend || next == WB_Format;
5027 /* WB4 Ignore Format and Extend characters, except when they appear at
5028 * the beginning of a region of text. This code currently isn't
5029 * general purpose, but it works as the rules are currently and likely
5030 * to be laid out. The reason it works is that when 'they appear at
5031 * the beginning of a region of text', the rule is to break before
5032 * them, just like any other character. Therefore, the default rule
5033 * applies and we don't have to look in more depth. Should this ever
5034 * change, we would have to have 2 'case' statements, like in the rules
5035 * below, and backup a single character (not spacing over the extend
5036 * ones) and then see if that is one of the region-end characters and
5038 case WB_Ex_or_FO_or_ZWJ_then_foo:
5039 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5042 case WB_DQ_then_HL + WB_BREAKABLE:
5043 case WB_DQ_then_HL + WB_NOBREAK:
5045 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5047 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5048 == WB_Hebrew_Letter)
5053 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5055 case WB_HL_then_DQ + WB_BREAKABLE:
5056 case WB_HL_then_DQ + WB_NOBREAK:
5058 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5060 if (advance_one_WB(&after_pos, strend, utf8_target,
5061 TRUE /* Do skip Extend and Format */ )
5062 == WB_Hebrew_Letter)
5067 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5069 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5070 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5072 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5073 * | Single_Quote) (ALetter | Hebrew_Letter) */
5075 next = advance_one_WB(&after_pos, strend, utf8_target,
5076 TRUE /* Do skip Extend and Format */ );
5078 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5083 return WB_table[before][after]
5084 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5086 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5087 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5089 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5090 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5092 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5093 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5098 return WB_table[before][after]
5099 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5101 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5102 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5104 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5107 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5113 return WB_table[before][after]
5114 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5116 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5117 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5119 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5121 if (advance_one_WB(&after_pos, strend, utf8_target,
5122 TRUE /* Do skip Extend and Format */ )
5128 return WB_table[before][after]
5129 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5131 case WB_RI_then_RI + WB_NOBREAK:
5132 case WB_RI_then_RI + WB_BREAKABLE:
5136 /* Do not break within emoji flag sequences. That is, do not
5137 * break between regional indicator (RI) symbols if there is an
5138 * odd number of RI characters before the potential break
5141 * WB15 ^ (RI RI)* RI × RI
5142 * WB16 [^RI] (RI RI)* RI × RI */
5144 while (backup_one_WB(&previous,
5147 utf8_target) == WB_Regional_Indicator)
5152 return RI_count % 2 != 1;
5160 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5161 before, after, WB_table[before][after]);
5168 S_advance_one_WB(pTHX_ U8 ** curpos,
5169 const U8 * const strend,
5170 const bool utf8_target,
5171 const bool skip_Extend_Format)
5175 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5177 if (*curpos >= strend) {
5183 /* Advance over Extend and Format */
5185 *curpos += UTF8SKIP(*curpos);
5186 if (*curpos >= strend) {
5189 wb = getWB_VAL_UTF8(*curpos, strend);
5190 } while ( skip_Extend_Format
5191 && (wb == WB_Extend || wb == WB_Format));
5196 if (*curpos >= strend) {
5199 wb = getWB_VAL_CP(**curpos);
5200 } while ( skip_Extend_Format
5201 && (wb == WB_Extend || wb == WB_Format));
5208 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5212 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5214 /* If we know what the previous character's break value is, don't have
5216 if (*previous != WB_UNKNOWN) {
5219 /* But we need to move backwards by one */
5221 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5223 *previous = WB_EDGE;
5224 *curpos = (U8 *) strbeg;
5227 *previous = WB_UNKNOWN;
5232 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5235 /* And we always back up over these three types */
5236 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5241 if (*curpos < strbeg) {
5246 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5247 if (! prev_char_pos) {
5251 /* Back up over Extend and Format. curpos is always just to the right
5252 * of the characater whose value we are getting */
5254 U8 * prev_prev_char_pos;
5255 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5259 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5260 *curpos = prev_char_pos;
5261 prev_char_pos = prev_prev_char_pos;
5264 *curpos = (U8 *) strbeg;
5267 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5271 if (*curpos - 2 < strbeg) {
5272 *curpos = (U8 *) strbeg;
5276 wb = getWB_VAL_CP(*(*curpos - 1));
5277 } while (wb == WB_Extend || wb == WB_Format);
5283 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5286 ( ( st )->u.eval.close_paren ) && \
5287 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5290 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5293 ( ( st )->u.eval.close_paren ) && \
5295 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5299 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5300 (st)->u.eval.close_paren = ( (expr) + 1 )
5302 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5303 (st)->u.eval.close_paren = 0
5305 /* returns -1 on failure, $+[0] on success */
5307 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5310 #if PERL_VERSION < 9 && !defined(PERL_CORE)
5314 const bool utf8_target = reginfo->is_utf8_target;
5315 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5316 REGEXP *rex_sv = reginfo->prog;
5317 regexp *rex = ReANY(rex_sv);
5318 RXi_GET_DECL(rex,rexi);
5319 /* the current state. This is a cached copy of PL_regmatch_state */
5321 /* cache heavy used fields of st in registers */
5324 U32 n = 0; /* general value; init to avoid compiler warning */
5325 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5326 char *locinput = startpos;
5327 char *pushinput; /* where to continue after a PUSH */
5328 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5330 bool result = 0; /* return value of S_regmatch */
5331 int depth = 0; /* depth of backtrack stack */
5332 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5333 const U32 max_nochange_depth =
5334 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5335 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5336 regmatch_state *yes_state = NULL; /* state to pop to on success of
5338 /* mark_state piggy backs on the yes_state logic so that when we unwind
5339 the stack on success we can update the mark_state as we go */
5340 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5341 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5342 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5344 bool no_final = 0; /* prevent failure from backtracking? */
5345 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5346 char *startpoint = locinput;
5347 SV *popmark = NULL; /* are we looking for a mark? */
5348 SV *sv_commit = NULL; /* last mark name seen in failure */
5349 SV *sv_yes_mark = NULL; /* last mark name we have seen
5350 during a successful match */
5351 U32 lastopen = 0; /* last open we saw */
5352 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
5353 SV* const oreplsv = GvSVn(PL_replgv);
5354 /* these three flags are set by various ops to signal information to
5355 * the very next op. They have a useful lifetime of exactly one loop
5356 * iteration, and are not preserved or restored by state pushes/pops
5358 bool sw = 0; /* the condition value in (?(cond)a|b) */
5359 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5360 int logical = 0; /* the following EVAL is:
5364 or the following IFMATCH/UNLESSM is:
5365 false: plain (?=foo)
5366 true: used as a condition: (?(?=foo))
5368 PAD* last_pad = NULL;
5370 U8 gimme = G_SCALAR;
5371 CV *caller_cv = NULL; /* who called us */
5372 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5373 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
5374 U32 maxopenparen = 0; /* max '(' index seen so far */
5375 int to_complement; /* Invert the result? */
5376 _char_class_number classnum;
5377 bool is_utf8_pat = reginfo->is_utf8_pat;
5380 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5381 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5382 # define SOLARIS_BAD_OPTIMIZER
5383 const U32 *pl_charclass_dup = PL_charclass;
5384 # define PL_charclass pl_charclass_dup
5388 GET_RE_DEBUG_FLAGS_DECL;
5391 /* protect against undef(*^R) */
5392 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5394 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5395 multicall_oldcatch = 0;
5396 PERL_UNUSED_VAR(multicall_cop);
5398 PERL_ARGS_ASSERT_REGMATCH;
5400 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5401 Perl_re_printf( aTHX_ "regmatch start\n");
5404 st = PL_regmatch_state;
5406 /* Note that nextchr is a byte even in UTF */
5409 while (scan != NULL) {
5412 next = scan + NEXT_OFF(scan);
5415 state_num = OP(scan);
5419 if (state_num <= REGNODE_MAX) {
5420 SV * const prop = sv_newmortal();
5421 regnode *rnext = regnext(scan);
5423 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5424 regprop(rex, prop, scan, reginfo, NULL);
5425 Perl_re_printf( aTHX_
5426 "%*s%"IVdf":%s(%"IVdf")\n",
5427 INDENT_CHARS(depth), "",
5428 (IV)(scan - rexi->program),
5430 (PL_regkind[OP(scan)] == END || !rnext) ?
5431 0 : (IV)(rnext - rexi->program));
5438 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5440 switch (state_num) {
5441 case SBOL: /* /^../ and /\A../ */
5442 if (locinput == reginfo->strbeg)
5446 case MBOL: /* /^../m */
5447 if (locinput == reginfo->strbeg ||
5448 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5455 if (locinput == reginfo->ganch)
5459 case KEEPS: /* \K */
5460 /* update the startpoint */
5461 st->u.keeper.val = rex->offs[0].start;
5462 rex->offs[0].start = locinput - reginfo->strbeg;
5463 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5464 NOT_REACHED; /* NOTREACHED */
5466 case KEEPS_next_fail:
5467 /* rollback the start point change */
5468 rex->offs[0].start = st->u.keeper.val;
5470 NOT_REACHED; /* NOTREACHED */
5472 case MEOL: /* /..$/m */
5473 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5477 case SEOL: /* /..$/ */
5478 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5480 if (reginfo->strend - locinput > 1)
5485 if (!NEXTCHR_IS_EOS)
5489 case SANY: /* /./s */
5492 goto increment_locinput;
5494 case REG_ANY: /* /./ */
5495 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5497 goto increment_locinput;
5501 #define ST st->u.trie
5502 case TRIEC: /* (ab|cd) with known charclass */
5503 /* In this case the charclass data is available inline so
5504 we can fail fast without a lot of extra overhead.
5506 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5508 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5509 depth, PL_colors[4], PL_colors[5])
5512 NOT_REACHED; /* NOTREACHED */
5515 case TRIE: /* (ab|cd) */
5516 /* the basic plan of execution of the trie is:
5517 * At the beginning, run though all the states, and
5518 * find the longest-matching word. Also remember the position
5519 * of the shortest matching word. For example, this pattern:
5522 * when matched against the string "abcde", will generate
5523 * accept states for all words except 3, with the longest
5524 * matching word being 4, and the shortest being 2 (with
5525 * the position being after char 1 of the string).
5527 * Then for each matching word, in word order (i.e. 1,2,4,5),
5528 * we run the remainder of the pattern; on each try setting
5529 * the current position to the character following the word,
5530 * returning to try the next word on failure.
5532 * We avoid having to build a list of words at runtime by
5533 * using a compile-time structure, wordinfo[].prev, which
5534 * gives, for each word, the previous accepting word (if any).
5535 * In the case above it would contain the mappings 1->2, 2->0,
5536 * 3->0, 4->5, 5->1. We can use this table to generate, from
5537 * the longest word (4 above), a list of all words, by
5538 * following the list of prev pointers; this gives us the
5539 * unordered list 4,5,1,2. Then given the current word we have
5540 * just tried, we can go through the list and find the
5541 * next-biggest word to try (so if we just failed on word 2,
5542 * the next in the list is 4).
5544 * Since at runtime we don't record the matching position in
5545 * the string for each word, we have to work that out for
5546 * each word we're about to process. The wordinfo table holds
5547 * the character length of each word; given that we recorded
5548 * at the start: the position of the shortest word and its
5549 * length in chars, we just need to move the pointer the
5550 * difference between the two char lengths. Depending on
5551 * Unicode status and folding, that's cheap or expensive.
5553 * This algorithm is optimised for the case where are only a
5554 * small number of accept states, i.e. 0,1, or maybe 2.
5555 * With lots of accepts states, and having to try all of them,
5556 * it becomes quadratic on number of accept states to find all
5561 /* what type of TRIE am I? (utf8 makes this contextual) */
5562 DECL_TRIE_TYPE(scan);
5564 /* what trie are we using right now */
5565 reg_trie_data * const trie
5566 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5567 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5568 U32 state = trie->startstate;
5570 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5571 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5573 && UTF8_IS_ABOVE_LATIN1(nextchr)
5574 && scan->flags == EXACTL)
5576 /* We only output for EXACTL, as we let the folder
5577 * output this message for EXACTFLU8 to avoid
5579 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5584 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5586 if (trie->states[ state ].wordnum) {
5588 Perl_re_exec_indentf( aTHX_ "%smatched empty string...%s\n",
5589 depth, PL_colors[4], PL_colors[5])
5595 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5596 depth, PL_colors[4], PL_colors[5])
5603 U8 *uc = ( U8* )locinput;
5607 U8 *uscan = (U8*)NULL;
5608 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5609 U32 charcount = 0; /* how many input chars we have matched */
5610 U32 accepted = 0; /* have we seen any accepting states? */
5612 ST.jump = trie->jump;
5615 ST.longfold = FALSE; /* char longer if folded => it's harder */
5618 /* fully traverse the TRIE; note the position of the
5619 shortest accept state and the wordnum of the longest
5622 while ( state && uc <= (U8*)(reginfo->strend) ) {
5623 U32 base = trie->states[ state ].trans.base;
5627 wordnum = trie->states[ state ].wordnum;
5629 if (wordnum) { /* it's an accept state */
5632 /* record first match position */
5634 ST.firstpos = (U8*)locinput;
5639 ST.firstchars = charcount;
5642 if (!ST.nextword || wordnum < ST.nextword)
5643 ST.nextword = wordnum;
5644 ST.topword = wordnum;
5647 DEBUG_TRIE_EXECUTE_r({
5648 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
5649 Perl_re_exec_indentf( aTHX_
5650 "%sState: %4"UVxf" Accepted: %c ",
5651 depth, PL_colors[4],
5652 (UV)state, (accepted ? 'Y' : 'N'));
5655 /* read a char and goto next state */
5656 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5658 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5659 uscan, len, uvc, charid, foldlen,
5666 base + charid - 1 - trie->uniquecharcount)) >= 0)
5668 && ((U32)offset < trie->lasttrans)
5669 && trie->trans[offset].check == state)
5671 state = trie->trans[offset].next;
5682 DEBUG_TRIE_EXECUTE_r(
5683 Perl_re_printf( aTHX_
5684 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5685 charid, uvc, (UV)state, PL_colors[5] );
5691 /* calculate total number of accept states */
5696 w = trie->wordinfo[w].prev;
5699 ST.accepted = accepted;
5703 Perl_re_exec_indentf( aTHX_ "%sgot %"IVdf" possible matches%s\n",
5705 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5707 goto trie_first_try; /* jump into the fail handler */
5709 NOT_REACHED; /* NOTREACHED */
5711 case TRIE_next_fail: /* we failed - try next alternative */
5715 REGCP_UNWIND(ST.cp);
5716 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5718 if (!--ST.accepted) {
5720 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
5728 /* Find next-highest word to process. Note that this code
5729 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5732 U16 const nextword = ST.nextword;
5733 reg_trie_wordinfo * const wordinfo
5734 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5735 for (word=ST.topword; word; word=wordinfo[word].prev) {
5736 if (word > nextword && (!min || word < min))
5749 ST.lastparen = rex->lastparen;
5750 ST.lastcloseparen = rex->lastcloseparen;
5754 /* find start char of end of current word */
5756 U32 chars; /* how many chars to skip */
5757 reg_trie_data * const trie
5758 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5760 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5762 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5767 /* the hard option - fold each char in turn and find
5768 * its folded length (which may be different */
5769 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5777 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5785 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5790 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5806 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5807 ? ST.jump[ST.nextword]
5811 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
5819 if (ST.accepted > 1 || has_cutgroup) {
5820 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5821 NOT_REACHED; /* NOTREACHED */
5823 /* only one choice left - just continue */
5825 AV *const trie_words
5826 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5827 SV ** const tmp = trie_words
5828 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5829 SV *sv= tmp ? sv_newmortal() : NULL;
5831 Perl_re_exec_indentf( aTHX_ "%sonly one match left, short-circuiting: #%d <%s>%s\n",
5832 depth, PL_colors[4],
5834 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5835 PL_colors[0], PL_colors[1],
5836 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5838 : "not compiled under -Dr",
5842 locinput = (char*)uc;
5843 continue; /* execute rest of RE */
5848 case EXACTL: /* /abc/l */
5849 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5851 /* Complete checking would involve going through every character
5852 * matched by the string to see if any is above latin1. But the
5853 * comparision otherwise might very well be a fast assembly
5854 * language routine, and I (khw) don't think slowing things down
5855 * just to check for this warning is worth it. So this just checks
5856 * the first character */
5857 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5858 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5861 case EXACT: { /* /abc/ */
5862 char *s = STRING(scan);
5864 if (utf8_target != is_utf8_pat) {
5865 /* The target and the pattern have differing utf8ness. */
5867 const char * const e = s + ln;
5870 /* The target is utf8, the pattern is not utf8.
5871 * Above-Latin1 code points can't match the pattern;
5872 * invariants match exactly, and the other Latin1 ones need
5873 * to be downgraded to a single byte in order to do the
5874 * comparison. (If we could be confident that the target
5875 * is not malformed, this could be refactored to have fewer
5876 * tests by just assuming that if the first bytes match, it
5877 * is an invariant, but there are tests in the test suite
5878 * dealing with (??{...}) which violate this) */
5880 if (l >= reginfo->strend
5881 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5885 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5892 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5902 /* The target is not utf8, the pattern is utf8. */
5904 if (l >= reginfo->strend
5905 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5909 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5916 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5928 /* The target and the pattern have the same utf8ness. */
5929 /* Inline the first character, for speed. */
5930 if (reginfo->strend - locinput < ln
5931 || UCHARAT(s) != nextchr
5932 || (ln > 1 && memNE(s, locinput, ln)))
5941 case EXACTFL: { /* /abc/il */
5943 const U8 * fold_array;
5945 U32 fold_utf8_flags;
5947 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5948 folder = foldEQ_locale;
5949 fold_array = PL_fold_locale;
5950 fold_utf8_flags = FOLDEQ_LOCALE;
5953 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5954 is effectively /u; hence to match, target
5956 if (! utf8_target) {
5959 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5960 | FOLDEQ_S1_FOLDS_SANE;
5961 folder = foldEQ_latin1;
5962 fold_array = PL_fold_latin1;
5965 case EXACTFU_SS: /* /\x{df}/iu */
5966 case EXACTFU: /* /abc/iu */
5967 folder = foldEQ_latin1;
5968 fold_array = PL_fold_latin1;
5969 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5972 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5974 assert(! is_utf8_pat);
5976 case EXACTFA: /* /abc/iaa */
5977 folder = foldEQ_latin1;
5978 fold_array = PL_fold_latin1;
5979 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5982 case EXACTF: /* /abc/i This node only generated for
5983 non-utf8 patterns */
5984 assert(! is_utf8_pat);
5986 fold_array = PL_fold;
5987 fold_utf8_flags = 0;
5995 || state_num == EXACTFU_SS
5996 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5998 /* Either target or the pattern are utf8, or has the issue where
5999 * the fold lengths may differ. */
6000 const char * const l = locinput;
6001 char *e = reginfo->strend;
6003 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6004 l, &e, 0, utf8_target, fold_utf8_flags))
6012 /* Neither the target nor the pattern are utf8 */
6013 if (UCHARAT(s) != nextchr
6015 && UCHARAT(s) != fold_array[nextchr])
6019 if (reginfo->strend - locinput < ln)
6021 if (ln > 1 && ! folder(s, locinput, ln))
6027 case NBOUNDL: /* /\B/l */
6031 case BOUNDL: /* /\b/l */
6034 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6036 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6037 if (! IN_UTF8_CTYPE_LOCALE) {
6038 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6039 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6045 if (locinput == reginfo->strbeg)
6046 b1 = isWORDCHAR_LC('\n');
6048 b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
6049 (U8*)(reginfo->strbeg)));
6051 b2 = (NEXTCHR_IS_EOS)
6052 ? isWORDCHAR_LC('\n')
6053 : isWORDCHAR_LC_utf8((U8*)locinput);
6055 else { /* Here the string isn't utf8 */
6056 b1 = (locinput == reginfo->strbeg)
6057 ? isWORDCHAR_LC('\n')
6058 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6059 b2 = (NEXTCHR_IS_EOS)
6060 ? isWORDCHAR_LC('\n')
6061 : isWORDCHAR_LC(nextchr);
6063 if (to_complement ^ (b1 == b2)) {
6069 case NBOUND: /* /\B/ */
6073 case BOUND: /* /\b/ */
6077 goto bound_ascii_match_only;
6079 case NBOUNDA: /* /\B/a */
6083 case BOUNDA: /* /\b/a */
6087 bound_ascii_match_only:
6088 /* Here the string isn't utf8, or is utf8 and only ascii characters
6089 * are to match \w. In the latter case looking at the byte just
6090 * prior to the current one may be just the final byte of a
6091 * multi-byte character. This is ok. There are two cases:
6092 * 1) it is a single byte character, and then the test is doing
6093 * just what it's supposed to.
6094 * 2) it is a multi-byte character, in which case the final byte is
6095 * never mistakable for ASCII, and so the test will say it is
6096 * not a word character, which is the correct answer. */
6097 b1 = (locinput == reginfo->strbeg)
6098 ? isWORDCHAR_A('\n')
6099 : isWORDCHAR_A(UCHARAT(locinput - 1));
6100 b2 = (NEXTCHR_IS_EOS)
6101 ? isWORDCHAR_A('\n')
6102 : isWORDCHAR_A(nextchr);
6103 if (to_complement ^ (b1 == b2)) {
6109 case NBOUNDU: /* /\B/u */
6113 case BOUNDU: /* /\b/u */
6116 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6119 else if (utf8_target) {
6121 switch((bound_type) FLAGS(scan)) {
6122 case TRADITIONAL_BOUND:
6125 b1 = (locinput == reginfo->strbeg)
6126 ? 0 /* isWORDCHAR_L1('\n') */
6127 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
6128 (U8*)(reginfo->strbeg)));
6129 b2 = (NEXTCHR_IS_EOS)
6130 ? 0 /* isWORDCHAR_L1('\n') */
6131 : isWORDCHAR_utf8((U8*)locinput);
6132 match = cBOOL(b1 != b2);
6136 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6137 match = TRUE; /* GCB always matches at begin and
6141 /* Find the gcb values of previous and current
6142 * chars, then see if is a break point */
6143 match = isGCB(getGCB_VAL_UTF8(
6144 reghop3((U8*)locinput,
6146 (U8*)(reginfo->strbeg)),
6147 (U8*) reginfo->strend),
6148 getGCB_VAL_UTF8((U8*) locinput,
6149 (U8*) reginfo->strend),
6150 (U8*) reginfo->strbeg,
6157 if (locinput == reginfo->strbeg) {
6160 else if (NEXTCHR_IS_EOS) {
6164 match = isLB(getLB_VAL_UTF8(
6165 reghop3((U8*)locinput,
6167 (U8*)(reginfo->strbeg)),
6168 (U8*) reginfo->strend),
6169 getLB_VAL_UTF8((U8*) locinput,
6170 (U8*) reginfo->strend),
6171 (U8*) reginfo->strbeg,
6173 (U8*) reginfo->strend,
6178 case SB_BOUND: /* Always matches at begin and end */
6179 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6183 match = isSB(getSB_VAL_UTF8(
6184 reghop3((U8*)locinput,
6186 (U8*)(reginfo->strbeg)),
6187 (U8*) reginfo->strend),
6188 getSB_VAL_UTF8((U8*) locinput,
6189 (U8*) reginfo->strend),
6190 (U8*) reginfo->strbeg,
6192 (U8*) reginfo->strend,
6198 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6202 match = isWB(WB_UNKNOWN,
6204 reghop3((U8*)locinput,
6206 (U8*)(reginfo->strbeg)),
6207 (U8*) reginfo->strend),
6208 getWB_VAL_UTF8((U8*) locinput,
6209 (U8*) reginfo->strend),
6210 (U8*) reginfo->strbeg,
6212 (U8*) reginfo->strend,
6218 else { /* Not utf8 target */
6219 switch((bound_type) FLAGS(scan)) {
6220 case TRADITIONAL_BOUND:
6223 b1 = (locinput == reginfo->strbeg)
6224 ? 0 /* isWORDCHAR_L1('\n') */
6225 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6226 b2 = (NEXTCHR_IS_EOS)
6227 ? 0 /* isWORDCHAR_L1('\n') */
6228 : isWORDCHAR_L1(nextchr);
6229 match = cBOOL(b1 != b2);
6234 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6235 match = TRUE; /* GCB always matches at begin and
6238 else { /* Only CR-LF combo isn't a GCB in 0-255
6240 match = UCHARAT(locinput - 1) != '\r'
6241 || UCHARAT(locinput) != '\n';
6246 if (locinput == reginfo->strbeg) {
6249 else if (NEXTCHR_IS_EOS) {
6253 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6254 getLB_VAL_CP(UCHARAT(locinput)),
6255 (U8*) reginfo->strbeg,
6257 (U8*) reginfo->strend,
6262 case SB_BOUND: /* Always matches at begin and end */
6263 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6267 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6268 getSB_VAL_CP(UCHARAT(locinput)),
6269 (U8*) reginfo->strbeg,
6271 (U8*) reginfo->strend,
6277 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6281 match = isWB(WB_UNKNOWN,
6282 getWB_VAL_CP(UCHARAT(locinput -1)),
6283 getWB_VAL_CP(UCHARAT(locinput)),
6284 (U8*) reginfo->strbeg,
6286 (U8*) reginfo->strend,
6293 if (to_complement ^ ! match) {
6298 case ANYOFL: /* /[abc]/l */
6299 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6301 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6303 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6306 case ANYOFD: /* /[abc]/d */
6307 case ANYOF: /* /[abc]/ */
6310 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6311 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6314 locinput += UTF8SKIP(locinput);
6317 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6323 /* The argument (FLAGS) to all the POSIX node types is the class number
6326 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6330 case POSIXL: /* \w or [:punct:] etc. under /l */
6331 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6335 /* Use isFOO_lc() for characters within Latin1. (Note that
6336 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6337 * wouldn't be invariant) */
6338 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6339 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6343 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6344 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6345 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6346 *(locinput + 1))))))
6351 else { /* Here, must be an above Latin-1 code point */
6352 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6353 goto utf8_posix_above_latin1;
6356 /* Here, must be utf8 */
6357 locinput += UTF8SKIP(locinput);
6360 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6364 case POSIXD: /* \w or [:punct:] etc. under /d */
6370 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6372 if (NEXTCHR_IS_EOS) {
6376 /* All UTF-8 variants match */
6377 if (! UTF8_IS_INVARIANT(nextchr)) {
6378 goto increment_locinput;
6384 case POSIXA: /* \w or [:punct:] etc. under /a */
6387 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6388 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6389 * character is a single byte */
6391 if (NEXTCHR_IS_EOS) {
6397 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6403 /* Here we are either not in utf8, or we matched a utf8-invariant,
6404 * so the next char is the next byte */
6408 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6412 case POSIXU: /* \w or [:punct:] etc. under /u */
6414 if (NEXTCHR_IS_EOS) {
6418 /* Use _generic_isCC() for characters within Latin1. (Note that
6419 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6420 * wouldn't be invariant) */
6421 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6422 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6429 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6430 if (! (to_complement
6431 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6439 else { /* Handle above Latin-1 code points */
6440 utf8_posix_above_latin1:
6441 classnum = (_char_class_number) FLAGS(scan);
6442 if (classnum < _FIRST_NON_SWASH_CC) {
6444 /* Here, uses a swash to find such code points. Load if if
6445 * not done already */
6446 if (! PL_utf8_swash_ptrs[classnum]) {
6447 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6448 PL_utf8_swash_ptrs[classnum]
6449 = _core_swash_init("utf8",
6452 PL_XPosix_ptrs[classnum], &flags);
6454 if (! (to_complement
6455 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6456 (U8 *) locinput, TRUE))))
6461 else { /* Here, uses macros to find above Latin-1 code points */
6463 case _CC_ENUM_SPACE:
6464 if (! (to_complement
6465 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6470 case _CC_ENUM_BLANK:
6471 if (! (to_complement
6472 ^ cBOOL(is_HORIZWS_high(locinput))))
6477 case _CC_ENUM_XDIGIT:
6478 if (! (to_complement
6479 ^ cBOOL(is_XDIGIT_high(locinput))))
6484 case _CC_ENUM_VERTSPACE:
6485 if (! (to_complement
6486 ^ cBOOL(is_VERTWS_high(locinput))))
6491 default: /* The rest, e.g. [:cntrl:], can't match
6493 if (! to_complement) {
6499 locinput += UTF8SKIP(locinput);
6503 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6504 a Unicode extended Grapheme Cluster */
6507 if (! utf8_target) {
6509 /* Match either CR LF or '.', as all the other possibilities
6511 locinput++; /* Match the . or CR */
6512 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6514 && locinput < reginfo->strend
6515 && UCHARAT(locinput) == '\n')
6522 /* Get the gcb type for the current character */
6523 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6524 (U8*) reginfo->strend);
6526 /* Then scan through the input until we get to the first
6527 * character whose type is supposed to be a gcb with the
6528 * current character. (There is always a break at the
6530 locinput += UTF8SKIP(locinput);
6531 while (locinput < reginfo->strend) {
6532 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6533 (U8*) reginfo->strend);
6534 if (isGCB(prev_gcb, cur_gcb,
6535 (U8*) reginfo->strbeg, (U8*) locinput,
6542 locinput += UTF8SKIP(locinput);
6549 case NREFFL: /* /\g{name}/il */
6550 { /* The capture buffer cases. The ones beginning with N for the
6551 named buffers just convert to the equivalent numbered and
6552 pretend they were called as the corresponding numbered buffer
6554 /* don't initialize these in the declaration, it makes C++
6559 const U8 *fold_array;
6562 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6563 folder = foldEQ_locale;
6564 fold_array = PL_fold_locale;
6566 utf8_fold_flags = FOLDEQ_LOCALE;
6569 case NREFFA: /* /\g{name}/iaa */
6570 folder = foldEQ_latin1;
6571 fold_array = PL_fold_latin1;
6573 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6576 case NREFFU: /* /\g{name}/iu */
6577 folder = foldEQ_latin1;
6578 fold_array = PL_fold_latin1;
6580 utf8_fold_flags = 0;
6583 case NREFF: /* /\g{name}/i */
6585 fold_array = PL_fold;
6587 utf8_fold_flags = 0;
6590 case NREF: /* /\g{name}/ */
6594 utf8_fold_flags = 0;
6597 /* For the named back references, find the corresponding buffer
6599 n = reg_check_named_buff_matched(rex,scan);
6604 goto do_nref_ref_common;
6606 case REFFL: /* /\1/il */
6607 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6608 folder = foldEQ_locale;
6609 fold_array = PL_fold_locale;
6610 utf8_fold_flags = FOLDEQ_LOCALE;
6613 case REFFA: /* /\1/iaa */
6614 folder = foldEQ_latin1;
6615 fold_array = PL_fold_latin1;
6616 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6619 case REFFU: /* /\1/iu */
6620 folder = foldEQ_latin1;
6621 fold_array = PL_fold_latin1;
6622 utf8_fold_flags = 0;
6625 case REFF: /* /\1/i */
6627 fold_array = PL_fold;
6628 utf8_fold_flags = 0;
6631 case REF: /* /\1/ */
6634 utf8_fold_flags = 0;
6638 n = ARG(scan); /* which paren pair */
6641 ln = rex->offs[n].start;
6642 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6643 if (rex->lastparen < n || ln == -1)
6644 sayNO; /* Do not match unless seen CLOSEn. */
6645 if (ln == rex->offs[n].end)
6648 s = reginfo->strbeg + ln;
6649 if (type != REF /* REF can do byte comparison */
6650 && (utf8_target || type == REFFU || type == REFFL))
6652 char * limit = reginfo->strend;
6654 /* This call case insensitively compares the entire buffer
6655 * at s, with the current input starting at locinput, but
6656 * not going off the end given by reginfo->strend, and
6657 * returns in <limit> upon success, how much of the
6658 * current input was matched */
6659 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6660 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6668 /* Not utf8: Inline the first character, for speed. */
6669 if (!NEXTCHR_IS_EOS &&
6670 UCHARAT(s) != nextchr &&
6672 UCHARAT(s) != fold_array[nextchr]))
6674 ln = rex->offs[n].end - ln;
6675 if (locinput + ln > reginfo->strend)
6677 if (ln > 1 && (type == REF
6678 ? memNE(s, locinput, ln)
6679 : ! folder(s, locinput, ln)))
6685 case NOTHING: /* null op; e.g. the 'nothing' following
6686 * the '*' in m{(a+|b)*}' */
6688 case TAIL: /* placeholder while compiling (A|B|C) */
6692 #define ST st->u.eval
6693 #define CUR_EVAL cur_eval->u.eval
6699 regexp_internal *rei;
6700 regnode *startpoint;
6703 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6704 arg= (U32)ARG(scan);
6705 if (cur_eval && cur_eval->locinput == locinput) {
6706 if ( ++nochange_depth > max_nochange_depth )
6708 "Pattern subroutine nesting without pos change"
6709 " exceeded limit in regex");
6716 startpoint = scan + ARG2L(scan);
6717 EVAL_CLOSE_PAREN_SET( st, arg );
6718 /* Detect infinite recursion
6720 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
6721 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
6722 * So we track the position in the string we are at each time
6723 * we recurse and if we try to enter the same routine twice from
6724 * the same position we throw an error.
6726 if ( rex->recurse_locinput[arg] == locinput ) {
6727 /* FIXME: we should show the regop that is failing as part
6728 * of the error message. */
6729 Perl_croak(aTHX_ "Infinite recursion in regex");
6731 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
6732 rex->recurse_locinput[arg]= locinput;
6735 GET_RE_DEBUG_FLAGS_DECL;
6737 Perl_re_exec_indentf( aTHX_
6738 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
6739 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
6745 /* Save all the positions seen so far. */
6746 ST.cp = regcppush(rex, 0, maxopenparen);
6747 REGCP_SET(ST.lastcp);
6749 /* and then jump to the code we share with EVAL */
6750 goto eval_recurse_doit;
6753 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6754 if (cur_eval && cur_eval->locinput==locinput) {
6755 if ( ++nochange_depth > max_nochange_depth )
6756 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6761 /* execute the code in the {...} */
6765 OP * const oop = PL_op;
6766 COP * const ocurcop = PL_curcop;
6770 /* save *all* paren positions */
6771 regcppush(rex, 0, maxopenparen);
6772 REGCP_SET(runops_cp);
6775 caller_cv = find_runcv(NULL);
6779 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6781 (REGEXP*)(rexi->data->data[n])
6783 nop = (OP*)rexi->data->data[n+1];
6785 else if (rexi->data->what[n] == 'l') { /* literal code */
6787 nop = (OP*)rexi->data->data[n];
6788 assert(CvDEPTH(newcv));
6791 /* literal with own CV */
6792 assert(rexi->data->what[n] == 'L');
6793 newcv = rex->qr_anoncv;
6794 nop = (OP*)rexi->data->data[n];
6797 /* normally if we're about to execute code from the same
6798 * CV that we used previously, we just use the existing
6799 * CX stack entry. However, its possible that in the
6800 * meantime we may have backtracked, popped from the save
6801 * stack, and undone the SAVECOMPPAD(s) associated with
6802 * PUSH_MULTICALL; in which case PL_comppad no longer
6803 * points to newcv's pad. */
6804 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6806 U8 flags = (CXp_SUB_RE |
6807 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6808 if (last_pushed_cv) {
6809 /* PUSH/POP_MULTICALL save and restore the
6810 * caller's PL_comppad; if we call multiple subs
6811 * using the same CX block, we have to save and
6812 * unwind the varying PL_comppad's ourselves,
6813 * especially restoring the right PL_comppad on
6814 * backtrack - so save it on the save stack */
6816 CHANGE_MULTICALL_FLAGS(newcv, flags);
6819 PUSH_MULTICALL_FLAGS(newcv, flags);
6821 last_pushed_cv = newcv;
6824 /* these assignments are just to silence compiler
6826 multicall_cop = NULL;
6828 last_pad = PL_comppad;
6830 /* the initial nextstate you would normally execute
6831 * at the start of an eval (which would cause error
6832 * messages to come from the eval), may be optimised
6833 * away from the execution path in the regex code blocks;
6834 * so manually set PL_curcop to it initially */
6836 OP *o = cUNOPx(nop)->op_first;
6837 assert(o->op_type == OP_NULL);
6838 if (o->op_targ == OP_SCOPE) {
6839 o = cUNOPo->op_first;
6842 assert(o->op_targ == OP_LEAVE);
6843 o = cUNOPo->op_first;
6844 assert(o->op_type == OP_ENTER);
6848 if (o->op_type != OP_STUB) {
6849 assert( o->op_type == OP_NEXTSTATE
6850 || o->op_type == OP_DBSTATE
6851 || (o->op_type == OP_NULL
6852 && ( o->op_targ == OP_NEXTSTATE
6853 || o->op_targ == OP_DBSTATE
6857 PL_curcop = (COP*)o;
6862 DEBUG_STATE_r( Perl_re_printf( aTHX_
6863 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6865 rex->offs[0].end = locinput - reginfo->strbeg;
6866 if (reginfo->info_aux_eval->pos_magic)
6867 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6868 reginfo->sv, reginfo->strbeg,
6869 locinput - reginfo->strbeg);
6872 SV *sv_mrk = get_sv("REGMARK", 1);
6873 sv_setsv(sv_mrk, sv_yes_mark);
6876 /* we don't use MULTICALL here as we want to call the
6877 * first op of the block of interest, rather than the
6878 * first op of the sub. Also, we don't want to free
6879 * the savestack frame */
6880 before = (IV)(SP-PL_stack_base);
6882 CALLRUNOPS(aTHX); /* Scalar context. */
6884 if ((IV)(SP-PL_stack_base) == before)
6885 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6891 /* before restoring everything, evaluate the returned
6892 * value, so that 'uninit' warnings don't use the wrong
6893 * PL_op or pad. Also need to process any magic vars
6894 * (e.g. $1) *before* parentheses are restored */
6899 if (logical == 0) /* (?{})/ */
6900 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6901 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6902 sw = cBOOL(SvTRUE(ret));
6905 else { /* /(??{}) */
6906 /* if its overloaded, let the regex compiler handle
6907 * it; otherwise extract regex, or stringify */
6908 if (SvGMAGICAL(ret))
6909 ret = sv_mortalcopy(ret);
6910 if (!SvAMAGIC(ret)) {
6914 if (SvTYPE(sv) == SVt_REGEXP)
6915 re_sv = (REGEXP*) sv;
6916 else if (SvSMAGICAL(ret)) {
6917 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6919 re_sv = (REGEXP *) mg->mg_obj;
6922 /* force any undef warnings here */
6923 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6924 ret = sv_mortalcopy(ret);
6925 (void) SvPV_force_nolen(ret);
6931 /* *** Note that at this point we don't restore
6932 * PL_comppad, (or pop the CxSUB) on the assumption it may
6933 * be used again soon. This is safe as long as nothing
6934 * in the regexp code uses the pad ! */
6936 PL_curcop = ocurcop;
6937 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6938 PL_curpm = PL_reg_curpm;
6944 /* only /(??{})/ from now on */
6947 /* extract RE object from returned value; compiling if
6951 re_sv = reg_temp_copy(NULL, re_sv);
6956 if (SvUTF8(ret) && IN_BYTES) {
6957 /* In use 'bytes': make a copy of the octet
6958 * sequence, but without the flag on */
6960 const char *const p = SvPV(ret, len);
6961 ret = newSVpvn_flags(p, len, SVs_TEMP);
6963 if (rex->intflags & PREGf_USE_RE_EVAL)
6964 pm_flags |= PMf_USE_RE_EVAL;
6966 /* if we got here, it should be an engine which
6967 * supports compiling code blocks and stuff */
6968 assert(rex->engine && rex->engine->op_comp);
6969 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6970 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6971 rex->engine, NULL, NULL,
6972 /* copy /msixn etc to inner pattern */
6977 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6978 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6979 /* This isn't a first class regexp. Instead, it's
6980 caching a regexp onto an existing, Perl visible
6982 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6988 RXp_MATCH_COPIED_off(re);
6989 re->subbeg = rex->subbeg;
6990 re->sublen = rex->sublen;
6991 re->suboffset = rex->suboffset;
6992 re->subcoffset = rex->subcoffset;
6994 re->lastcloseparen = 0;
6997 debug_start_match(re_sv, utf8_target, locinput,
6998 reginfo->strend, "Matching embedded");
7000 startpoint = rei->program + 1;
7001 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7002 * close_paren only for GOSUB */
7003 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7004 /* Save all the seen positions so far. */
7005 ST.cp = regcppush(rex, 0, maxopenparen);
7006 REGCP_SET(ST.lastcp);
7007 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7009 /* run the pattern returned from (??{...}) */
7011 eval_recurse_doit: /* Share code with GOSUB below this line
7012 * At this point we expect the stack context to be
7013 * set up correctly */
7015 /* invalidate the S-L poscache. We're now executing a
7016 * different set of WHILEM ops (and their associated
7017 * indexes) against the same string, so the bits in the
7018 * cache are meaningless. Setting maxiter to zero forces
7019 * the cache to be invalidated and zeroed before reuse.
7020 * XXX This is too dramatic a measure. Ideally we should
7021 * save the old cache and restore when running the outer
7023 reginfo->poscache_maxiter = 0;
7025 /* the new regexp might have a different is_utf8_pat than we do */
7026 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7028 ST.prev_rex = rex_sv;
7029 ST.prev_curlyx = cur_curlyx;
7031 SET_reg_curpm(rex_sv);
7036 ST.prev_eval = cur_eval;
7038 /* now continue from first node in postoned RE */
7039 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
7040 NOT_REACHED; /* NOTREACHED */
7043 case EVAL_AB: /* cleanup after a successful (??{A})B */
7044 /* note: this is called twice; first after popping B, then A */
7046 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7047 depth, cur_eval, ST.prev_eval);
7050 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7051 if ( cur_eval && CUR_EVAL.close_paren ) {\
7053 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7055 CUR_EVAL.close_paren - 1,\
7059 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7062 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7064 rex_sv = ST.prev_rex;
7065 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7066 SET_reg_curpm(rex_sv);
7067 rex = ReANY(rex_sv);
7068 rexi = RXi_GET(rex);
7070 /* preserve $^R across LEAVE's. See Bug 121070. */
7071 SV *save_sv= GvSV(PL_replgv);
7072 SvREFCNT_inc(save_sv);
7073 regcpblow(ST.cp); /* LEAVE in disguise */
7074 sv_setsv(GvSV(PL_replgv), save_sv);
7075 SvREFCNT_dec(save_sv);
7077 cur_eval = ST.prev_eval;
7078 cur_curlyx = ST.prev_curlyx;
7080 /* Invalidate cache. See "invalidate" comment above. */
7081 reginfo->poscache_maxiter = 0;
7082 if ( nochange_depth )
7085 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7089 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7090 /* note: this is called twice; first after popping B, then A */
7092 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7093 depth, cur_eval, ST.prev_eval);
7096 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7098 rex_sv = ST.prev_rex;
7099 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7100 SET_reg_curpm(rex_sv);
7101 rex = ReANY(rex_sv);
7102 rexi = RXi_GET(rex);
7104 REGCP_UNWIND(ST.lastcp);
7105 regcppop(rex, &maxopenparen);
7106 cur_eval = ST.prev_eval;
7107 cur_curlyx = ST.prev_curlyx;
7109 /* Invalidate cache. See "invalidate" comment above. */
7110 reginfo->poscache_maxiter = 0;
7111 if ( nochange_depth )
7114 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7119 n = ARG(scan); /* which paren pair */
7120 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7121 if (n > maxopenparen)
7123 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_
7124 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
7128 (IV)rex->offs[n].start_tmp,
7134 /* XXX really need to log other places start/end are set too */
7135 #define CLOSE_CAPTURE \
7136 rex->offs[n].start = rex->offs[n].start_tmp; \
7137 rex->offs[n].end = locinput - reginfo->strbeg; \
7138 DEBUG_BUFFERS_r(Perl_re_printf( aTHX_ \
7139 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
7141 PTR2UV(rex->offs), \
7143 (IV)rex->offs[n].start, \
7144 (IV)rex->offs[n].end \
7148 n = ARG(scan); /* which paren pair */
7150 if (n > rex->lastparen)
7152 rex->lastcloseparen = n;
7153 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7158 case ACCEPT: /* (*ACCEPT) */
7160 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7164 cursor && OP(cursor)!=END;
7165 cursor=regnext(cursor))
7167 if ( OP(cursor)==CLOSE ){
7169 if ( n <= lastopen ) {
7171 if (n > rex->lastparen)
7173 rex->lastcloseparen = n;
7174 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7183 case GROUPP: /* (?(1)) */
7184 n = ARG(scan); /* which paren pair */
7185 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7188 case NGROUPP: /* (?(<name>)) */
7189 /* reg_check_named_buff_matched returns 0 for no match */
7190 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7193 case INSUBP: /* (?(R)) */
7195 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7196 * of SCAN is already set up as matches a eval.close_paren */
7197 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7200 case DEFINEP: /* (?(DEFINE)) */
7204 case IFTHEN: /* (?(cond)A|B) */
7205 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7207 next = NEXTOPER(NEXTOPER(scan));
7209 next = scan + ARG(scan);
7210 if (OP(next) == IFTHEN) /* Fake one. */
7211 next = NEXTOPER(NEXTOPER(next));
7215 case LOGICAL: /* modifier for EVAL and IFMATCH */
7216 logical = scan->flags;
7219 /*******************************************************************
7221 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7222 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7223 STAR/PLUS/CURLY/CURLYN are used instead.)
7225 A*B is compiled as <CURLYX><A><WHILEM><B>
7227 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7228 state, which contains the current count, initialised to -1. It also sets
7229 cur_curlyx to point to this state, with any previous value saved in the
7232 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7233 since the pattern may possibly match zero times (i.e. it's a while {} loop
7234 rather than a do {} while loop).
7236 Each entry to WHILEM represents a successful match of A. The count in the
7237 CURLYX block is incremented, another WHILEM state is pushed, and execution
7238 passes to A or B depending on greediness and the current count.
7240 For example, if matching against the string a1a2a3b (where the aN are
7241 substrings that match /A/), then the match progresses as follows: (the
7242 pushed states are interspersed with the bits of strings matched so far):
7245 <CURLYX cnt=0><WHILEM>
7246 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7247 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7248 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7249 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7251 (Contrast this with something like CURLYM, which maintains only a single
7255 a1 <CURLYM cnt=1> a2
7256 a1 a2 <CURLYM cnt=2> a3
7257 a1 a2 a3 <CURLYM cnt=3> b
7260 Each WHILEM state block marks a point to backtrack to upon partial failure
7261 of A or B, and also contains some minor state data related to that
7262 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7263 overall state, such as the count, and pointers to the A and B ops.
7265 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7266 must always point to the *current* CURLYX block, the rules are:
7268 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7269 and set cur_curlyx to point the new block.
7271 When popping the CURLYX block after a successful or unsuccessful match,
7272 restore the previous cur_curlyx.
7274 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7275 to the outer one saved in the CURLYX block.
7277 When popping the WHILEM block after a successful or unsuccessful B match,
7278 restore the previous cur_curlyx.
7280 Here's an example for the pattern (AI* BI)*BO
7281 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7284 curlyx backtrack stack
7285 ------ ---------------
7287 CO <CO prev=NULL> <WO>
7288 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7289 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7290 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7292 At this point the pattern succeeds, and we work back down the stack to
7293 clean up, restoring as we go:
7295 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7296 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7297 CO <CO prev=NULL> <WO>
7300 *******************************************************************/
7302 #define ST st->u.curlyx
7304 case CURLYX: /* start of /A*B/ (for complex A) */
7306 /* No need to save/restore up to this paren */
7307 I32 parenfloor = scan->flags;
7309 assert(next); /* keep Coverity happy */
7310 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7313 /* XXXX Probably it is better to teach regpush to support
7314 parenfloor > maxopenparen ... */
7315 if (parenfloor > (I32)rex->lastparen)
7316 parenfloor = rex->lastparen; /* Pessimization... */
7318 ST.prev_curlyx= cur_curlyx;
7320 ST.cp = PL_savestack_ix;
7322 /* these fields contain the state of the current curly.
7323 * they are accessed by subsequent WHILEMs */
7324 ST.parenfloor = parenfloor;
7329 ST.count = -1; /* this will be updated by WHILEM */
7330 ST.lastloc = NULL; /* this will be updated by WHILEM */
7332 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7333 NOT_REACHED; /* NOTREACHED */
7336 case CURLYX_end: /* just finished matching all of A*B */
7337 cur_curlyx = ST.prev_curlyx;
7339 NOT_REACHED; /* NOTREACHED */
7341 case CURLYX_end_fail: /* just failed to match all of A*B */
7343 cur_curlyx = ST.prev_curlyx;
7345 NOT_REACHED; /* NOTREACHED */
7349 #define ST st->u.whilem
7351 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7353 /* see the discussion above about CURLYX/WHILEM */
7358 assert(cur_curlyx); /* keep Coverity happy */
7360 min = ARG1(cur_curlyx->u.curlyx.me);
7361 max = ARG2(cur_curlyx->u.curlyx.me);
7362 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7363 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7364 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7365 ST.cache_offset = 0;
7369 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: matched %ld out of %d..%d\n",
7370 depth, (long)n, min, max)
7373 /* First just match a string of min A's. */
7376 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7378 cur_curlyx->u.curlyx.lastloc = locinput;
7379 REGCP_SET(ST.lastcp);
7381 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7382 NOT_REACHED; /* NOTREACHED */
7385 /* If degenerate A matches "", assume A done. */
7387 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7388 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: empty match detected, trying continuation...\n",
7391 goto do_whilem_B_max;
7394 /* super-linear cache processing.
7396 * The idea here is that for certain types of CURLYX/WHILEM -
7397 * principally those whose upper bound is infinity (and
7398 * excluding regexes that have things like \1 and other very
7399 * non-regular expresssiony things), then if a pattern like
7400 * /....A*.../ fails and we backtrack to the WHILEM, then we
7401 * make a note that this particular WHILEM op was at string
7402 * position 47 (say) when the rest of pattern failed. Then, if
7403 * we ever find ourselves back at that WHILEM, and at string
7404 * position 47 again, we can just fail immediately rather than
7405 * running the rest of the pattern again.
7407 * This is very handy when patterns start to go
7408 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7409 * with a combinatorial explosion of backtracking.
7411 * The cache is implemented as a bit array, with one bit per
7412 * string byte position per WHILEM op (up to 16) - so its
7413 * between 0.25 and 2x the string size.
7415 * To avoid allocating a poscache buffer every time, we do an
7416 * initially countdown; only after we have executed a WHILEM
7417 * op (string-length x #WHILEMs) times do we allocate the
7420 * The top 4 bits of scan->flags byte say how many different
7421 * relevant CURLLYX/WHILEM op pairs there are, while the
7422 * bottom 4-bits is the identifying index number of this
7428 if (!reginfo->poscache_maxiter) {
7429 /* start the countdown: Postpone detection until we
7430 * know the match is not *that* much linear. */
7431 reginfo->poscache_maxiter
7432 = (reginfo->strend - reginfo->strbeg + 1)
7434 /* possible overflow for long strings and many CURLYX's */
7435 if (reginfo->poscache_maxiter < 0)
7436 reginfo->poscache_maxiter = I32_MAX;
7437 reginfo->poscache_iter = reginfo->poscache_maxiter;
7440 if (reginfo->poscache_iter-- == 0) {
7441 /* initialise cache */
7442 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7443 regmatch_info_aux *const aux = reginfo->info_aux;
7444 if (aux->poscache) {
7445 if ((SSize_t)reginfo->poscache_size < size) {
7446 Renew(aux->poscache, size, char);
7447 reginfo->poscache_size = size;
7449 Zero(aux->poscache, size, char);
7452 reginfo->poscache_size = size;
7453 Newxz(aux->poscache, size, char);
7455 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7456 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7457 PL_colors[4], PL_colors[5])
7461 if (reginfo->poscache_iter < 0) {
7462 /* have we already failed at this position? */
7463 SSize_t offset, mask;
7465 reginfo->poscache_iter = -1; /* stop eventual underflow */
7466 offset = (scan->flags & 0xf) - 1
7467 + (locinput - reginfo->strbeg)
7469 mask = 1 << (offset % 8);
7471 if (reginfo->info_aux->poscache[offset] & mask) {
7472 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: (cache) already tried at this position...\n",
7475 sayNO; /* cache records failure */
7477 ST.cache_offset = offset;
7478 ST.cache_mask = mask;
7482 /* Prefer B over A for minimal matching. */
7484 if (cur_curlyx->u.curlyx.minmod) {
7485 ST.save_curlyx = cur_curlyx;
7486 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7487 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
7489 REGCP_SET(ST.lastcp);
7490 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7492 NOT_REACHED; /* NOTREACHED */
7495 /* Prefer A over B for maximal matching. */
7497 if (n < max) { /* More greed allowed? */
7498 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7500 cur_curlyx->u.curlyx.lastloc = locinput;
7501 REGCP_SET(ST.lastcp);
7502 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7503 NOT_REACHED; /* NOTREACHED */
7505 goto do_whilem_B_max;
7507 NOT_REACHED; /* NOTREACHED */
7509 case WHILEM_B_min: /* just matched B in a minimal match */
7510 case WHILEM_B_max: /* just matched B in a maximal match */
7511 cur_curlyx = ST.save_curlyx;
7513 NOT_REACHED; /* NOTREACHED */
7515 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7516 cur_curlyx = ST.save_curlyx;
7517 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7518 cur_curlyx->u.curlyx.count--;
7520 NOT_REACHED; /* NOTREACHED */
7522 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7524 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7525 REGCP_UNWIND(ST.lastcp);
7526 regcppop(rex, &maxopenparen);
7527 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7528 cur_curlyx->u.curlyx.count--;
7530 NOT_REACHED; /* NOTREACHED */
7532 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7533 REGCP_UNWIND(ST.lastcp);
7534 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7535 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "whilem: failed, trying continuation...\n",
7539 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7540 && ckWARN(WARN_REGEXP)
7541 && !reginfo->warned)
7543 reginfo->warned = TRUE;
7544 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7545 "Complex regular subexpression recursion limit (%d) "
7551 ST.save_curlyx = cur_curlyx;
7552 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7553 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7555 NOT_REACHED; /* NOTREACHED */
7557 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7558 cur_curlyx = ST.save_curlyx;
7559 REGCP_UNWIND(ST.lastcp);
7560 regcppop(rex, &maxopenparen);
7562 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7563 /* Maximum greed exceeded */
7564 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7565 && ckWARN(WARN_REGEXP)
7566 && !reginfo->warned)
7568 reginfo->warned = TRUE;
7569 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7570 "Complex regular subexpression recursion "
7571 "limit (%d) exceeded",
7574 cur_curlyx->u.curlyx.count--;
7578 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "trying longer...\n", depth)
7580 /* Try grabbing another A and see if it helps. */
7581 cur_curlyx->u.curlyx.lastloc = locinput;
7582 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7584 REGCP_SET(ST.lastcp);
7585 PUSH_STATE_GOTO(WHILEM_A_min,
7586 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7588 NOT_REACHED; /* NOTREACHED */
7591 #define ST st->u.branch
7593 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7594 next = scan + ARG(scan);
7597 scan = NEXTOPER(scan);
7600 case BRANCH: /* /(...|A|...)/ */
7601 scan = NEXTOPER(scan); /* scan now points to inner node */
7602 ST.lastparen = rex->lastparen;
7603 ST.lastcloseparen = rex->lastcloseparen;
7604 ST.next_branch = next;
7607 /* Now go into the branch */
7609 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7611 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7613 NOT_REACHED; /* NOTREACHED */
7615 case CUTGROUP: /* /(*THEN)/ */
7616 sv_yes_mark = st->u.mark.mark_name = scan->flags
7617 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7619 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7620 NOT_REACHED; /* NOTREACHED */
7622 case CUTGROUP_next_fail:
7625 if (st->u.mark.mark_name)
7626 sv_commit = st->u.mark.mark_name;
7628 NOT_REACHED; /* NOTREACHED */
7632 NOT_REACHED; /* NOTREACHED */
7634 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7639 REGCP_UNWIND(ST.cp);
7640 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7641 scan = ST.next_branch;
7642 /* no more branches? */
7643 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7645 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
7652 continue; /* execute next BRANCH[J] op */
7655 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7660 #define ST st->u.curlym
7662 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7664 /* This is an optimisation of CURLYX that enables us to push
7665 * only a single backtracking state, no matter how many matches
7666 * there are in {m,n}. It relies on the pattern being constant
7667 * length, with no parens to influence future backrefs
7671 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7673 ST.lastparen = rex->lastparen;
7674 ST.lastcloseparen = rex->lastcloseparen;
7676 /* if paren positive, emulate an OPEN/CLOSE around A */
7678 U32 paren = ST.me->flags;
7679 if (paren > maxopenparen)
7680 maxopenparen = paren;
7681 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7689 ST.c1 = CHRTEST_UNINIT;
7692 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7695 curlym_do_A: /* execute the A in /A{m,n}B/ */
7696 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7697 NOT_REACHED; /* NOTREACHED */
7699 case CURLYM_A: /* we've just matched an A */
7701 /* after first match, determine A's length: u.curlym.alen */
7702 if (ST.count == 1) {
7703 if (reginfo->is_utf8_target) {
7704 char *s = st->locinput;
7705 while (s < locinput) {
7711 ST.alen = locinput - st->locinput;
7714 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7717 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7718 depth, (IV) ST.count, (IV)ST.alen)
7721 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7725 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7726 if ( max == REG_INFTY || ST.count < max )
7727 goto curlym_do_A; /* try to match another A */
7729 goto curlym_do_B; /* try to match B */
7731 case CURLYM_A_fail: /* just failed to match an A */
7732 REGCP_UNWIND(ST.cp);
7735 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7736 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7739 curlym_do_B: /* execute the B in /A{m,n}B/ */
7740 if (ST.c1 == CHRTEST_UNINIT) {
7741 /* calculate c1 and c2 for possible match of 1st char
7742 * following curly */
7743 ST.c1 = ST.c2 = CHRTEST_VOID;
7745 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7746 regnode *text_node = ST.B;
7747 if (! HAS_TEXT(text_node))
7748 FIND_NEXT_IMPT(text_node);
7751 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7753 But the former is redundant in light of the latter.
7755 if this changes back then the macro for
7756 IS_TEXT and friends need to change.
7758 if (PL_regkind[OP(text_node)] == EXACT) {
7759 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7760 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7770 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%"IVdf"...\n",
7771 depth, (IV)ST.count)
7773 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7774 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7775 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7776 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7778 /* simulate B failing */
7780 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7782 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7783 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7784 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7786 state_num = CURLYM_B_fail;
7787 goto reenter_switch;
7790 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7791 /* simulate B failing */
7793 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7795 (int) nextchr, ST.c1, ST.c2)
7797 state_num = CURLYM_B_fail;
7798 goto reenter_switch;
7803 /* emulate CLOSE: mark current A as captured */
7804 I32 paren = ST.me->flags;
7806 rex->offs[paren].start
7807 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7808 rex->offs[paren].end = locinput - reginfo->strbeg;
7809 if ((U32)paren > rex->lastparen)
7810 rex->lastparen = paren;
7811 rex->lastcloseparen = paren;
7814 rex->offs[paren].end = -1;
7816 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7825 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7826 NOT_REACHED; /* NOTREACHED */
7828 case CURLYM_B_fail: /* just failed to match a B */
7829 REGCP_UNWIND(ST.cp);
7830 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7832 I32 max = ARG2(ST.me);
7833 if (max != REG_INFTY && ST.count == max)
7835 goto curlym_do_A; /* try to match a further A */
7837 /* backtrack one A */
7838 if (ST.count == ARG1(ST.me) /* min */)
7841 SET_locinput(HOPc(locinput, -ST.alen));
7842 goto curlym_do_B; /* try to match B */
7845 #define ST st->u.curly
7847 #define CURLY_SETPAREN(paren, success) \
7850 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7851 rex->offs[paren].end = locinput - reginfo->strbeg; \
7852 if (paren > rex->lastparen) \
7853 rex->lastparen = paren; \
7854 rex->lastcloseparen = paren; \
7857 rex->offs[paren].end = -1; \
7858 rex->lastparen = ST.lastparen; \
7859 rex->lastcloseparen = ST.lastcloseparen; \
7863 case STAR: /* /A*B/ where A is width 1 char */
7867 scan = NEXTOPER(scan);
7870 case PLUS: /* /A+B/ where A is width 1 char */
7874 scan = NEXTOPER(scan);
7877 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7878 ST.paren = scan->flags; /* Which paren to set */
7879 ST.lastparen = rex->lastparen;
7880 ST.lastcloseparen = rex->lastcloseparen;
7881 if (ST.paren > maxopenparen)
7882 maxopenparen = ST.paren;
7883 ST.min = ARG1(scan); /* min to match */
7884 ST.max = ARG2(scan); /* max to match */
7885 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
7890 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7893 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7895 ST.min = ARG1(scan); /* min to match */
7896 ST.max = ARG2(scan); /* max to match */
7897 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7900 * Lookahead to avoid useless match attempts
7901 * when we know what character comes next.
7903 * Used to only do .*x and .*?x, but now it allows
7904 * for )'s, ('s and (?{ ... })'s to be in the way
7905 * of the quantifier and the EXACT-like node. -- japhy
7908 assert(ST.min <= ST.max);
7909 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7910 ST.c1 = ST.c2 = CHRTEST_VOID;
7913 regnode *text_node = next;
7915 if (! HAS_TEXT(text_node))
7916 FIND_NEXT_IMPT(text_node);
7918 if (! HAS_TEXT(text_node))
7919 ST.c1 = ST.c2 = CHRTEST_VOID;
7921 if ( PL_regkind[OP(text_node)] != EXACT ) {
7922 ST.c1 = ST.c2 = CHRTEST_VOID;
7926 /* Currently we only get here when
7928 PL_rekind[OP(text_node)] == EXACT
7930 if this changes back then the macro for IS_TEXT and
7931 friends need to change. */
7932 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7933 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7945 char *li = locinput;
7948 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7954 if (ST.c1 == CHRTEST_VOID)
7955 goto curly_try_B_min;
7957 ST.oldloc = locinput;
7959 /* set ST.maxpos to the furthest point along the
7960 * string that could possibly match */
7961 if (ST.max == REG_INFTY) {
7962 ST.maxpos = reginfo->strend - 1;
7964 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7967 else if (utf8_target) {
7968 int m = ST.max - ST.min;
7969 for (ST.maxpos = locinput;
7970 m >0 && ST.maxpos < reginfo->strend; m--)
7971 ST.maxpos += UTF8SKIP(ST.maxpos);
7974 ST.maxpos = locinput + ST.max - ST.min;
7975 if (ST.maxpos >= reginfo->strend)
7976 ST.maxpos = reginfo->strend - 1;
7978 goto curly_try_B_min_known;
7982 /* avoid taking address of locinput, so it can remain
7984 char *li = locinput;
7985 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7986 if (ST.count < ST.min)
7989 if ((ST.count > ST.min)
7990 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7992 /* A{m,n} must come at the end of the string, there's
7993 * no point in backing off ... */
7995 /* ...except that $ and \Z can match before *and* after
7996 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7997 We may back off by one in this case. */
7998 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8002 goto curly_try_B_max;
8004 NOT_REACHED; /* NOTREACHED */
8006 case CURLY_B_min_known_fail:
8007 /* failed to find B in a non-greedy match where c1,c2 valid */
8009 REGCP_UNWIND(ST.cp);
8011 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8013 /* Couldn't or didn't -- move forward. */
8014 ST.oldloc = locinput;
8016 locinput += UTF8SKIP(locinput);
8020 curly_try_B_min_known:
8021 /* find the next place where 'B' could work, then call B */
8025 n = (ST.oldloc == locinput) ? 0 : 1;
8026 if (ST.c1 == ST.c2) {
8027 /* set n to utf8_distance(oldloc, locinput) */
8028 while (locinput <= ST.maxpos
8029 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8031 locinput += UTF8SKIP(locinput);
8036 /* set n to utf8_distance(oldloc, locinput) */
8037 while (locinput <= ST.maxpos
8038 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8039 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8041 locinput += UTF8SKIP(locinput);
8046 else { /* Not utf8_target */
8047 if (ST.c1 == ST.c2) {
8048 while (locinput <= ST.maxpos &&
8049 UCHARAT(locinput) != ST.c1)
8053 while (locinput <= ST.maxpos
8054 && UCHARAT(locinput) != ST.c1
8055 && UCHARAT(locinput) != ST.c2)
8058 n = locinput - ST.oldloc;
8060 if (locinput > ST.maxpos)
8063 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8064 * at b; check that everything between oldloc and
8065 * locinput matches */
8066 char *li = ST.oldloc;
8068 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
8070 assert(n == REG_INFTY || locinput == li);
8072 CURLY_SETPAREN(ST.paren, ST.count);
8073 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8075 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8077 NOT_REACHED; /* NOTREACHED */
8079 case CURLY_B_min_fail:
8080 /* failed to find B in a non-greedy match where c1,c2 invalid */
8082 REGCP_UNWIND(ST.cp);
8084 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8086 /* failed -- move forward one */
8088 char *li = locinput;
8089 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
8096 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8097 ST.count > 0)) /* count overflow ? */
8100 CURLY_SETPAREN(ST.paren, ST.count);
8101 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8103 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8107 NOT_REACHED; /* NOTREACHED */
8110 /* a successful greedy match: now try to match B */
8111 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8114 bool could_match = locinput < reginfo->strend;
8116 /* If it could work, try it. */
8117 if (ST.c1 != CHRTEST_VOID && could_match) {
8118 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8120 could_match = memEQ(locinput,
8125 UTF8SKIP(locinput));
8128 could_match = UCHARAT(locinput) == ST.c1
8129 || UCHARAT(locinput) == ST.c2;
8132 if (ST.c1 == CHRTEST_VOID || could_match) {
8133 CURLY_SETPAREN(ST.paren, ST.count);
8134 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8135 NOT_REACHED; /* NOTREACHED */
8140 case CURLY_B_max_fail:
8141 /* failed to find B in a greedy match */
8143 REGCP_UNWIND(ST.cp);
8145 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8148 if (--ST.count < ST.min)
8150 locinput = HOPc(locinput, -1);
8151 goto curly_try_B_max;
8155 case END: /* last op of main pattern */
8158 /* we've just finished A in /(??{A})B/; now continue with B */
8159 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8160 st->u.eval.prev_rex = rex_sv; /* inner */
8162 /* Save *all* the positions. */
8163 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8164 rex_sv = CUR_EVAL.prev_rex;
8165 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8166 SET_reg_curpm(rex_sv);
8167 rex = ReANY(rex_sv);
8168 rexi = RXi_GET(rex);
8170 st->u.eval.prev_curlyx = cur_curlyx;
8171 cur_curlyx = CUR_EVAL.prev_curlyx;
8173 REGCP_SET(st->u.eval.lastcp);
8175 /* Restore parens of the outer rex without popping the
8177 S_regcp_restore(aTHX_ rex, CUR_EVAL.lastcp,
8180 st->u.eval.prev_eval = cur_eval;
8181 cur_eval = CUR_EVAL.prev_eval;
8183 Perl_re_exec_indentf( aTHX_ "EVAL trying tail ... (cur_eval=%p)\n",
8185 if ( nochange_depth )
8188 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8190 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
8191 locinput); /* match B */
8194 if (locinput < reginfo->till) {
8195 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8196 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8198 (long)(locinput - startpos),
8199 (long)(reginfo->till - startpos),
8202 sayNO_SILENT; /* Cannot match: too short. */
8204 sayYES; /* Success! */
8206 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8208 Perl_re_exec_indentf( aTHX_ "%ssubpattern success...%s\n",
8209 depth, PL_colors[4], PL_colors[5]));
8210 sayYES; /* Success! */
8213 #define ST st->u.ifmatch
8218 case SUSPEND: /* (?>A) */
8220 newstart = locinput;
8223 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8225 goto ifmatch_trivial_fail_test;
8227 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8229 ifmatch_trivial_fail_test:
8231 char * const s = HOPBACKc(locinput, scan->flags);
8236 sw = 1 - cBOOL(ST.wanted);
8240 next = scan + ARG(scan);
8248 newstart = locinput;
8252 ST.logical = logical;
8253 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8255 /* execute body of (?...A) */
8256 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8257 NOT_REACHED; /* NOTREACHED */
8260 case IFMATCH_A_fail: /* body of (?...A) failed */
8261 ST.wanted = !ST.wanted;
8264 case IFMATCH_A: /* body of (?...A) succeeded */
8266 sw = cBOOL(ST.wanted);
8268 else if (!ST.wanted)
8271 if (OP(ST.me) != SUSPEND) {
8272 /* restore old position except for (?>...) */
8273 locinput = st->locinput;
8275 scan = ST.me + ARG(ST.me);
8278 continue; /* execute B */
8282 case LONGJMP: /* alternative with many branches compiles to
8283 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8284 next = scan + ARG(scan);
8289 case COMMIT: /* (*COMMIT) */
8290 reginfo->cutpoint = reginfo->strend;
8293 case PRUNE: /* (*PRUNE) */
8295 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8296 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8297 NOT_REACHED; /* NOTREACHED */
8299 case COMMIT_next_fail:
8303 NOT_REACHED; /* NOTREACHED */
8305 case OPFAIL: /* (*FAIL) */
8307 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8309 /* deal with (?(?!)X|Y) properly,
8310 * make sure we trigger the no branch
8311 * of the trailing IFTHEN structure*/
8317 NOT_REACHED; /* NOTREACHED */
8319 #define ST st->u.mark
8320 case MARKPOINT: /* (*MARK:foo) */
8321 ST.prev_mark = mark_state;
8322 ST.mark_name = sv_commit = sv_yes_mark
8323 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8325 ST.mark_loc = locinput;
8326 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8327 NOT_REACHED; /* NOTREACHED */
8329 case MARKPOINT_next:
8330 mark_state = ST.prev_mark;
8332 NOT_REACHED; /* NOTREACHED */
8334 case MARKPOINT_next_fail:
8335 if (popmark && sv_eq(ST.mark_name,popmark))
8337 if (ST.mark_loc > startpoint)
8338 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8339 popmark = NULL; /* we found our mark */
8340 sv_commit = ST.mark_name;
8343 Perl_re_exec_indentf( aTHX_ "%ssetting cutpoint to mark:%"SVf"...%s\n",
8345 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8348 mark_state = ST.prev_mark;
8349 sv_yes_mark = mark_state ?
8350 mark_state->u.mark.mark_name : NULL;
8352 NOT_REACHED; /* NOTREACHED */
8354 case SKIP: /* (*SKIP) */
8356 /* (*SKIP) : if we fail we cut here*/
8357 ST.mark_name = NULL;
8358 ST.mark_loc = locinput;
8359 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8361 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8362 otherwise do nothing. Meaning we need to scan
8364 regmatch_state *cur = mark_state;
8365 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8368 if ( sv_eq( cur->u.mark.mark_name,
8371 ST.mark_name = find;
8372 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8374 cur = cur->u.mark.prev_mark;
8377 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8380 case SKIP_next_fail:
8382 /* (*CUT:NAME) - Set up to search for the name as we
8383 collapse the stack*/
8384 popmark = ST.mark_name;
8386 /* (*CUT) - No name, we cut here.*/
8387 if (ST.mark_loc > startpoint)
8388 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8389 /* but we set sv_commit to latest mark_name if there
8390 is one so they can test to see how things lead to this
8393 sv_commit=mark_state->u.mark.mark_name;
8397 NOT_REACHED; /* NOTREACHED */
8400 case LNBREAK: /* \R */
8401 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8408 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
8409 PTR2UV(scan), OP(scan));
8410 Perl_croak(aTHX_ "regexp memory corruption");
8412 /* this is a point to jump to in order to increment
8413 * locinput by one character */
8415 assert(!NEXTCHR_IS_EOS);
8417 locinput += PL_utf8skip[nextchr];
8418 /* locinput is allowed to go 1 char off the end, but not 2+ */
8419 if (locinput > reginfo->strend)
8428 /* switch break jumps here */
8429 scan = next; /* prepare to execute the next op and ... */
8430 continue; /* ... jump back to the top, reusing st */
8434 /* push a state that backtracks on success */
8435 st->u.yes.prev_yes_state = yes_state;
8439 /* push a new regex state, then continue at scan */
8441 regmatch_state *newst;
8444 regmatch_state *cur = st;
8445 regmatch_state *curyes = yes_state;
8447 regmatch_slab *slab = PL_regmatch_slab;
8448 for (;curd > -1 && (depth-curd < 3);cur--,curd--) {
8449 if (cur < SLAB_FIRST(slab)) {
8451 cur = SLAB_LAST(slab);
8453 Perl_re_exec_indentf( aTHX_ "#%-3d %-10s %s\n",
8455 curd, PL_reg_name[cur->resume_state],
8456 (curyes == cur) ? "yes" : ""
8459 curyes = cur->u.yes.prev_yes_state;
8462 DEBUG_STATE_pp("push")
8465 st->locinput = locinput;
8467 if (newst > SLAB_LAST(PL_regmatch_slab))
8468 newst = S_push_slab(aTHX);
8469 PL_regmatch_state = newst;
8471 locinput = pushinput;
8477 #ifdef SOLARIS_BAD_OPTIMIZER
8478 # undef PL_charclass
8482 * We get here only if there's trouble -- normally "case END" is
8483 * the terminating point.
8485 Perl_croak(aTHX_ "corrupted regexp pointers");
8486 NOT_REACHED; /* NOTREACHED */
8490 /* we have successfully completed a subexpression, but we must now
8491 * pop to the state marked by yes_state and continue from there */
8492 assert(st != yes_state);
8494 while (st != yes_state) {
8496 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8497 PL_regmatch_slab = PL_regmatch_slab->prev;
8498 st = SLAB_LAST(PL_regmatch_slab);
8502 DEBUG_STATE_pp("pop (no final)");
8504 DEBUG_STATE_pp("pop (yes)");
8510 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8511 || yes_state > SLAB_LAST(PL_regmatch_slab))
8513 /* not in this slab, pop slab */
8514 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8515 PL_regmatch_slab = PL_regmatch_slab->prev;
8516 st = SLAB_LAST(PL_regmatch_slab);
8518 depth -= (st - yes_state);
8521 yes_state = st->u.yes.prev_yes_state;
8522 PL_regmatch_state = st;
8525 locinput= st->locinput;
8526 state_num = st->resume_state + no_final;
8527 goto reenter_switch;
8530 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
8531 PL_colors[4], PL_colors[5]));
8533 if (reginfo->info_aux_eval) {
8534 /* each successfully executed (?{...}) block does the equivalent of
8535 * local $^R = do {...}
8536 * When popping the save stack, all these locals would be undone;
8537 * bypass this by setting the outermost saved $^R to the latest
8539 /* I dont know if this is needed or works properly now.
8540 * see code related to PL_replgv elsewhere in this file.
8543 if (oreplsv != GvSV(PL_replgv))
8544 sv_setsv(oreplsv, GvSV(PL_replgv));
8551 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
8553 PL_colors[4], PL_colors[5])
8565 /* there's a previous state to backtrack to */
8567 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8568 PL_regmatch_slab = PL_regmatch_slab->prev;
8569 st = SLAB_LAST(PL_regmatch_slab);
8571 PL_regmatch_state = st;
8572 locinput= st->locinput;
8574 DEBUG_STATE_pp("pop");
8576 if (yes_state == st)
8577 yes_state = st->u.yes.prev_yes_state;
8579 state_num = st->resume_state + 1; /* failure = success + 1 */
8581 goto reenter_switch;
8586 if (rex->intflags & PREGf_VERBARG_SEEN) {
8587 SV *sv_err = get_sv("REGERROR", 1);
8588 SV *sv_mrk = get_sv("REGMARK", 1);
8590 sv_commit = &PL_sv_no;
8592 sv_yes_mark = &PL_sv_yes;
8595 sv_commit = &PL_sv_yes;
8596 sv_yes_mark = &PL_sv_no;
8600 sv_setsv(sv_err, sv_commit);
8601 sv_setsv(sv_mrk, sv_yes_mark);
8605 if (last_pushed_cv) {
8608 PERL_UNUSED_VAR(SP);
8611 assert(!result || locinput - reginfo->strbeg >= 0);
8612 return result ? locinput - reginfo->strbeg : -1;
8616 - regrepeat - repeatedly match something simple, report how many
8618 * What 'simple' means is a node which can be the operand of a quantifier like
8621 * startposp - pointer a pointer to the start position. This is updated
8622 * to point to the byte following the highest successful
8624 * p - the regnode to be repeatedly matched against.
8625 * reginfo - struct holding match state, such as strend
8626 * max - maximum number of things to match.
8627 * depth - (for debugging) backtracking depth.
8630 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8631 regmatch_info *const reginfo, I32 max, int depth)
8633 char *scan; /* Pointer to current position in target string */
8635 char *loceol = reginfo->strend; /* local version */
8636 I32 hardcount = 0; /* How many matches so far */
8637 bool utf8_target = reginfo->is_utf8_target;
8638 unsigned int to_complement = 0; /* Invert the result? */
8640 _char_class_number classnum;
8642 PERL_UNUSED_ARG(depth);
8645 PERL_ARGS_ASSERT_REGREPEAT;
8648 if (max == REG_INFTY)
8650 else if (! utf8_target && loceol - scan > max)
8651 loceol = scan + max;
8653 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8654 * to the maximum of how far we should go in it (leaving it set to the real
8655 * end, if the maximum permissible would take us beyond that). This allows
8656 * us to make the loop exit condition that we haven't gone past <loceol> to
8657 * also mean that we haven't exceeded the max permissible count, saving a
8658 * test each time through the loop. But it assumes that the OP matches a
8659 * single byte, which is true for most of the OPs below when applied to a
8660 * non-UTF-8 target. Those relatively few OPs that don't have this
8661 * characteristic will have to compensate.
8663 * There is no adjustment for UTF-8 targets, as the number of bytes per
8664 * character varies. OPs will have to test both that the count is less
8665 * than the max permissible (using <hardcount> to keep track), and that we
8666 * are still within the bounds of the string (using <loceol>. A few OPs
8667 * match a single byte no matter what the encoding. They can omit the max
8668 * test if, for the UTF-8 case, they do the adjustment that was skipped
8671 * Thus, the code above sets things up for the common case; and exceptional
8672 * cases need extra work; the common case is to make sure <scan> doesn't
8673 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8674 * count doesn't exceed the maximum permissible */
8679 while (scan < loceol && hardcount < max && *scan != '\n') {
8680 scan += UTF8SKIP(scan);
8684 while (scan < loceol && *scan != '\n')
8690 while (scan < loceol && hardcount < max) {
8691 scan += UTF8SKIP(scan);
8699 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8700 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8701 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8705 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8709 /* Can use a simple loop if the pattern char to match on is invariant
8710 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8711 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8712 * true iff it doesn't matter if the argument is in UTF-8 or not */
8713 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8714 if (utf8_target && loceol - scan > max) {
8715 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8716 * since here, to match at all, 1 char == 1 byte */
8717 loceol = scan + max;
8719 while (scan < loceol && UCHARAT(scan) == c) {
8723 else if (reginfo->is_utf8_pat) {
8725 STRLEN scan_char_len;
8727 /* When both target and pattern are UTF-8, we have to do
8729 while (hardcount < max
8731 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8732 && memEQ(scan, STRING(p), scan_char_len))
8734 scan += scan_char_len;
8738 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8740 /* Target isn't utf8; convert the character in the UTF-8
8741 * pattern to non-UTF8, and do a simple loop */
8742 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8743 while (scan < loceol && UCHARAT(scan) == c) {
8746 } /* else pattern char is above Latin1, can't possibly match the
8751 /* Here, the string must be utf8; pattern isn't, and <c> is
8752 * different in utf8 than not, so can't compare them directly.
8753 * Outside the loop, find the two utf8 bytes that represent c, and
8754 * then look for those in sequence in the utf8 string */
8755 U8 high = UTF8_TWO_BYTE_HI(c);
8756 U8 low = UTF8_TWO_BYTE_LO(c);
8758 while (hardcount < max
8759 && scan + 1 < loceol
8760 && UCHARAT(scan) == high
8761 && UCHARAT(scan + 1) == low)
8769 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8770 assert(! reginfo->is_utf8_pat);
8773 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8777 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8778 utf8_flags = FOLDEQ_LOCALE;
8781 case EXACTF: /* This node only generated for non-utf8 patterns */
8782 assert(! reginfo->is_utf8_pat);
8787 if (! utf8_target) {
8790 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8791 | FOLDEQ_S2_FOLDS_SANE;
8796 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8800 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8802 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8804 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8807 if (c1 == CHRTEST_VOID) {
8808 /* Use full Unicode fold matching */
8809 char *tmpeol = reginfo->strend;
8810 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8811 while (hardcount < max
8812 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8813 STRING(p), NULL, pat_len,
8814 reginfo->is_utf8_pat, utf8_flags))
8817 tmpeol = reginfo->strend;
8821 else if (utf8_target) {
8823 while (scan < loceol
8825 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8827 scan += UTF8SKIP(scan);
8832 while (scan < loceol
8834 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8835 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8837 scan += UTF8SKIP(scan);
8842 else if (c1 == c2) {
8843 while (scan < loceol && UCHARAT(scan) == c1) {
8848 while (scan < loceol &&
8849 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8858 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8860 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8861 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8867 while (hardcount < max
8869 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8871 scan += UTF8SKIP(scan);
8875 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan, 0))
8880 /* The argument (FLAGS) to all the POSIX node types is the class number */
8887 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8888 if (! utf8_target) {
8889 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8895 while (hardcount < max && scan < loceol
8896 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8899 scan += UTF8SKIP(scan);
8912 if (utf8_target && loceol - scan > max) {
8914 /* We didn't adjust <loceol> at the beginning of this routine
8915 * because is UTF-8, but it is actually ok to do so, since here, to
8916 * match, 1 char == 1 byte. */
8917 loceol = scan + max;
8919 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8932 if (! utf8_target) {
8933 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8939 /* The complement of something that matches only ASCII matches all
8940 * non-ASCII, plus everything in ASCII that isn't in the class. */
8941 while (hardcount < max && scan < loceol
8942 && (! isASCII_utf8(scan)
8943 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8945 scan += UTF8SKIP(scan);
8956 if (! utf8_target) {
8957 while (scan < loceol && to_complement
8958 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8965 classnum = (_char_class_number) FLAGS(p);
8966 if (classnum < _FIRST_NON_SWASH_CC) {
8968 /* Here, a swash is needed for above-Latin1 code points.
8969 * Process as many Latin1 code points using the built-in rules.
8970 * Go to another loop to finish processing upon encountering
8971 * the first Latin1 code point. We could do that in this loop
8972 * as well, but the other way saves having to test if the swash
8973 * has been loaded every time through the loop: extra space to
8975 while (hardcount < max && scan < loceol) {
8976 if (UTF8_IS_INVARIANT(*scan)) {
8977 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8984 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8985 if (! (to_complement
8986 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
8995 goto found_above_latin1;
9002 /* For these character classes, the knowledge of how to handle
9003 * every code point is compiled in to Perl via a macro. This
9004 * code is written for making the loops as tight as possible.
9005 * It could be refactored to save space instead */
9007 case _CC_ENUM_SPACE:
9008 while (hardcount < max
9010 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
9012 scan += UTF8SKIP(scan);
9016 case _CC_ENUM_BLANK:
9017 while (hardcount < max
9019 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
9021 scan += UTF8SKIP(scan);
9025 case _CC_ENUM_XDIGIT:
9026 while (hardcount < max
9028 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
9030 scan += UTF8SKIP(scan);
9034 case _CC_ENUM_VERTSPACE:
9035 while (hardcount < max
9037 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
9039 scan += UTF8SKIP(scan);
9043 case _CC_ENUM_CNTRL:
9044 while (hardcount < max
9046 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
9048 scan += UTF8SKIP(scan);
9053 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
9059 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
9061 /* Load the swash if not already present */
9062 if (! PL_utf8_swash_ptrs[classnum]) {
9063 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
9064 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
9068 PL_XPosix_ptrs[classnum], &flags);
9071 while (hardcount < max && scan < loceol
9072 && to_complement ^ cBOOL(_generic_utf8(
9075 swash_fetch(PL_utf8_swash_ptrs[classnum],
9079 scan += UTF8SKIP(scan);
9086 while (hardcount < max && scan < loceol &&
9087 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9092 /* LNBREAK can match one or two latin chars, which is ok, but we
9093 * have to use hardcount in this situation, and throw away the
9094 * adjustment to <loceol> done before the switch statement */
9095 loceol = reginfo->strend;
9096 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9105 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9119 /* These are all 0 width, so match right here or not at all. */
9123 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9124 NOT_REACHED; /* NOTREACHED */
9131 c = scan - *startposp;
9135 GET_RE_DEBUG_FLAGS_DECL;
9137 SV * const prop = sv_newmortal();
9138 regprop(prog, prop, p, reginfo, NULL);
9139 Perl_re_exec_indentf( aTHX_ "%s can match %"IVdf" times out of %"IVdf"...\n",
9140 depth, SvPVX_const(prop),(IV)c,(IV)max);
9148 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9150 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9151 create a copy so that changes the caller makes won't change the shared one.
9152 If <altsvp> is non-null, will return NULL in it, for back-compat.
9155 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9157 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9163 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9166 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9169 - reginclass - determine if a character falls into a character class
9171 n is the ANYOF-type regnode
9172 p is the target string
9173 p_end points to one byte beyond the end of the target string
9174 utf8_target tells whether p is in UTF-8.
9176 Returns true if matched; false otherwise.
9178 Note that this can be a synthetic start class, a combination of various
9179 nodes, so things you think might be mutually exclusive, such as locale,
9180 aren't. It can match both locale and non-locale
9185 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9188 const char flags = ANYOF_FLAGS(n);
9192 PERL_ARGS_ASSERT_REGINCLASS;
9194 /* If c is not already the code point, get it. Note that
9195 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9196 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9198 c = utf8n_to_uvchr(p, p_end - p, &c_len,
9199 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
9200 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
9201 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
9202 * UTF8_ALLOW_FFFF */
9203 if (c_len == (STRLEN)-1)
9204 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
9205 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9206 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9210 /* If this character is potentially in the bitmap, check it */
9211 if (c < NUM_ANYOF_CODE_POINTS) {
9212 if (ANYOF_BITMAP_TEST(n, c))
9215 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9222 else if (flags & ANYOF_LOCALE_FLAGS) {
9223 if ((flags & ANYOFL_FOLD)
9225 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9229 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9233 /* The data structure is arranged so bits 0, 2, 4, ... are set
9234 * if the class includes the Posix character class given by
9235 * bit/2; and 1, 3, 5, ... are set if the class includes the
9236 * complemented Posix class given by int(bit/2). So we loop
9237 * through the bits, each time changing whether we complement
9238 * the result or not. Suppose for the sake of illustration
9239 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9240 * is set, it means there is a match for this ANYOF node if the
9241 * character is in the class given by the expression (0 / 2 = 0
9242 * = \w). If it is in that class, isFOO_lc() will return 1,
9243 * and since 'to_complement' is 0, the result will stay TRUE,
9244 * and we exit the loop. Suppose instead that bit 0 is 0, but
9245 * bit 1 is 1. That means there is a match if the character
9246 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9247 * but will on bit 1. On the second iteration 'to_complement'
9248 * will be 1, so the exclusive or will reverse things, so we
9249 * are testing for \W. On the third iteration, 'to_complement'
9250 * will be 0, and we would be testing for \s; the fourth
9251 * iteration would test for \S, etc.
9253 * Note that this code assumes that all the classes are closed
9254 * under folding. For example, if a character matches \w, then
9255 * its fold does too; and vice versa. This should be true for
9256 * any well-behaved locale for all the currently defined Posix
9257 * classes, except for :lower: and :upper:, which are handled
9258 * by the pseudo-class :cased: which matches if either of the
9259 * other two does. To get rid of this assumption, an outer
9260 * loop could be used below to iterate over both the source
9261 * character, and its fold (if different) */
9264 int to_complement = 0;
9266 while (count < ANYOF_MAX) {
9267 if (ANYOF_POSIXL_TEST(n, count)
9268 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9281 /* If the bitmap didn't (or couldn't) match, and something outside the
9282 * bitmap could match, try that. */
9284 if (c >= NUM_ANYOF_CODE_POINTS
9285 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9287 match = TRUE; /* Everything above the bitmap matches */
9289 /* Here doesn't match everything above the bitmap. If there is
9290 * some information available beyond the bitmap, we may find a
9291 * match in it. If so, this is most likely because the code point
9292 * is outside the bitmap range. But rarely, it could be because of
9293 * some other reason. If so, various flags are set to indicate
9294 * this possibility. On ANYOFD nodes, there may be matches that
9295 * happen only when the target string is UTF-8; or for other node
9296 * types, because runtime lookup is needed, regardless of the
9297 * UTF-8ness of the target string. Finally, under /il, there may
9298 * be some matches only possible if the locale is a UTF-8 one. */
9299 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9300 && ( c >= NUM_ANYOF_CODE_POINTS
9301 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9302 && ( UNLIKELY(OP(n) != ANYOFD)
9303 || (utf8_target && ! isASCII_uni(c)
9304 # if NUM_ANYOF_CODE_POINTS > 256
9308 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9309 && IN_UTF8_CTYPE_LOCALE)))
9311 SV* only_utf8_locale = NULL;
9312 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9313 &only_utf8_locale, NULL);
9319 } else { /* Convert to utf8 */
9320 utf8_p = utf8_buffer;
9321 append_utf8_from_native_byte(*p, &utf8_p);
9322 utf8_p = utf8_buffer;
9325 if (swash_fetch(sw, utf8_p, TRUE)) {
9329 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9330 match = _invlist_contains_cp(only_utf8_locale, c);
9334 if (UNICODE_IS_SUPER(c)
9336 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9338 && ckWARN_d(WARN_NON_UNICODE))
9340 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9341 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
9345 #if ANYOF_INVERT != 1
9346 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9348 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9351 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9352 return (flags & ANYOF_INVERT) ^ match;
9356 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9358 /* return the position 'off' UTF-8 characters away from 's', forward if
9359 * 'off' >= 0, backwards if negative. But don't go outside of position
9360 * 'lim', which better be < s if off < 0 */
9362 PERL_ARGS_ASSERT_REGHOP3;
9365 while (off-- && s < lim) {
9366 /* XXX could check well-formedness here */
9371 while (off++ && s > lim) {
9373 if (UTF8_IS_CONTINUED(*s)) {
9374 while (s > lim && UTF8_IS_CONTINUATION(*s))
9376 if (! UTF8_IS_START(*s)) {
9377 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9380 /* XXX could check well-formedness here */
9387 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9389 PERL_ARGS_ASSERT_REGHOP4;
9392 while (off-- && s < rlim) {
9393 /* XXX could check well-formedness here */
9398 while (off++ && s > llim) {
9400 if (UTF8_IS_CONTINUED(*s)) {
9401 while (s > llim && UTF8_IS_CONTINUATION(*s))
9403 if (! UTF8_IS_START(*s)) {
9404 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9407 /* XXX could check well-formedness here */
9413 /* like reghop3, but returns NULL on overrun, rather than returning last
9417 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9419 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9422 while (off-- && s < lim) {
9423 /* XXX could check well-formedness here */
9430 while (off++ && s > lim) {
9432 if (UTF8_IS_CONTINUED(*s)) {
9433 while (s > lim && UTF8_IS_CONTINUATION(*s))
9435 if (! UTF8_IS_START(*s)) {
9436 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9439 /* XXX could check well-formedness here */
9448 /* when executing a regex that may have (?{}), extra stuff needs setting
9449 up that will be visible to the called code, even before the current
9450 match has finished. In particular:
9452 * $_ is localised to the SV currently being matched;
9453 * pos($_) is created if necessary, ready to be updated on each call-out
9455 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9456 isn't set until the current pattern is successfully finished), so that
9457 $1 etc of the match-so-far can be seen;
9458 * save the old values of subbeg etc of the current regex, and set then
9459 to the current string (again, this is normally only done at the end
9464 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9467 regexp *const rex = ReANY(reginfo->prog);
9468 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9470 eval_state->rex = rex;
9473 /* Make $_ available to executed code. */
9474 if (reginfo->sv != DEFSV) {
9476 DEFSV_set(reginfo->sv);
9479 if (!(mg = mg_find_mglob(reginfo->sv))) {
9480 /* prepare for quick setting of pos */
9481 mg = sv_magicext_mglob(reginfo->sv);
9484 eval_state->pos_magic = mg;
9485 eval_state->pos = mg->mg_len;
9486 eval_state->pos_flags = mg->mg_flags;
9489 eval_state->pos_magic = NULL;
9491 if (!PL_reg_curpm) {
9492 /* PL_reg_curpm is a fake PMOP that we can attach the current
9493 * regex to and point PL_curpm at, so that $1 et al are visible
9494 * within a /(?{})/. It's just allocated once per interpreter the
9495 * first time its needed */
9496 Newxz(PL_reg_curpm, 1, PMOP);
9499 SV* const repointer = &PL_sv_undef;
9500 /* this regexp is also owned by the new PL_reg_curpm, which
9501 will try to free it. */
9502 av_push(PL_regex_padav, repointer);
9503 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9504 PL_regex_pad = AvARRAY(PL_regex_padav);
9508 SET_reg_curpm(reginfo->prog);
9509 eval_state->curpm = PL_curpm;
9510 PL_curpm = PL_reg_curpm;
9511 if (RXp_MATCH_COPIED(rex)) {
9512 /* Here is a serious problem: we cannot rewrite subbeg,
9513 since it may be needed if this match fails. Thus
9514 $` inside (?{}) could fail... */
9515 eval_state->subbeg = rex->subbeg;
9516 eval_state->sublen = rex->sublen;
9517 eval_state->suboffset = rex->suboffset;
9518 eval_state->subcoffset = rex->subcoffset;
9520 eval_state->saved_copy = rex->saved_copy;
9522 RXp_MATCH_COPIED_off(rex);
9525 eval_state->subbeg = NULL;
9526 rex->subbeg = (char *)reginfo->strbeg;
9528 rex->subcoffset = 0;
9529 rex->sublen = reginfo->strend - reginfo->strbeg;
9533 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9536 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9538 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9539 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9542 Safefree(aux->poscache);
9546 /* undo the effects of S_setup_eval_state() */
9548 if (eval_state->subbeg) {
9549 regexp * const rex = eval_state->rex;
9550 rex->subbeg = eval_state->subbeg;
9551 rex->sublen = eval_state->sublen;
9552 rex->suboffset = eval_state->suboffset;
9553 rex->subcoffset = eval_state->subcoffset;
9555 rex->saved_copy = eval_state->saved_copy;
9557 RXp_MATCH_COPIED_on(rex);
9559 if (eval_state->pos_magic)
9561 eval_state->pos_magic->mg_len = eval_state->pos;
9562 eval_state->pos_magic->mg_flags =
9563 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9564 | (eval_state->pos_flags & MGf_BYTES);
9567 PL_curpm = eval_state->curpm;
9570 PL_regmatch_state = aux->old_regmatch_state;
9571 PL_regmatch_slab = aux->old_regmatch_slab;
9573 /* free all slabs above current one - this must be the last action
9574 * of this function, as aux and eval_state are allocated within
9575 * slabs and may be freed here */
9577 s = PL_regmatch_slab->next;
9579 PL_regmatch_slab->next = NULL;
9581 regmatch_slab * const osl = s;
9590 S_to_utf8_substr(pTHX_ regexp *prog)
9592 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9593 * on the converted value */
9597 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9600 if (prog->substrs->data[i].substr
9601 && !prog->substrs->data[i].utf8_substr) {
9602 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9603 prog->substrs->data[i].utf8_substr = sv;
9604 sv_utf8_upgrade(sv);
9605 if (SvVALID(prog->substrs->data[i].substr)) {
9606 if (SvTAIL(prog->substrs->data[i].substr)) {
9607 /* Trim the trailing \n that fbm_compile added last
9609 SvCUR_set(sv, SvCUR(sv) - 1);
9610 /* Whilst this makes the SV technically "invalid" (as its
9611 buffer is no longer followed by "\0") when fbm_compile()
9612 adds the "\n" back, a "\0" is restored. */
9613 fbm_compile(sv, FBMcf_TAIL);
9617 if (prog->substrs->data[i].substr == prog->check_substr)
9618 prog->check_utf8 = sv;
9624 S_to_byte_substr(pTHX_ regexp *prog)
9626 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9627 * on the converted value; returns FALSE if can't be converted. */
9631 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9634 if (prog->substrs->data[i].utf8_substr
9635 && !prog->substrs->data[i].substr) {
9636 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9637 if (! sv_utf8_downgrade(sv, TRUE)) {
9640 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9641 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9642 /* Trim the trailing \n that fbm_compile added last
9644 SvCUR_set(sv, SvCUR(sv) - 1);
9645 fbm_compile(sv, FBMcf_TAIL);
9649 prog->substrs->data[i].substr = sv;
9650 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9651 prog->check_substr = sv;
9659 * ex: set ts=8 sts=4 sw=4 et: