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))
123 #define HOPc(pos,off) \
124 (char *)(reginfo->is_utf8_target \
125 ? reghop3((U8*)pos, off, \
126 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
129 /* like HOPMAYBE3 but backwards. lim must be +ve. Returns NULL on overshoot */
130 #define HOPBACK3(pos, off, lim) \
131 (reginfo->is_utf8_target \
132 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(lim)) \
133 : (pos - off >= lim) \
137 #define HOPBACKc(pos, off) ((char*)HOPBACK3(pos, off, reginfo->strbeg))
139 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
140 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
142 /* lim must be +ve. Returns NULL on overshoot */
143 #define HOPMAYBE3(pos,off,lim) \
144 (reginfo->is_utf8_target \
145 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
146 : ((U8*)pos + off <= lim) \
150 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
151 * off must be >=0; args should be vars rather than expressions */
152 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
153 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
154 : (U8*)((pos + off) > lim ? lim : (pos + off)))
155 #define HOP3clim(pos,off,lim) ((char*)HOP3lim(pos,off,lim))
157 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
158 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
160 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
162 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
163 #define NEXTCHR_IS_EOS (nextchr < 0)
165 #define SET_nextchr \
166 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
168 #define SET_locinput(p) \
173 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
175 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
176 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
177 1, 0, invlist, &flags); \
182 /* If in debug mode, we test that a known character properly matches */
184 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
187 utf8_char_in_property) \
188 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
189 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
191 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
194 utf8_char_in_property) \
195 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
198 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
199 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
201 PL_XPosix_ptrs[_CC_WORDCHAR], \
202 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
204 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
205 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
207 /* for use after a quantifier and before an EXACT-like node -- japhy */
208 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
210 * NOTE that *nothing* that affects backtracking should be in here, specifically
211 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
212 * node that is in between two EXACT like nodes when ascertaining what the required
213 * "follow" character is. This should probably be moved to regex compile time
214 * although it may be done at run time beause of the REF possibility - more
215 * investigation required. -- demerphq
217 #define JUMPABLE(rn) ( \
219 (OP(rn) == CLOSE && \
220 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
222 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
223 OP(rn) == PLUS || OP(rn) == MINMOD || \
225 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
227 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
229 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
232 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
233 we don't need this definition. XXX These are now out-of-sync*/
234 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
235 #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 )
236 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
239 /* ... so we use this as its faster. */
240 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
241 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
242 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
243 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
248 Search for mandatory following text node; for lookahead, the text must
249 follow but for lookbehind (rn->flags != 0) we skip to the next step.
251 #define FIND_NEXT_IMPT(rn) STMT_START { \
252 while (JUMPABLE(rn)) { \
253 const OPCODE type = OP(rn); \
254 if (type == SUSPEND || PL_regkind[type] == CURLY) \
255 rn = NEXTOPER(NEXTOPER(rn)); \
256 else if (type == PLUS) \
258 else if (type == IFMATCH) \
259 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
260 else rn += NEXT_OFF(rn); \
264 #define SLAB_FIRST(s) (&(s)->states[0])
265 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
267 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
268 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
269 static regmatch_state * S_push_slab(pTHX);
271 #define REGCP_PAREN_ELEMS 3
272 #define REGCP_OTHER_ELEMS 3
273 #define REGCP_FRAME_ELEMS 1
274 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
275 * are needed for the regexp context stack bookkeeping. */
278 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
280 const int retval = PL_savestack_ix;
281 const int paren_elems_to_push =
282 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
283 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
284 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
286 GET_RE_DEBUG_FLAGS_DECL;
288 PERL_ARGS_ASSERT_REGCPPUSH;
290 if (paren_elems_to_push < 0)
291 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
292 (int)paren_elems_to_push, (int)maxopenparen,
293 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
295 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
296 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
297 " out of range (%lu-%ld)",
299 (unsigned long)maxopenparen,
302 SSGROW(total_elems + REGCP_FRAME_ELEMS);
305 if ((int)maxopenparen > (int)parenfloor)
306 Perl_re_exec_indentf( aTHX_
307 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
313 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
314 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
315 SSPUSHIV(rex->offs[p].end);
316 SSPUSHIV(rex->offs[p].start);
317 SSPUSHINT(rex->offs[p].start_tmp);
318 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
319 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
322 (IV)rex->offs[p].start,
323 (IV)rex->offs[p].start_tmp,
327 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
328 SSPUSHINT(maxopenparen);
329 SSPUSHINT(rex->lastparen);
330 SSPUSHINT(rex->lastcloseparen);
331 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
336 /* These are needed since we do not localize EVAL nodes: */
337 #define REGCP_SET(cp) \
339 Perl_re_exec_indentf( aTHX_ \
340 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
341 depth, (IV)PL_savestack_ix \
346 #define REGCP_UNWIND(cp) \
348 if (cp != PL_savestack_ix) \
349 Perl_re_exec_indentf( aTHX_ \
350 "Clearing an EVAL scope, savestack=%" \
351 IVdf "..%" IVdf "\n", \
352 depth, (IV)(cp), (IV)PL_savestack_ix \
357 #define UNWIND_PAREN(lp, lcp) \
358 for (n = rex->lastparen; n > lp; n--) \
359 rex->offs[n].end = -1; \
360 rex->lastparen = n; \
361 rex->lastcloseparen = lcp;
365 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
369 GET_RE_DEBUG_FLAGS_DECL;
371 PERL_ARGS_ASSERT_REGCPPOP;
373 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
375 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
376 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
377 rex->lastcloseparen = SSPOPINT;
378 rex->lastparen = SSPOPINT;
379 *maxopenparen_p = SSPOPINT;
381 i -= REGCP_OTHER_ELEMS;
382 /* Now restore the parentheses context. */
384 if (i || rex->lastparen + 1 <= rex->nparens)
385 Perl_re_exec_indentf( aTHX_
386 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
392 paren = *maxopenparen_p;
393 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
395 rex->offs[paren].start_tmp = SSPOPINT;
396 rex->offs[paren].start = SSPOPIV;
398 if (paren <= rex->lastparen)
399 rex->offs[paren].end = tmps;
400 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
401 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
404 (IV)rex->offs[paren].start,
405 (IV)rex->offs[paren].start_tmp,
406 (IV)rex->offs[paren].end,
407 (paren > rex->lastparen ? "(skipped)" : ""));
412 /* It would seem that the similar code in regtry()
413 * already takes care of this, and in fact it is in
414 * a better location to since this code can #if 0-ed out
415 * but the code in regtry() is needed or otherwise tests
416 * requiring null fields (pat.t#187 and split.t#{13,14}
417 * (as of patchlevel 7877) will fail. Then again,
418 * this code seems to be necessary or otherwise
419 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
420 * --jhi updated by dapm */
421 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
422 if (i > *maxopenparen_p)
423 rex->offs[i].start = -1;
424 rex->offs[i].end = -1;
425 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
426 " \\%" UVuf ": %s ..-1 undeffing\n",
429 (i > *maxopenparen_p) ? "-1" : " "
435 /* restore the parens and associated vars at savestack position ix,
436 * but without popping the stack */
439 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
441 I32 tmpix = PL_savestack_ix;
442 PERL_ARGS_ASSERT_REGCP_RESTORE;
444 PL_savestack_ix = ix;
445 regcppop(rex, maxopenparen_p);
446 PL_savestack_ix = tmpix;
449 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
451 #ifndef PERL_IN_XSUB_RE
454 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
456 /* Returns a boolean as to whether or not 'character' is a member of the
457 * Posix character class given by 'classnum' that should be equivalent to a
458 * value in the typedef '_char_class_number'.
460 * Ideally this could be replaced by a just an array of function pointers
461 * to the C library functions that implement the macros this calls.
462 * However, to compile, the precise function signatures are required, and
463 * these may vary from platform to to platform. To avoid having to figure
464 * out what those all are on each platform, I (khw) am using this method,
465 * which adds an extra layer of function call overhead (unless the C
466 * optimizer strips it away). But we don't particularly care about
467 * performance with locales anyway. */
469 switch ((_char_class_number) classnum) {
470 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
471 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
472 case _CC_ENUM_ASCII: return isASCII_LC(character);
473 case _CC_ENUM_BLANK: return isBLANK_LC(character);
474 case _CC_ENUM_CASED: return isLOWER_LC(character)
475 || isUPPER_LC(character);
476 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
477 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
478 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
479 case _CC_ENUM_LOWER: return isLOWER_LC(character);
480 case _CC_ENUM_PRINT: return isPRINT_LC(character);
481 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
482 case _CC_ENUM_SPACE: return isSPACE_LC(character);
483 case _CC_ENUM_UPPER: return isUPPER_LC(character);
484 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
485 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
486 default: /* VERTSPACE should never occur in locales */
487 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
490 NOT_REACHED; /* NOTREACHED */
497 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
499 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
500 * 'character' is a member of the Posix character class given by 'classnum'
501 * that should be equivalent to a value in the typedef
502 * '_char_class_number'.
504 * This just calls isFOO_lc on the code point for the character if it is in
505 * the range 0-255. Outside that range, all characters use Unicode
506 * rules, ignoring any locale. So use the Unicode function if this class
507 * requires a swash, and use the Unicode macro otherwise. */
509 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
511 if (UTF8_IS_INVARIANT(*character)) {
512 return isFOO_lc(classnum, *character);
514 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
515 return isFOO_lc(classnum,
516 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
519 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
521 if (classnum < _FIRST_NON_SWASH_CC) {
523 /* Initialize the swash unless done already */
524 if (! PL_utf8_swash_ptrs[classnum]) {
525 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
526 PL_utf8_swash_ptrs[classnum] =
527 _core_swash_init("utf8",
530 PL_XPosix_ptrs[classnum], &flags);
533 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
535 TRUE /* is UTF */ ));
538 switch ((_char_class_number) classnum) {
539 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
540 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
541 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
542 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
546 return FALSE; /* Things like CNTRL are always below 256 */
550 * pregexec and friends
553 #ifndef PERL_IN_XSUB_RE
555 - pregexec - match a regexp against a string
558 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
559 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
560 /* stringarg: the point in the string at which to begin matching */
561 /* strend: pointer to null at end of string */
562 /* strbeg: real beginning of string */
563 /* minend: end of match must be >= minend bytes after stringarg. */
564 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
565 * itself is accessed via the pointers above */
566 /* nosave: For optimizations. */
568 PERL_ARGS_ASSERT_PREGEXEC;
571 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
572 nosave ? 0 : REXEC_COPY_STR);
578 /* re_intuit_start():
580 * Based on some optimiser hints, try to find the earliest position in the
581 * string where the regex could match.
583 * rx: the regex to match against
584 * sv: the SV being matched: only used for utf8 flag; the string
585 * itself is accessed via the pointers below. Note that on
586 * something like an overloaded SV, SvPOK(sv) may be false
587 * and the string pointers may point to something unrelated to
589 * strbeg: real beginning of string
590 * strpos: the point in the string at which to begin matching
591 * strend: pointer to the byte following the last char of the string
592 * flags currently unused; set to 0
593 * data: currently unused; set to NULL
595 * The basic idea of re_intuit_start() is to use some known information
596 * about the pattern, namely:
598 * a) the longest known anchored substring (i.e. one that's at a
599 * constant offset from the beginning of the pattern; but not
600 * necessarily at a fixed offset from the beginning of the
602 * b) the longest floating substring (i.e. one that's not at a constant
603 * offset from the beginning of the pattern);
604 * c) Whether the pattern is anchored to the string; either
605 * an absolute anchor: /^../, or anchored to \n: /^.../m,
606 * or anchored to pos(): /\G/;
607 * d) A start class: a real or synthetic character class which
608 * represents which characters are legal at the start of the pattern;
610 * to either quickly reject the match, or to find the earliest position
611 * within the string at which the pattern might match, thus avoiding
612 * running the full NFA engine at those earlier locations, only to
613 * eventually fail and retry further along.
615 * Returns NULL if the pattern can't match, or returns the address within
616 * the string which is the earliest place the match could occur.
618 * The longest of the anchored and floating substrings is called 'check'
619 * and is checked first. The other is called 'other' and is checked
620 * second. The 'other' substring may not be present. For example,
622 * /(abc|xyz)ABC\d{0,3}DEFG/
626 * check substr (float) = "DEFG", offset 6..9 chars
627 * other substr (anchored) = "ABC", offset 3..3 chars
630 * Be aware that during the course of this function, sometimes 'anchored'
631 * refers to a substring being anchored relative to the start of the
632 * pattern, and sometimes to the pattern itself being anchored relative to
633 * the string. For example:
635 * /\dabc/: "abc" is anchored to the pattern;
636 * /^\dabc/: "abc" is anchored to the pattern and the string;
637 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
638 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
639 * but the pattern is anchored to the string.
643 Perl_re_intuit_start(pTHX_
646 const char * const strbeg,
650 re_scream_pos_data *data)
652 struct regexp *const prog = ReANY(rx);
653 SSize_t start_shift = prog->check_offset_min;
654 /* Should be nonnegative! */
655 SSize_t end_shift = 0;
656 /* current lowest pos in string where the regex can start matching */
657 char *rx_origin = strpos;
659 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
660 U8 other_ix = 1 - prog->substrs->check_ix;
662 char *other_last = strpos;/* latest pos 'other' substr already checked to */
663 char *check_at = NULL; /* check substr found at this pos */
664 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
665 RXi_GET_DECL(prog,progi);
666 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
667 regmatch_info *const reginfo = ®info_buf;
668 GET_RE_DEBUG_FLAGS_DECL;
670 PERL_ARGS_ASSERT_RE_INTUIT_START;
671 PERL_UNUSED_ARG(flags);
672 PERL_UNUSED_ARG(data);
674 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
675 "Intuit: trying to determine minimum start position...\n"));
677 /* for now, assume that all substr offsets are positive. If at some point
678 * in the future someone wants to do clever things with lookbehind and
679 * -ve offsets, they'll need to fix up any code in this function
680 * which uses these offsets. See the thread beginning
681 * <20140113145929.GF27210@iabyn.com>
683 assert(prog->substrs->data[0].min_offset >= 0);
684 assert(prog->substrs->data[0].max_offset >= 0);
685 assert(prog->substrs->data[1].min_offset >= 0);
686 assert(prog->substrs->data[1].max_offset >= 0);
687 assert(prog->substrs->data[2].min_offset >= 0);
688 assert(prog->substrs->data[2].max_offset >= 0);
690 /* for now, assume that if both present, that the floating substring
691 * doesn't start before the anchored substring.
692 * If you break this assumption (e.g. doing better optimisations
693 * with lookahead/behind), then you'll need to audit the code in this
694 * function carefully first
697 ! ( (prog->anchored_utf8 || prog->anchored_substr)
698 && (prog->float_utf8 || prog->float_substr))
699 || (prog->float_min_offset >= prog->anchored_offset));
701 /* byte rather than char calculation for efficiency. It fails
702 * to quickly reject some cases that can't match, but will reject
703 * them later after doing full char arithmetic */
704 if (prog->minlen > strend - strpos) {
705 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
706 " String too short...\n"));
710 RXp_MATCH_UTF8_set(prog, utf8_target);
711 reginfo->is_utf8_target = cBOOL(utf8_target);
712 reginfo->info_aux = NULL;
713 reginfo->strbeg = strbeg;
714 reginfo->strend = strend;
715 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
717 /* not actually used within intuit, but zero for safety anyway */
718 reginfo->poscache_maxiter = 0;
721 if ((!prog->anchored_utf8 && prog->anchored_substr)
722 || (!prog->float_utf8 && prog->float_substr))
723 to_utf8_substr(prog);
724 check = prog->check_utf8;
726 if (!prog->check_substr && prog->check_utf8) {
727 if (! to_byte_substr(prog)) {
728 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
731 check = prog->check_substr;
734 /* dump the various substring data */
735 DEBUG_OPTIMISE_MORE_r({
737 for (i=0; i<=2; i++) {
738 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
739 : prog->substrs->data[i].substr);
743 Perl_re_printf( aTHX_
744 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
745 " useful=%" IVdf " utf8=%d [%s]\n",
747 (IV)prog->substrs->data[i].min_offset,
748 (IV)prog->substrs->data[i].max_offset,
749 (IV)prog->substrs->data[i].end_shift,
756 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
758 /* ml_anch: check after \n?
760 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
761 * with /.*.../, these flags will have been added by the
763 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
764 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
766 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
767 && !(prog->intflags & PREGf_IMPLICIT);
769 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
770 /* we are only allowed to match at BOS or \G */
772 /* trivially reject if there's a BOS anchor and we're not at BOS.
774 * Note that we don't try to do a similar quick reject for
775 * \G, since generally the caller will have calculated strpos
776 * based on pos() and gofs, so the string is already correctly
777 * anchored by definition; and handling the exceptions would
778 * be too fiddly (e.g. REXEC_IGNOREPOS).
780 if ( strpos != strbeg
781 && (prog->intflags & PREGf_ANCH_SBOL))
783 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
784 " Not at start...\n"));
788 /* in the presence of an anchor, the anchored (relative to the
789 * start of the regex) substr must also be anchored relative
790 * to strpos. So quickly reject if substr isn't found there.
791 * This works for \G too, because the caller will already have
792 * subtracted gofs from pos, and gofs is the offset from the
793 * \G to the start of the regex. For example, in /.abc\Gdef/,
794 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
795 * caller will have set strpos=pos()-4; we look for the substr
796 * at position pos()-4+1, which lines up with the "a" */
798 if (prog->check_offset_min == prog->check_offset_max) {
799 /* Substring at constant offset from beg-of-str... */
800 SSize_t slen = SvCUR(check);
801 char *s = HOP3c(strpos, prog->check_offset_min, strend);
803 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
804 " Looking for check substr at fixed offset %" IVdf "...\n",
805 (IV)prog->check_offset_min));
808 /* In this case, the regex is anchored at the end too.
809 * Unless it's a multiline match, the lengths must match
810 * exactly, give or take a \n. NB: slen >= 1 since
811 * the last char of check is \n */
813 && ( strend - s > slen
814 || strend - s < slen - 1
815 || (strend - s == slen && strend[-1] != '\n')))
817 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
818 " String too long...\n"));
821 /* Now should match s[0..slen-2] */
824 if (slen && (strend - s < slen
825 || *SvPVX_const(check) != *s
826 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
828 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
829 " String not equal...\n"));
834 goto success_at_start;
839 end_shift = prog->check_end_shift;
841 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
843 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
844 (IV)end_shift, RX_PRECOMP(rx));
849 /* This is the (re)entry point of the main loop in this function.
850 * The goal of this loop is to:
851 * 1) find the "check" substring in the region rx_origin..strend
852 * (adjusted by start_shift / end_shift). If not found, reject
854 * 2) If it exists, look for the "other" substr too if defined; for
855 * example, if the check substr maps to the anchored substr, then
856 * check the floating substr, and vice-versa. If not found, go
857 * back to (1) with rx_origin suitably incremented.
858 * 3) If we find an rx_origin position that doesn't contradict
859 * either of the substrings, then check the possible additional
860 * constraints on rx_origin of /^.../m or a known start class.
861 * If these fail, then depending on which constraints fail, jump
862 * back to here, or to various other re-entry points further along
863 * that skip some of the first steps.
864 * 4) If we pass all those tests, update the BmUSEFUL() count on the
865 * substring. If the start position was determined to be at the
866 * beginning of the string - so, not rejected, but not optimised,
867 * since we have to run regmatch from position 0 - decrement the
868 * BmUSEFUL() count. Otherwise increment it.
872 /* first, look for the 'check' substring */
878 DEBUG_OPTIMISE_MORE_r({
879 Perl_re_printf( aTHX_
880 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
881 " Start shift: %" IVdf " End shift %" IVdf
882 " Real end Shift: %" IVdf "\n",
883 (IV)(rx_origin - strbeg),
884 (IV)prog->check_offset_min,
887 (IV)prog->check_end_shift);
890 end_point = HOPBACK3(strend, end_shift, rx_origin);
893 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
898 /* If the regex is absolutely anchored to either the start of the
899 * string (SBOL) or to pos() (ANCH_GPOS), then
900 * check_offset_max represents an upper bound on the string where
901 * the substr could start. For the ANCH_GPOS case, we assume that
902 * the caller of intuit will have already set strpos to
903 * pos()-gofs, so in this case strpos + offset_max will still be
904 * an upper bound on the substr.
907 && prog->intflags & PREGf_ANCH
908 && prog->check_offset_max != SSize_t_MAX)
910 SSize_t len = SvCUR(check) - !!SvTAIL(check);
911 const char * const anchor =
912 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
914 /* do a bytes rather than chars comparison. It's conservative;
915 * so it skips doing the HOP if the result can't possibly end
916 * up earlier than the old value of end_point.
918 if ((char*)end_point - anchor > prog->check_offset_max) {
919 end_point = HOP3lim((U8*)anchor,
920 prog->check_offset_max,
926 check_at = fbm_instr( start_point, end_point,
927 check, multiline ? FBMrf_MULTILINE : 0);
929 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
930 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
931 (IV)((char*)start_point - strbeg),
932 (IV)((char*)end_point - strbeg),
933 (IV)(check_at ? check_at - strbeg : -1)
936 /* Update the count-of-usability, remove useless subpatterns,
940 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
941 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
942 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
943 (check_at ? "Found" : "Did not find"),
944 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
945 ? "anchored" : "floating"),
948 (check_at ? " at offset " : "...\n") );
953 /* set rx_origin to the minimum position where the regex could start
954 * matching, given the constraint of the just-matched check substring.
955 * But don't set it lower than previously.
958 if (check_at - rx_origin > prog->check_offset_max)
959 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
960 /* Finish the diagnostic message */
961 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
962 "%ld (rx_origin now %" IVdf ")...\n",
963 (long)(check_at - strbeg),
964 (IV)(rx_origin - strbeg)
969 /* now look for the 'other' substring if defined */
971 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
972 : prog->substrs->data[other_ix].substr)
974 /* Take into account the "other" substring. */
978 struct reg_substr_datum *other;
981 other = &prog->substrs->data[other_ix];
983 /* if "other" is anchored:
984 * we've previously found a floating substr starting at check_at.
985 * This means that the regex origin must lie somewhere
986 * between min (rx_origin): HOP3(check_at, -check_offset_max)
987 * and max: HOP3(check_at, -check_offset_min)
988 * (except that min will be >= strpos)
989 * So the fixed substr must lie somewhere between
990 * HOP3(min, anchored_offset)
991 * HOP3(max, anchored_offset) + SvCUR(substr)
994 /* if "other" is floating
995 * Calculate last1, the absolute latest point where the
996 * floating substr could start in the string, ignoring any
997 * constraints from the earlier fixed match. It is calculated
1000 * strend - prog->minlen (in chars) is the absolute latest
1001 * position within the string where the origin of the regex
1002 * could appear. The latest start point for the floating
1003 * substr is float_min_offset(*) on from the start of the
1004 * regex. last1 simply combines thee two offsets.
1006 * (*) You might think the latest start point should be
1007 * float_max_offset from the regex origin, and technically
1008 * you'd be correct. However, consider
1010 * Here, float min, max are 3,5 and minlen is 7.
1011 * This can match either
1015 * In the first case, the regex matches minlen chars; in the
1016 * second, minlen+1, in the third, minlen+2.
1017 * In the first case, the floating offset is 3 (which equals
1018 * float_min), in the second, 4, and in the third, 5 (which
1019 * equals float_max). In all cases, the floating string bcd
1020 * can never start more than 4 chars from the end of the
1021 * string, which equals minlen - float_min. As the substring
1022 * starts to match more than float_min from the start of the
1023 * regex, it makes the regex match more than minlen chars,
1024 * and the two cancel each other out. So we can always use
1025 * float_min - minlen, rather than float_max - minlen for the
1026 * latest position in the string.
1028 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1029 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1032 assert(prog->minlen >= other->min_offset);
1033 last1 = HOP3c(strend,
1034 other->min_offset - prog->minlen, strbeg);
1036 if (other_ix) {/* i.e. if (other-is-float) */
1037 /* last is the latest point where the floating substr could
1038 * start, *given* any constraints from the earlier fixed
1039 * match. This constraint is that the floating string starts
1040 * <= float_max_offset chars from the regex origin (rx_origin).
1041 * If this value is less than last1, use it instead.
1043 assert(rx_origin <= last1);
1045 /* this condition handles the offset==infinity case, and
1046 * is a short-cut otherwise. Although it's comparing a
1047 * byte offset to a char length, it does so in a safe way,
1048 * since 1 char always occupies 1 or more bytes,
1049 * so if a string range is (last1 - rx_origin) bytes,
1050 * it will be less than or equal to (last1 - rx_origin)
1051 * chars; meaning it errs towards doing the accurate HOP3
1052 * rather than just using last1 as a short-cut */
1053 (last1 - rx_origin) < other->max_offset
1055 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1058 assert(strpos + start_shift <= check_at);
1059 last = HOP4c(check_at, other->min_offset - start_shift,
1063 s = HOP3c(rx_origin, other->min_offset, strend);
1064 if (s < other_last) /* These positions already checked */
1067 must = utf8_target ? other->utf8_substr : other->substr;
1068 assert(SvPOK(must));
1071 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1077 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1078 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1079 (IV)(from - strbeg),
1085 (unsigned char*)from,
1088 multiline ? FBMrf_MULTILINE : 0
1090 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1091 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1092 (IV)(from - strbeg),
1094 (IV)(s ? s - strbeg : -1)
1100 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1101 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1102 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1103 s ? "Found" : "Contradicts",
1104 other_ix ? "floating" : "anchored",
1105 quoted, RE_SV_TAIL(must));
1110 /* last1 is latest possible substr location. If we didn't
1111 * find it before there, we never will */
1112 if (last >= last1) {
1113 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1114 "; giving up...\n"));
1118 /* try to find the check substr again at a later
1119 * position. Maybe next time we'll find the "other" substr
1121 other_last = HOP3c(last, 1, strend) /* highest failure */;
1123 other_ix /* i.e. if other-is-float */
1124 ? HOP3c(rx_origin, 1, strend)
1125 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1126 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1127 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1128 (other_ix ? "floating" : "anchored"),
1129 (long)(HOP3c(check_at, 1, strend) - strbeg),
1130 (IV)(rx_origin - strbeg)
1135 if (other_ix) { /* if (other-is-float) */
1136 /* other_last is set to s, not s+1, since its possible for
1137 * a floating substr to fail first time, then succeed
1138 * second time at the same floating position; e.g.:
1139 * "-AB--AABZ" =~ /\wAB\d*Z/
1140 * The first time round, anchored and float match at
1141 * "-(AB)--AAB(Z)" then fail on the initial \w character
1142 * class. Second time round, they match at "-AB--A(AB)(Z)".
1147 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1148 other_last = HOP3c(s, 1, strend);
1150 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1151 " at offset %ld (rx_origin now %" IVdf ")...\n",
1153 (IV)(rx_origin - strbeg)
1159 DEBUG_OPTIMISE_MORE_r(
1160 Perl_re_printf( aTHX_
1161 " Check-only match: offset min:%" IVdf " max:%" IVdf
1162 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1163 " strend:%" IVdf "\n",
1164 (IV)prog->check_offset_min,
1165 (IV)prog->check_offset_max,
1166 (IV)(check_at-strbeg),
1167 (IV)(rx_origin-strbeg),
1168 (IV)(rx_origin-check_at),
1174 postprocess_substr_matches:
1176 /* handle the extra constraint of /^.../m if present */
1178 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1181 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1182 " looking for /^/m anchor"));
1184 /* we have failed the constraint of a \n before rx_origin.
1185 * Find the next \n, if any, even if it's beyond the current
1186 * anchored and/or floating substrings. Whether we should be
1187 * scanning ahead for the next \n or the next substr is debatable.
1188 * On the one hand you'd expect rare substrings to appear less
1189 * often than \n's. On the other hand, searching for \n means
1190 * we're effectively flipping between check_substr and "\n" on each
1191 * iteration as the current "rarest" string candidate, which
1192 * means for example that we'll quickly reject the whole string if
1193 * hasn't got a \n, rather than trying every substr position
1197 s = HOP3c(strend, - prog->minlen, strpos);
1198 if (s <= rx_origin ||
1199 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1201 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1202 " Did not find /%s^%s/m...\n",
1203 PL_colors[0], PL_colors[1]));
1207 /* earliest possible origin is 1 char after the \n.
1208 * (since *rx_origin == '\n', it's safe to ++ here rather than
1209 * HOP(rx_origin, 1)) */
1212 if (prog->substrs->check_ix == 0 /* check is anchored */
1213 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1215 /* Position contradicts check-string; either because
1216 * check was anchored (and thus has no wiggle room),
1217 * or check was float and rx_origin is above the float range */
1218 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1219 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1220 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1224 /* if we get here, the check substr must have been float,
1225 * is in range, and we may or may not have had an anchored
1226 * "other" substr which still contradicts */
1227 assert(prog->substrs->check_ix); /* check is float */
1229 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1230 /* whoops, the anchored "other" substr exists, so we still
1231 * contradict. On the other hand, the float "check" substr
1232 * didn't contradict, so just retry the anchored "other"
1234 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1235 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1236 PL_colors[0], PL_colors[1],
1237 (IV)(rx_origin - strbeg + prog->anchored_offset),
1238 (IV)(rx_origin - strbeg)
1240 goto do_other_substr;
1243 /* success: we don't contradict the found floating substring
1244 * (and there's no anchored substr). */
1245 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1246 " Found /%s^%s/m with rx_origin %ld...\n",
1247 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1250 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1251 " (multiline anchor test skipped)\n"));
1257 /* if we have a starting character class, then test that extra constraint.
1258 * (trie stclasses are too expensive to use here, we are better off to
1259 * leave it to regmatch itself) */
1261 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1262 const U8* const str = (U8*)STRING(progi->regstclass);
1264 /* XXX this value could be pre-computed */
1265 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1266 ? (reginfo->is_utf8_pat
1267 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1268 : STR_LEN(progi->regstclass))
1272 /* latest pos that a matching float substr constrains rx start to */
1273 char *rx_max_float = NULL;
1275 /* if the current rx_origin is anchored, either by satisfying an
1276 * anchored substring constraint, or a /^.../m constraint, then we
1277 * can reject the current origin if the start class isn't found
1278 * at the current position. If we have a float-only match, then
1279 * rx_origin is constrained to a range; so look for the start class
1280 * in that range. if neither, then look for the start class in the
1281 * whole rest of the string */
1283 /* XXX DAPM it's not clear what the minlen test is for, and why
1284 * it's not used in the floating case. Nothing in the test suite
1285 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1286 * Here are some old comments, which may or may not be correct:
1288 * minlen == 0 is possible if regstclass is \b or \B,
1289 * and the fixed substr is ''$.
1290 * Since minlen is already taken into account, rx_origin+1 is
1291 * before strend; accidentally, minlen >= 1 guaranties no false
1292 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1293 * 0) below assumes that regstclass does not come from lookahead...
1294 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1295 * This leaves EXACTF-ish only, which are dealt with in
1299 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1300 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1301 else if (prog->float_substr || prog->float_utf8) {
1302 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1303 endpos = HOP3clim(rx_max_float, cl_l, strend);
1308 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1309 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1310 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1311 (IV)start_shift, (IV)(check_at - strbeg),
1312 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1314 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1317 if (endpos == strend) {
1318 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1319 " Could not match STCLASS...\n") );
1322 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1323 " This position contradicts STCLASS...\n") );
1324 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1325 && !(prog->intflags & PREGf_IMPLICIT))
1328 /* Contradict one of substrings */
1329 if (prog->anchored_substr || prog->anchored_utf8) {
1330 if (prog->substrs->check_ix == 1) { /* check is float */
1331 /* Have both, check_string is floating */
1332 assert(rx_origin + start_shift <= check_at);
1333 if (rx_origin + start_shift != check_at) {
1334 /* not at latest position float substr could match:
1335 * Recheck anchored substring, but not floating.
1336 * The condition above is in bytes rather than
1337 * chars for efficiency. It's conservative, in
1338 * that it errs on the side of doing 'goto
1339 * do_other_substr'. In this case, at worst,
1340 * an extra anchored search may get done, but in
1341 * practice the extra fbm_instr() is likely to
1342 * get skipped anyway. */
1343 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1344 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1345 (long)(other_last - strbeg),
1346 (IV)(rx_origin - strbeg)
1348 goto do_other_substr;
1356 /* In the presence of ml_anch, we might be able to
1357 * find another \n without breaking the current float
1360 /* strictly speaking this should be HOP3c(..., 1, ...),
1361 * but since we goto a block of code that's going to
1362 * search for the next \n if any, its safe here */
1364 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1365 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1366 PL_colors[0], PL_colors[1],
1367 (long)(rx_origin - strbeg)) );
1368 goto postprocess_substr_matches;
1371 /* strictly speaking this can never be true; but might
1372 * be if we ever allow intuit without substrings */
1373 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1376 rx_origin = rx_max_float;
1379 /* at this point, any matching substrings have been
1380 * contradicted. Start again... */
1382 rx_origin = HOP3c(rx_origin, 1, strend);
1384 /* uses bytes rather than char calculations for efficiency.
1385 * It's conservative: it errs on the side of doing 'goto restart',
1386 * where there is code that does a proper char-based test */
1387 if (rx_origin + start_shift + end_shift > strend) {
1388 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1389 " Could not match STCLASS...\n") );
1392 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1393 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1394 (prog->substrs->check_ix ? "floating" : "anchored"),
1395 (long)(rx_origin + start_shift - strbeg),
1396 (IV)(rx_origin - strbeg)
1403 if (rx_origin != s) {
1404 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1405 " By STCLASS: moving %ld --> %ld\n",
1406 (long)(rx_origin - strbeg), (long)(s - strbeg))
1410 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1411 " Does not contradict STCLASS...\n");
1416 /* Decide whether using the substrings helped */
1418 if (rx_origin != strpos) {
1419 /* Fixed substring is found far enough so that the match
1420 cannot start at strpos. */
1422 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1423 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1426 /* The found rx_origin position does not prohibit matching at
1427 * strpos, so calling intuit didn't gain us anything. Decrement
1428 * the BmUSEFUL() count on the check substring, and if we reach
1430 if (!(prog->intflags & PREGf_NAUGHTY)
1432 prog->check_utf8 /* Could be deleted already */
1433 && --BmUSEFUL(prog->check_utf8) < 0
1434 && (prog->check_utf8 == prog->float_utf8)
1436 prog->check_substr /* Could be deleted already */
1437 && --BmUSEFUL(prog->check_substr) < 0
1438 && (prog->check_substr == prog->float_substr)
1441 /* If flags & SOMETHING - do not do it many times on the same match */
1442 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1443 /* XXX Does the destruction order has to change with utf8_target? */
1444 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1445 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1446 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1447 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1448 check = NULL; /* abort */
1449 /* XXXX This is a remnant of the old implementation. It
1450 looks wasteful, since now INTUIT can use many
1451 other heuristics. */
1452 prog->extflags &= ~RXf_USE_INTUIT;
1456 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1457 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1458 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1462 fail_finish: /* Substring not found */
1463 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1464 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1466 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1467 PL_colors[4], PL_colors[5]));
1472 #define DECL_TRIE_TYPE(scan) \
1473 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1474 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1475 trie_utf8l, trie_flu8 } \
1476 trie_type = ((scan->flags == EXACT) \
1477 ? (utf8_target ? trie_utf8 : trie_plain) \
1478 : (scan->flags == EXACTL) \
1479 ? (utf8_target ? trie_utf8l : trie_plain) \
1480 : (scan->flags == EXACTFA) \
1482 ? trie_utf8_exactfa_fold \
1483 : trie_latin_utf8_exactfa_fold) \
1484 : (scan->flags == EXACTFLU8 \
1488 : trie_latin_utf8_fold)))
1490 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1493 U8 flags = FOLD_FLAGS_FULL; \
1494 switch (trie_type) { \
1496 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1497 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1498 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1500 goto do_trie_utf8_fold; \
1501 case trie_utf8_exactfa_fold: \
1502 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1504 case trie_utf8_fold: \
1505 do_trie_utf8_fold: \
1506 if ( foldlen>0 ) { \
1507 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1512 len = UTF8SKIP(uc); \
1513 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc + len, foldbuf, &foldlen, \
1515 skiplen = UVCHR_SKIP( uvc ); \
1516 foldlen -= skiplen; \
1517 uscan = foldbuf + skiplen; \
1520 case trie_latin_utf8_exactfa_fold: \
1521 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1523 case trie_latin_utf8_fold: \
1524 if ( foldlen>0 ) { \
1525 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1531 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1532 skiplen = UVCHR_SKIP( uvc ); \
1533 foldlen -= skiplen; \
1534 uscan = foldbuf + skiplen; \
1538 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1539 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1540 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1544 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1551 charid = trie->charmap[ uvc ]; \
1555 if (widecharmap) { \
1556 SV** const svpp = hv_fetch(widecharmap, \
1557 (char*)&uvc, sizeof(UV), 0); \
1559 charid = (U16)SvIV(*svpp); \
1564 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1565 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1566 startpos, doutf8, depth)
1568 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1572 && (ln == 1 || folder(s, pat_string, ln)) \
1573 && (reginfo->intuit || regtry(reginfo, &s)) )\
1579 #define REXEC_FBC_UTF8_SCAN(CODE) \
1581 while (s < strend) { \
1587 #define REXEC_FBC_SCAN(CODE) \
1589 while (s < strend) { \
1595 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1596 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1598 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1607 #define REXEC_FBC_CLASS_SCAN(COND) \
1608 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1610 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1619 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1620 if (utf8_target) { \
1621 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1624 REXEC_FBC_CLASS_SCAN(COND); \
1627 /* The three macros below are slightly different versions of the same logic.
1629 * The first is for /a and /aa when the target string is UTF-8. This can only
1630 * match ascii, but it must advance based on UTF-8. The other two handle the
1631 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1632 * for the boundary (or non-boundary) between a word and non-word character.
1633 * The utf8 and non-utf8 cases have the same logic, but the details must be
1634 * different. Find the "wordness" of the character just prior to this one, and
1635 * compare it with the wordness of this one. If they differ, we have a
1636 * boundary. At the beginning of the string, pretend that the previous
1637 * character was a new-line.
1639 * All these macros uncleanly have side-effects with each other and outside
1640 * variables. So far it's been too much trouble to clean-up
1642 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1643 * a word character or not.
1644 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1646 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1648 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1649 * are looking for a boundary or for a non-boundary. If we are looking for a
1650 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1651 * see if this tentative match actually works, and if so, to quit the loop
1652 * here. And vice-versa if we are looking for a non-boundary.
1654 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1655 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1656 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1657 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1658 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1659 * complement. But in that branch we complement tmp, meaning that at the
1660 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1661 * which means at the top of the loop in the next iteration, it is
1662 * TEST_NON_UTF8(s-1) */
1663 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1664 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1665 tmp = TEST_NON_UTF8(tmp); \
1666 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1667 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1669 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1676 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1677 * TEST_UTF8 is a macro that for the same input code points returns identically
1678 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1679 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1680 if (s == reginfo->strbeg) { \
1683 else { /* Back-up to the start of the previous character */ \
1684 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1685 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1686 0, UTF8_ALLOW_DEFAULT); \
1688 tmp = TEST_UV(tmp); \
1689 LOAD_UTF8_CHARCLASS_ALNUM(); \
1690 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1691 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1700 /* Like the above two macros. UTF8_CODE is the complete code for handling
1701 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1703 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1704 if (utf8_target) { \
1707 else { /* Not utf8 */ \
1708 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1709 tmp = TEST_NON_UTF8(tmp); \
1710 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1711 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1720 /* Here, things have been set up by the previous code so that tmp is the \
1721 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1722 * utf8ness of the target). We also have to check if this matches against \
1723 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1724 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1726 if (tmp == ! TEST_NON_UTF8('\n')) { \
1733 /* This is the macro to use when we want to see if something that looks like it
1734 * could match, actually does, and if so exits the loop */
1735 #define REXEC_FBC_TRYIT \
1736 if ((reginfo->intuit || regtry(reginfo, &s))) \
1739 /* The only difference between the BOUND and NBOUND cases is that
1740 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1741 * NBOUND. This is accomplished by passing it as either the if or else clause,
1742 * with the other one being empty (PLACEHOLDER is defined as empty).
1744 * The TEST_FOO parameters are for operating on different forms of input, but
1745 * all should be ones that return identically for the same underlying code
1747 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1749 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1750 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1752 #define FBC_BOUND_A(TEST_NON_UTF8) \
1754 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1755 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1757 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1759 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1760 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1762 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1764 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1765 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1769 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1770 IV cp_out = Perl__invlist_search(invlist, cp_in);
1771 assert(cp_out >= 0);
1774 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1775 invmap[S_get_break_val_cp_checked(invlist, cp)]
1777 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1778 invmap[_invlist_search(invlist, cp)]
1781 /* Takes a pointer to an inversion list, a pointer to its corresponding
1782 * inversion map, and a code point, and returns the code point's value
1783 * according to the two arrays. It assumes that all code points have a value.
1784 * This is used as the base macro for macros for particular properties */
1785 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1786 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1788 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1789 * of a code point, returning the value for the first code point in the string.
1790 * And it takes the particular macro name that finds the desired value given a
1791 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1792 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1793 (__ASSERT_(pos < strend) \
1794 /* Note assumes is valid UTF-8 */ \
1795 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1797 /* Returns the GCB value for the input code point */
1798 #define getGCB_VAL_CP(cp) \
1799 _generic_GET_BREAK_VAL_CP( \
1804 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1805 * bounded by pos and strend */
1806 #define getGCB_VAL_UTF8(pos, strend) \
1807 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1809 /* Returns the LB value for the input code point */
1810 #define getLB_VAL_CP(cp) \
1811 _generic_GET_BREAK_VAL_CP( \
1816 /* Returns the LB value for the first code point in the UTF-8 encoded string
1817 * bounded by pos and strend */
1818 #define getLB_VAL_UTF8(pos, strend) \
1819 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1822 /* Returns the SB value for the input code point */
1823 #define getSB_VAL_CP(cp) \
1824 _generic_GET_BREAK_VAL_CP( \
1829 /* Returns the SB value for the first code point in the UTF-8 encoded string
1830 * bounded by pos and strend */
1831 #define getSB_VAL_UTF8(pos, strend) \
1832 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1834 /* Returns the WB value for the input code point */
1835 #define getWB_VAL_CP(cp) \
1836 _generic_GET_BREAK_VAL_CP( \
1841 /* Returns the WB value for the first code point in the UTF-8 encoded string
1842 * bounded by pos and strend */
1843 #define getWB_VAL_UTF8(pos, strend) \
1844 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1846 /* We know what class REx starts with. Try to find this position... */
1847 /* if reginfo->intuit, its a dryrun */
1848 /* annoyingly all the vars in this routine have different names from their counterparts
1849 in regmatch. /grrr */
1851 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1852 const char *strend, regmatch_info *reginfo)
1855 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1856 char *pat_string; /* The pattern's exactish string */
1857 char *pat_end; /* ptr to end char of pat_string */
1858 re_fold_t folder; /* Function for computing non-utf8 folds */
1859 const U8 *fold_array; /* array for folding ords < 256 */
1865 I32 tmp = 1; /* Scratch variable? */
1866 const bool utf8_target = reginfo->is_utf8_target;
1867 UV utf8_fold_flags = 0;
1868 const bool is_utf8_pat = reginfo->is_utf8_pat;
1869 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1870 with a result inverts that result, as 0^1 =
1872 _char_class_number classnum;
1874 RXi_GET_DECL(prog,progi);
1876 PERL_ARGS_ASSERT_FIND_BYCLASS;
1878 /* We know what class it must start with. */
1881 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1883 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1884 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1891 REXEC_FBC_UTF8_CLASS_SCAN(
1892 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1894 else if (ANYOF_FLAGS(c)) {
1895 REXEC_FBC_CLASS_SCAN(reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
1898 REXEC_FBC_CLASS_SCAN(ANYOF_BITMAP_TEST(c, *((U8*)s)));
1902 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1903 assert(! is_utf8_pat);
1906 if (is_utf8_pat || utf8_target) {
1907 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1908 goto do_exactf_utf8;
1910 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1911 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1912 goto do_exactf_non_utf8; /* isn't dealt with by these */
1914 case EXACTF: /* This node only generated for non-utf8 patterns */
1915 assert(! is_utf8_pat);
1917 utf8_fold_flags = 0;
1918 goto do_exactf_utf8;
1920 fold_array = PL_fold;
1922 goto do_exactf_non_utf8;
1925 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1926 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1927 utf8_fold_flags = FOLDEQ_LOCALE;
1928 goto do_exactf_utf8;
1930 fold_array = PL_fold_locale;
1931 folder = foldEQ_locale;
1932 goto do_exactf_non_utf8;
1936 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1938 goto do_exactf_utf8;
1941 if (! utf8_target) { /* All code points in this node require
1942 UTF-8 to express. */
1945 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1946 | FOLDEQ_S2_FOLDS_SANE;
1947 goto do_exactf_utf8;
1950 if (is_utf8_pat || utf8_target) {
1951 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1952 goto do_exactf_utf8;
1955 /* Any 'ss' in the pattern should have been replaced by regcomp,
1956 * so we don't have to worry here about this single special case
1957 * in the Latin1 range */
1958 fold_array = PL_fold_latin1;
1959 folder = foldEQ_latin1;
1963 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1964 are no glitches with fold-length differences
1965 between the target string and pattern */
1967 /* The idea in the non-utf8 EXACTF* cases is to first find the
1968 * first character of the EXACTF* node and then, if necessary,
1969 * case-insensitively compare the full text of the node. c1 is the
1970 * first character. c2 is its fold. This logic will not work for
1971 * Unicode semantics and the german sharp ss, which hence should
1972 * not be compiled into a node that gets here. */
1973 pat_string = STRING(c);
1974 ln = STR_LEN(c); /* length to match in octets/bytes */
1976 /* We know that we have to match at least 'ln' bytes (which is the
1977 * same as characters, since not utf8). If we have to match 3
1978 * characters, and there are only 2 availabe, we know without
1979 * trying that it will fail; so don't start a match past the
1980 * required minimum number from the far end */
1981 e = HOP3c(strend, -((SSize_t)ln), s);
1986 c2 = fold_array[c1];
1987 if (c1 == c2) { /* If char and fold are the same */
1988 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1991 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1999 /* If one of the operands is in utf8, we can't use the simpler folding
2000 * above, due to the fact that many different characters can have the
2001 * same fold, or portion of a fold, or different- length fold */
2002 pat_string = STRING(c);
2003 ln = STR_LEN(c); /* length to match in octets/bytes */
2004 pat_end = pat_string + ln;
2005 lnc = is_utf8_pat /* length to match in characters */
2006 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2009 /* We have 'lnc' characters to match in the pattern, but because of
2010 * multi-character folding, each character in the target can match
2011 * up to 3 characters (Unicode guarantees it will never exceed
2012 * this) if it is utf8-encoded; and up to 2 if not (based on the
2013 * fact that the Latin 1 folds are already determined, and the
2014 * only multi-char fold in that range is the sharp-s folding to
2015 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2016 * string character. Adjust lnc accordingly, rounding up, so that
2017 * if we need to match at least 4+1/3 chars, that really is 5. */
2018 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2019 lnc = (lnc + expansion - 1) / expansion;
2021 /* As in the non-UTF8 case, if we have to match 3 characters, and
2022 * only 2 are left, it's guaranteed to fail, so don't start a
2023 * match that would require us to go beyond the end of the string
2025 e = HOP3c(strend, -((SSize_t)lnc), s);
2027 /* XXX Note that we could recalculate e to stop the loop earlier,
2028 * as the worst case expansion above will rarely be met, and as we
2029 * go along we would usually find that e moves further to the left.
2030 * This would happen only after we reached the point in the loop
2031 * where if there were no expansion we should fail. Unclear if
2032 * worth the expense */
2035 char *my_strend= (char *)strend;
2036 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2037 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2038 && (reginfo->intuit || regtry(reginfo, &s)) )
2042 s += (utf8_target) ? UTF8SKIP(s) : 1;
2048 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2049 if (FLAGS(c) != TRADITIONAL_BOUND) {
2050 if (! IN_UTF8_CTYPE_LOCALE) {
2051 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2052 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2057 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2061 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2062 if (FLAGS(c) != TRADITIONAL_BOUND) {
2063 if (! IN_UTF8_CTYPE_LOCALE) {
2064 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2065 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2070 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2073 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2075 assert(FLAGS(c) == TRADITIONAL_BOUND);
2077 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2080 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2082 assert(FLAGS(c) == TRADITIONAL_BOUND);
2084 FBC_BOUND_A(isWORDCHAR_A);
2087 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2089 assert(FLAGS(c) == TRADITIONAL_BOUND);
2091 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2094 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2096 assert(FLAGS(c) == TRADITIONAL_BOUND);
2098 FBC_NBOUND_A(isWORDCHAR_A);
2102 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2103 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2114 switch((bound_type) FLAGS(c)) {
2115 case TRADITIONAL_BOUND:
2116 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2119 if (s == reginfo->strbeg) {
2120 if (reginfo->intuit || regtry(reginfo, &s))
2125 /* Didn't match. Try at the next position (if there is one) */
2126 s += (utf8_target) ? UTF8SKIP(s) : 1;
2127 if (UNLIKELY(s >= reginfo->strend)) {
2133 GCB_enum before = getGCB_VAL_UTF8(
2135 (U8*)(reginfo->strbeg)),
2136 (U8*) reginfo->strend);
2137 while (s < strend) {
2138 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2139 (U8*) reginfo->strend);
2140 if ( (to_complement ^ isGCB(before,
2142 (U8*) reginfo->strbeg,
2145 && (reginfo->intuit || regtry(reginfo, &s)))
2153 else { /* Not utf8. Everything is a GCB except between CR and
2155 while (s < strend) {
2156 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2157 || UCHARAT(s) != '\n'))
2158 && (reginfo->intuit || regtry(reginfo, &s)))
2166 /* And, since this is a bound, it can match after the final
2167 * character in the string */
2168 if ((reginfo->intuit || regtry(reginfo, &s))) {
2174 if (s == reginfo->strbeg) {
2175 if (reginfo->intuit || regtry(reginfo, &s)) {
2178 s += (utf8_target) ? UTF8SKIP(s) : 1;
2179 if (UNLIKELY(s >= reginfo->strend)) {
2185 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2187 (U8*)(reginfo->strbeg)),
2188 (U8*) reginfo->strend);
2189 while (s < strend) {
2190 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2191 if (to_complement ^ isLB(before,
2193 (U8*) reginfo->strbeg,
2195 (U8*) reginfo->strend,
2197 && (reginfo->intuit || regtry(reginfo, &s)))
2205 else { /* Not utf8. */
2206 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2207 while (s < strend) {
2208 LB_enum after = getLB_VAL_CP((U8) *s);
2209 if (to_complement ^ isLB(before,
2211 (U8*) reginfo->strbeg,
2213 (U8*) reginfo->strend,
2215 && (reginfo->intuit || regtry(reginfo, &s)))
2224 if (reginfo->intuit || regtry(reginfo, &s)) {
2231 if (s == reginfo->strbeg) {
2232 if (reginfo->intuit || regtry(reginfo, &s)) {
2235 s += (utf8_target) ? UTF8SKIP(s) : 1;
2236 if (UNLIKELY(s >= reginfo->strend)) {
2242 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2244 (U8*)(reginfo->strbeg)),
2245 (U8*) reginfo->strend);
2246 while (s < strend) {
2247 SB_enum after = getSB_VAL_UTF8((U8*) s,
2248 (U8*) reginfo->strend);
2249 if ((to_complement ^ isSB(before,
2251 (U8*) reginfo->strbeg,
2253 (U8*) reginfo->strend,
2255 && (reginfo->intuit || regtry(reginfo, &s)))
2263 else { /* Not utf8. */
2264 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2265 while (s < strend) {
2266 SB_enum after = getSB_VAL_CP((U8) *s);
2267 if ((to_complement ^ isSB(before,
2269 (U8*) reginfo->strbeg,
2271 (U8*) reginfo->strend,
2273 && (reginfo->intuit || regtry(reginfo, &s)))
2282 /* Here are at the final position in the target string. The SB
2283 * value is always true here, so matches, depending on other
2285 if (reginfo->intuit || regtry(reginfo, &s)) {
2292 if (s == reginfo->strbeg) {
2293 if (reginfo->intuit || regtry(reginfo, &s)) {
2296 s += (utf8_target) ? UTF8SKIP(s) : 1;
2297 if (UNLIKELY(s >= reginfo->strend)) {
2303 /* We are at a boundary between char_sub_0 and char_sub_1.
2304 * We also keep track of the value for char_sub_-1 as we
2305 * loop through the line. Context may be needed to make a
2306 * determination, and if so, this can save having to
2308 WB_enum previous = WB_UNKNOWN;
2309 WB_enum before = getWB_VAL_UTF8(
2312 (U8*)(reginfo->strbeg)),
2313 (U8*) reginfo->strend);
2314 while (s < strend) {
2315 WB_enum after = getWB_VAL_UTF8((U8*) s,
2316 (U8*) reginfo->strend);
2317 if ((to_complement ^ isWB(previous,
2320 (U8*) reginfo->strbeg,
2322 (U8*) reginfo->strend,
2324 && (reginfo->intuit || regtry(reginfo, &s)))
2333 else { /* Not utf8. */
2334 WB_enum previous = WB_UNKNOWN;
2335 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2336 while (s < strend) {
2337 WB_enum after = getWB_VAL_CP((U8) *s);
2338 if ((to_complement ^ isWB(previous,
2341 (U8*) reginfo->strbeg,
2343 (U8*) reginfo->strend,
2345 && (reginfo->intuit || regtry(reginfo, &s)))
2355 if (reginfo->intuit || regtry(reginfo, &s)) {
2362 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2363 is_LNBREAK_latin1_safe(s, strend)
2367 /* The argument to all the POSIX node types is the class number to pass to
2368 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2375 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2376 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2377 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2392 /* The complement of something that matches only ASCII matches all
2393 * non-ASCII, plus everything in ASCII that isn't in the class. */
2394 REXEC_FBC_UTF8_CLASS_SCAN( ! isASCII_utf8_safe(s, strend)
2395 || ! _generic_isCC_A(*s, FLAGS(c)));
2404 /* Don't need to worry about utf8, as it can match only a single
2405 * byte invariant character. */
2406 REXEC_FBC_CLASS_SCAN(
2407 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2415 if (! utf8_target) {
2416 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2422 classnum = (_char_class_number) FLAGS(c);
2423 if (classnum < _FIRST_NON_SWASH_CC) {
2424 while (s < strend) {
2426 /* We avoid loading in the swash as long as possible, but
2427 * should we have to, we jump to a separate loop. This
2428 * extra 'if' statement is what keeps this code from being
2429 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2430 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2431 goto found_above_latin1;
2433 if ((UTF8_IS_INVARIANT(*s)
2434 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2436 || ( UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, strend)
2437 && to_complement ^ cBOOL(
2438 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2442 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2454 else switch (classnum) { /* These classes are implemented as
2456 case _CC_ENUM_SPACE:
2457 REXEC_FBC_UTF8_CLASS_SCAN(
2458 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2461 case _CC_ENUM_BLANK:
2462 REXEC_FBC_UTF8_CLASS_SCAN(
2463 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2466 case _CC_ENUM_XDIGIT:
2467 REXEC_FBC_UTF8_CLASS_SCAN(
2468 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2471 case _CC_ENUM_VERTSPACE:
2472 REXEC_FBC_UTF8_CLASS_SCAN(
2473 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2476 case _CC_ENUM_CNTRL:
2477 REXEC_FBC_UTF8_CLASS_SCAN(
2478 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2482 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2483 NOT_REACHED; /* NOTREACHED */
2488 found_above_latin1: /* Here we have to load a swash to get the result
2489 for the current code point */
2490 if (! PL_utf8_swash_ptrs[classnum]) {
2491 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2492 PL_utf8_swash_ptrs[classnum] =
2493 _core_swash_init("utf8",
2496 PL_XPosix_ptrs[classnum], &flags);
2499 /* This is a copy of the loop above for swash classes, though using the
2500 * FBC macro instead of being expanded out. Since we've loaded the
2501 * swash, we don't have to check for that each time through the loop */
2502 REXEC_FBC_UTF8_CLASS_SCAN(
2503 to_complement ^ cBOOL(_generic_utf8_safe(
2507 swash_fetch(PL_utf8_swash_ptrs[classnum],
2515 /* what trie are we using right now */
2516 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2517 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2518 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2520 const char *last_start = strend - trie->minlen;
2522 const char *real_start = s;
2524 STRLEN maxlen = trie->maxlen;
2526 U8 **points; /* map of where we were in the input string
2527 when reading a given char. For ASCII this
2528 is unnecessary overhead as the relationship
2529 is always 1:1, but for Unicode, especially
2530 case folded Unicode this is not true. */
2531 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2535 GET_RE_DEBUG_FLAGS_DECL;
2537 /* We can't just allocate points here. We need to wrap it in
2538 * an SV so it gets freed properly if there is a croak while
2539 * running the match */
2542 sv_points=newSV(maxlen * sizeof(U8 *));
2543 SvCUR_set(sv_points,
2544 maxlen * sizeof(U8 *));
2545 SvPOK_on(sv_points);
2546 sv_2mortal(sv_points);
2547 points=(U8**)SvPV_nolen(sv_points );
2548 if ( trie_type != trie_utf8_fold
2549 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2552 bitmap=(U8*)trie->bitmap;
2554 bitmap=(U8*)ANYOF_BITMAP(c);
2556 /* this is the Aho-Corasick algorithm modified a touch
2557 to include special handling for long "unknown char" sequences.
2558 The basic idea being that we use AC as long as we are dealing
2559 with a possible matching char, when we encounter an unknown char
2560 (and we have not encountered an accepting state) we scan forward
2561 until we find a legal starting char.
2562 AC matching is basically that of trie matching, except that when
2563 we encounter a failing transition, we fall back to the current
2564 states "fail state", and try the current char again, a process
2565 we repeat until we reach the root state, state 1, or a legal
2566 transition. If we fail on the root state then we can either
2567 terminate if we have reached an accepting state previously, or
2568 restart the entire process from the beginning if we have not.
2571 while (s <= last_start) {
2572 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2580 U8 *uscan = (U8*)NULL;
2581 U8 *leftmost = NULL;
2583 U32 accepted_word= 0;
2587 while ( state && uc <= (U8*)strend ) {
2589 U32 word = aho->states[ state ].wordnum;
2593 DEBUG_TRIE_EXECUTE_r(
2594 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2595 dump_exec_pos( (char *)uc, c, strend, real_start,
2596 (char *)uc, utf8_target, 0 );
2597 Perl_re_printf( aTHX_
2598 " Scanning for legal start char...\n");
2602 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2606 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2612 if (uc >(U8*)last_start) break;
2616 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2617 if (!leftmost || lpos < leftmost) {
2618 DEBUG_r(accepted_word=word);
2624 points[pointpos++ % maxlen]= uc;
2625 if (foldlen || uc < (U8*)strend) {
2626 REXEC_TRIE_READ_CHAR(trie_type, trie,
2628 uscan, len, uvc, charid, foldlen,
2630 DEBUG_TRIE_EXECUTE_r({
2631 dump_exec_pos( (char *)uc, c, strend,
2632 real_start, s, utf8_target, 0);
2633 Perl_re_printf( aTHX_
2634 " Charid:%3u CP:%4" UVxf " ",
2646 word = aho->states[ state ].wordnum;
2648 base = aho->states[ state ].trans.base;
2650 DEBUG_TRIE_EXECUTE_r({
2652 dump_exec_pos( (char *)uc, c, strend, real_start,
2653 s, utf8_target, 0 );
2654 Perl_re_printf( aTHX_
2655 "%sState: %4" UVxf ", word=%" UVxf,
2656 failed ? " Fail transition to " : "",
2657 (UV)state, (UV)word);
2663 ( ((offset = base + charid
2664 - 1 - trie->uniquecharcount)) >= 0)
2665 && ((U32)offset < trie->lasttrans)
2666 && trie->trans[offset].check == state
2667 && (tmp=trie->trans[offset].next))
2669 DEBUG_TRIE_EXECUTE_r(
2670 Perl_re_printf( aTHX_ " - legal\n"));
2675 DEBUG_TRIE_EXECUTE_r(
2676 Perl_re_printf( aTHX_ " - fail\n"));
2678 state = aho->fail[state];
2682 /* we must be accepting here */
2683 DEBUG_TRIE_EXECUTE_r(
2684 Perl_re_printf( aTHX_ " - accepting\n"));
2693 if (!state) state = 1;
2696 if ( aho->states[ state ].wordnum ) {
2697 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2698 if (!leftmost || lpos < leftmost) {
2699 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2704 s = (char*)leftmost;
2705 DEBUG_TRIE_EXECUTE_r({
2706 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
2707 (UV)accepted_word, (IV)(s - real_start)
2710 if (reginfo->intuit || regtry(reginfo, &s)) {
2716 DEBUG_TRIE_EXECUTE_r({
2717 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2720 DEBUG_TRIE_EXECUTE_r(
2721 Perl_re_printf( aTHX_ "No match.\n"));
2730 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2737 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2738 * flags have same meanings as with regexec_flags() */
2741 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2748 struct regexp *const prog = ReANY(rx);
2750 if (flags & REXEC_COPY_STR) {
2753 DEBUG_C(Perl_re_printf( aTHX_
2754 "Copy on write: regexp capture, type %d\n",
2756 /* Create a new COW SV to share the match string and store
2757 * in saved_copy, unless the current COW SV in saved_copy
2758 * is valid and suitable for our purpose */
2759 if (( prog->saved_copy
2760 && SvIsCOW(prog->saved_copy)
2761 && SvPOKp(prog->saved_copy)
2764 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2766 /* just reuse saved_copy SV */
2767 if (RXp_MATCH_COPIED(prog)) {
2768 Safefree(prog->subbeg);
2769 RXp_MATCH_COPIED_off(prog);
2773 /* create new COW SV to share string */
2774 RXp_MATCH_COPY_FREE(prog);
2775 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2777 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2778 assert (SvPOKp(prog->saved_copy));
2779 prog->sublen = strend - strbeg;
2780 prog->suboffset = 0;
2781 prog->subcoffset = 0;
2786 SSize_t max = strend - strbeg;
2789 if ( (flags & REXEC_COPY_SKIP_POST)
2790 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2791 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2792 ) { /* don't copy $' part of string */
2795 /* calculate the right-most part of the string covered
2796 * by a capture. Due to lookahead, this may be to
2797 * the right of $&, so we have to scan all captures */
2798 while (n <= prog->lastparen) {
2799 if (prog->offs[n].end > max)
2800 max = prog->offs[n].end;
2804 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2805 ? prog->offs[0].start
2807 assert(max >= 0 && max <= strend - strbeg);
2810 if ( (flags & REXEC_COPY_SKIP_PRE)
2811 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2812 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2813 ) { /* don't copy $` part of string */
2816 /* calculate the left-most part of the string covered
2817 * by a capture. Due to lookbehind, this may be to
2818 * the left of $&, so we have to scan all captures */
2819 while (min && n <= prog->lastparen) {
2820 if ( prog->offs[n].start != -1
2821 && prog->offs[n].start < min)
2823 min = prog->offs[n].start;
2827 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2828 && min > prog->offs[0].end
2830 min = prog->offs[0].end;
2834 assert(min >= 0 && min <= max && min <= strend - strbeg);
2837 if (RXp_MATCH_COPIED(prog)) {
2838 if (sublen > prog->sublen)
2840 (char*)saferealloc(prog->subbeg, sublen+1);
2843 prog->subbeg = (char*)safemalloc(sublen+1);
2844 Copy(strbeg + min, prog->subbeg, sublen, char);
2845 prog->subbeg[sublen] = '\0';
2846 prog->suboffset = min;
2847 prog->sublen = sublen;
2848 RXp_MATCH_COPIED_on(prog);
2850 prog->subcoffset = prog->suboffset;
2851 if (prog->suboffset && utf8_target) {
2852 /* Convert byte offset to chars.
2853 * XXX ideally should only compute this if @-/@+
2854 * has been seen, a la PL_sawampersand ??? */
2856 /* If there's a direct correspondence between the
2857 * string which we're matching and the original SV,
2858 * then we can use the utf8 len cache associated with
2859 * the SV. In particular, it means that under //g,
2860 * sv_pos_b2u() will use the previously cached
2861 * position to speed up working out the new length of
2862 * subcoffset, rather than counting from the start of
2863 * the string each time. This stops
2864 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2865 * from going quadratic */
2866 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2867 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2868 SV_GMAGIC|SV_CONST_RETURN);
2870 prog->subcoffset = utf8_length((U8*)strbeg,
2871 (U8*)(strbeg+prog->suboffset));
2875 RXp_MATCH_COPY_FREE(prog);
2876 prog->subbeg = strbeg;
2877 prog->suboffset = 0;
2878 prog->subcoffset = 0;
2879 prog->sublen = strend - strbeg;
2887 - regexec_flags - match a regexp against a string
2890 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2891 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2892 /* stringarg: the point in the string at which to begin matching */
2893 /* strend: pointer to null at end of string */
2894 /* strbeg: real beginning of string */
2895 /* minend: end of match must be >= minend bytes after stringarg. */
2896 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2897 * itself is accessed via the pointers above */
2898 /* data: May be used for some additional optimizations.
2899 Currently unused. */
2900 /* flags: For optimizations. See REXEC_* in regexp.h */
2903 struct regexp *const prog = ReANY(rx);
2907 SSize_t minlen; /* must match at least this many chars */
2908 SSize_t dontbother = 0; /* how many characters not to try at end */
2909 const bool utf8_target = cBOOL(DO_UTF8(sv));
2911 RXi_GET_DECL(prog,progi);
2912 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2913 regmatch_info *const reginfo = ®info_buf;
2914 regexp_paren_pair *swap = NULL;
2916 GET_RE_DEBUG_FLAGS_DECL;
2918 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2919 PERL_UNUSED_ARG(data);
2921 /* Be paranoid... */
2923 Perl_croak(aTHX_ "NULL regexp parameter");
2927 debug_start_match(rx, utf8_target, stringarg, strend,
2931 startpos = stringarg;
2933 /* set these early as they may be used by the HOP macros below */
2934 reginfo->strbeg = strbeg;
2935 reginfo->strend = strend;
2936 reginfo->is_utf8_target = cBOOL(utf8_target);
2938 if (prog->intflags & PREGf_GPOS_SEEN) {
2941 /* set reginfo->ganch, the position where \G can match */
2944 (flags & REXEC_IGNOREPOS)
2945 ? stringarg /* use start pos rather than pos() */
2946 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2947 /* Defined pos(): */
2948 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2949 : strbeg; /* pos() not defined; use start of string */
2951 DEBUG_GPOS_r(Perl_re_printf( aTHX_
2952 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
2954 /* in the presence of \G, we may need to start looking earlier in
2955 * the string than the suggested start point of stringarg:
2956 * if prog->gofs is set, then that's a known, fixed minimum
2959 * /ab|c\G/: gofs = 1
2960 * or if the minimum offset isn't known, then we have to go back
2961 * to the start of the string, e.g. /w+\G/
2964 if (prog->intflags & PREGf_ANCH_GPOS) {
2966 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2968 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2970 DEBUG_r(Perl_re_printf( aTHX_
2971 "fail: ganch-gofs before earliest possible start\n"));
2976 startpos = reginfo->ganch;
2978 else if (prog->gofs) {
2979 startpos = HOPBACKc(startpos, prog->gofs);
2983 else if (prog->intflags & PREGf_GPOS_FLOAT)
2987 minlen = prog->minlen;
2988 if ((startpos + minlen) > strend || startpos < strbeg) {
2989 DEBUG_r(Perl_re_printf( aTHX_
2990 "Regex match can't succeed, so not even tried\n"));
2994 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2995 * which will call destuctors to reset PL_regmatch_state, free higher
2996 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2997 * regmatch_info_aux_eval */
2999 oldsave = PL_savestack_ix;
3003 if ((prog->extflags & RXf_USE_INTUIT)
3004 && !(flags & REXEC_CHECKED))
3006 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3011 if (prog->extflags & RXf_CHECK_ALL) {
3012 /* we can match based purely on the result of INTUIT.
3013 * Set up captures etc just for $& and $-[0]
3014 * (an intuit-only match wont have $1,$2,..) */
3015 assert(!prog->nparens);
3017 /* s/// doesn't like it if $& is earlier than where we asked it to
3018 * start searching (which can happen on something like /.\G/) */
3019 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3022 /* this should only be possible under \G */
3023 assert(prog->intflags & PREGf_GPOS_SEEN);
3024 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3025 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3029 /* match via INTUIT shouldn't have any captures.
3030 * Let @-, @+, $^N know */
3031 prog->lastparen = prog->lastcloseparen = 0;
3032 RXp_MATCH_UTF8_set(prog, utf8_target);
3033 prog->offs[0].start = s - strbeg;
3034 prog->offs[0].end = utf8_target
3035 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3036 : s - strbeg + prog->minlenret;
3037 if ( !(flags & REXEC_NOT_FIRST) )
3038 S_reg_set_capture_string(aTHX_ rx,
3040 sv, flags, utf8_target);
3046 multiline = prog->extflags & RXf_PMf_MULTILINE;
3048 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3049 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3050 "String too short [regexec_flags]...\n"));
3054 /* Check validity of program. */
3055 if (UCHARAT(progi->program) != REG_MAGIC) {
3056 Perl_croak(aTHX_ "corrupted regexp program");
3059 RXp_MATCH_TAINTED_off(prog);
3060 RXp_MATCH_UTF8_set(prog, utf8_target);
3062 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3063 reginfo->intuit = 0;
3064 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3065 reginfo->warned = FALSE;
3067 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3068 /* see how far we have to get to not match where we matched before */
3069 reginfo->till = stringarg + minend;
3071 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3072 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3073 S_cleanup_regmatch_info_aux has executed (registered by
3074 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3075 magic belonging to this SV.
3076 Not newSVsv, either, as it does not COW.
3078 reginfo->sv = newSV(0);
3079 SvSetSV_nosteal(reginfo->sv, sv);
3080 SAVEFREESV(reginfo->sv);
3083 /* reserve next 2 or 3 slots in PL_regmatch_state:
3084 * slot N+0: may currently be in use: skip it
3085 * slot N+1: use for regmatch_info_aux struct
3086 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3087 * slot N+3: ready for use by regmatch()
3091 regmatch_state *old_regmatch_state;
3092 regmatch_slab *old_regmatch_slab;
3093 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3095 /* on first ever match, allocate first slab */
3096 if (!PL_regmatch_slab) {
3097 Newx(PL_regmatch_slab, 1, regmatch_slab);
3098 PL_regmatch_slab->prev = NULL;
3099 PL_regmatch_slab->next = NULL;
3100 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3103 old_regmatch_state = PL_regmatch_state;
3104 old_regmatch_slab = PL_regmatch_slab;
3106 for (i=0; i <= max; i++) {
3108 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3110 reginfo->info_aux_eval =
3111 reginfo->info_aux->info_aux_eval =
3112 &(PL_regmatch_state->u.info_aux_eval);
3114 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3115 PL_regmatch_state = S_push_slab(aTHX);
3118 /* note initial PL_regmatch_state position; at end of match we'll
3119 * pop back to there and free any higher slabs */
3121 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3122 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3123 reginfo->info_aux->poscache = NULL;
3125 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3127 if ((prog->extflags & RXf_EVAL_SEEN))
3128 S_setup_eval_state(aTHX_ reginfo);
3130 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3133 /* If there is a "must appear" string, look for it. */
3135 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3136 /* We have to be careful. If the previous successful match
3137 was from this regex we don't want a subsequent partially
3138 successful match to clobber the old results.
3139 So when we detect this possibility we add a swap buffer
3140 to the re, and switch the buffer each match. If we fail,
3141 we switch it back; otherwise we leave it swapped.
3144 /* do we need a save destructor here for eval dies? */
3145 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3146 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3147 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3155 if (prog->recurse_locinput)
3156 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3158 /* Simplest case: anchored match need be tried only once, or with
3159 * MBOL, only at the beginning of each line.
3161 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3162 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3163 * match at the start of the string then it won't match anywhere else
3164 * either; while with /.*.../, if it doesn't match at the beginning,
3165 * the earliest it could match is at the start of the next line */
3167 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3170 if (regtry(reginfo, &s))
3173 if (!(prog->intflags & PREGf_ANCH_MBOL))
3176 /* didn't match at start, try at other newline positions */
3179 dontbother = minlen - 1;
3180 end = HOP3c(strend, -dontbother, strbeg) - 1;
3182 /* skip to next newline */
3184 while (s <= end) { /* note it could be possible to match at the end of the string */
3185 /* NB: newlines are the same in unicode as they are in latin */
3188 if (prog->check_substr || prog->check_utf8) {
3189 /* note that with PREGf_IMPLICIT, intuit can only fail
3190 * or return the start position, so it's of limited utility.
3191 * Nevertheless, I made the decision that the potential for
3192 * quick fail was still worth it - DAPM */
3193 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3197 if (regtry(reginfo, &s))
3201 } /* end anchored search */
3203 if (prog->intflags & PREGf_ANCH_GPOS)
3205 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3206 assert(prog->intflags & PREGf_GPOS_SEEN);
3207 /* For anchored \G, the only position it can match from is
3208 * (ganch-gofs); we already set startpos to this above; if intuit
3209 * moved us on from there, we can't possibly succeed */
3210 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3211 if (s == startpos && regtry(reginfo, &s))
3216 /* Messy cases: unanchored match. */
3217 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3218 /* we have /x+whatever/ */
3219 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3225 if (! prog->anchored_utf8) {
3226 to_utf8_substr(prog);
3228 ch = SvPVX_const(prog->anchored_utf8)[0];
3231 DEBUG_EXECUTE_r( did_match = 1 );
3232 if (regtry(reginfo, &s)) goto got_it;
3234 while (s < strend && *s == ch)
3241 if (! prog->anchored_substr) {
3242 if (! to_byte_substr(prog)) {
3243 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3246 ch = SvPVX_const(prog->anchored_substr)[0];
3249 DEBUG_EXECUTE_r( did_match = 1 );
3250 if (regtry(reginfo, &s)) goto got_it;
3252 while (s < strend && *s == ch)
3257 DEBUG_EXECUTE_r(if (!did_match)
3258 Perl_re_printf( aTHX_
3259 "Did not find anchored character...\n")
3262 else if (prog->anchored_substr != NULL
3263 || prog->anchored_utf8 != NULL
3264 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3265 && prog->float_max_offset < strend - s)) {
3270 char *last1; /* Last position checked before */
3274 if (prog->anchored_substr || prog->anchored_utf8) {
3276 if (! prog->anchored_utf8) {
3277 to_utf8_substr(prog);
3279 must = prog->anchored_utf8;
3282 if (! prog->anchored_substr) {
3283 if (! to_byte_substr(prog)) {
3284 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3287 must = prog->anchored_substr;
3289 back_max = back_min = prog->anchored_offset;
3292 if (! prog->float_utf8) {
3293 to_utf8_substr(prog);
3295 must = prog->float_utf8;
3298 if (! prog->float_substr) {
3299 if (! to_byte_substr(prog)) {
3300 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3303 must = prog->float_substr;
3305 back_max = prog->float_max_offset;
3306 back_min = prog->float_min_offset;
3312 last = HOP3c(strend, /* Cannot start after this */
3313 -(SSize_t)(CHR_SVLEN(must)
3314 - (SvTAIL(must) != 0) + back_min), strbeg);
3316 if (s > reginfo->strbeg)
3317 last1 = HOPc(s, -1);
3319 last1 = s - 1; /* bogus */
3321 /* XXXX check_substr already used to find "s", can optimize if
3322 check_substr==must. */
3324 strend = HOPc(strend, -dontbother);
3325 while ( (s <= last) &&
3326 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3327 (unsigned char*)strend, must,
3328 multiline ? FBMrf_MULTILINE : 0)) ) {
3329 DEBUG_EXECUTE_r( did_match = 1 );
3330 if (HOPc(s, -back_max) > last1) {
3331 last1 = HOPc(s, -back_min);
3332 s = HOPc(s, -back_max);
3335 char * const t = (last1 >= reginfo->strbeg)
3336 ? HOPc(last1, 1) : last1 + 1;
3338 last1 = HOPc(s, -back_min);
3342 while (s <= last1) {
3343 if (regtry(reginfo, &s))
3346 s++; /* to break out of outer loop */
3353 while (s <= last1) {
3354 if (regtry(reginfo, &s))
3360 DEBUG_EXECUTE_r(if (!did_match) {
3361 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3362 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3363 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3364 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3365 ? "anchored" : "floating"),
3366 quoted, RE_SV_TAIL(must));
3370 else if ( (c = progi->regstclass) ) {
3372 const OPCODE op = OP(progi->regstclass);
3373 /* don't bother with what can't match */
3374 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3375 strend = HOPc(strend, -(minlen - 1));
3378 SV * const prop = sv_newmortal();
3379 regprop(prog, prop, c, reginfo, NULL);
3381 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3383 Perl_re_printf( aTHX_
3384 "Matching stclass %.*s against %s (%d bytes)\n",
3385 (int)SvCUR(prop), SvPVX_const(prop),
3386 quoted, (int)(strend - s));
3389 if (find_byclass(prog, c, s, strend, reginfo))
3391 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3395 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3403 if (! prog->float_utf8) {
3404 to_utf8_substr(prog);
3406 float_real = prog->float_utf8;
3409 if (! prog->float_substr) {
3410 if (! to_byte_substr(prog)) {
3411 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3414 float_real = prog->float_substr;
3417 little = SvPV_const(float_real, len);
3418 if (SvTAIL(float_real)) {
3419 /* This means that float_real contains an artificial \n on
3420 * the end due to the presence of something like this:
3421 * /foo$/ where we can match both "foo" and "foo\n" at the
3422 * end of the string. So we have to compare the end of the
3423 * string first against the float_real without the \n and
3424 * then against the full float_real with the string. We
3425 * have to watch out for cases where the string might be
3426 * smaller than the float_real or the float_real without
3428 char *checkpos= strend - len;
3430 Perl_re_printf( aTHX_
3431 "%sChecking for float_real.%s\n",
3432 PL_colors[4], PL_colors[5]));
3433 if (checkpos + 1 < strbeg) {
3434 /* can't match, even if we remove the trailing \n
3435 * string is too short to match */
3437 Perl_re_printf( aTHX_
3438 "%sString shorter than required trailing substring, cannot match.%s\n",
3439 PL_colors[4], PL_colors[5]));
3441 } else if (memEQ(checkpos + 1, little, len - 1)) {
3442 /* can match, the end of the string matches without the
3444 last = checkpos + 1;
3445 } else if (checkpos < strbeg) {
3446 /* cant match, string is too short when the "\n" is
3449 Perl_re_printf( aTHX_
3450 "%sString does not contain required trailing substring, cannot match.%s\n",
3451 PL_colors[4], PL_colors[5]));
3453 } else if (!multiline) {
3454 /* non multiline match, so compare with the "\n" at the
3455 * end of the string */
3456 if (memEQ(checkpos, little, len)) {
3460 Perl_re_printf( aTHX_
3461 "%sString does not contain required trailing substring, cannot match.%s\n",
3462 PL_colors[4], PL_colors[5]));
3466 /* multiline match, so we have to search for a place
3467 * where the full string is located */
3473 last = rninstr(s, strend, little, little + len);
3475 last = strend; /* matching "$" */
3478 /* at one point this block contained a comment which was
3479 * probably incorrect, which said that this was a "should not
3480 * happen" case. Even if it was true when it was written I am
3481 * pretty sure it is not anymore, so I have removed the comment
3482 * and replaced it with this one. Yves */
3484 Perl_re_printf( aTHX_
3485 "%sString does not contain required substring, cannot match.%s\n",
3486 PL_colors[4], PL_colors[5]
3490 dontbother = strend - last + prog->float_min_offset;
3492 if (minlen && (dontbother < minlen))
3493 dontbother = minlen - 1;
3494 strend -= dontbother; /* this one's always in bytes! */
3495 /* We don't know much -- general case. */
3498 if (regtry(reginfo, &s))
3507 if (regtry(reginfo, &s))
3509 } while (s++ < strend);
3517 /* s/// doesn't like it if $& is earlier than where we asked it to
3518 * start searching (which can happen on something like /.\G/) */
3519 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3520 && (prog->offs[0].start < stringarg - strbeg))
3522 /* this should only be possible under \G */
3523 assert(prog->intflags & PREGf_GPOS_SEEN);
3524 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3525 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3531 Perl_re_exec_indentf( aTHX_
3532 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3540 /* clean up; this will trigger destructors that will free all slabs
3541 * above the current one, and cleanup the regmatch_info_aux
3542 * and regmatch_info_aux_eval sructs */
3544 LEAVE_SCOPE(oldsave);
3546 if (RXp_PAREN_NAMES(prog))
3547 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3549 /* make sure $`, $&, $', and $digit will work later */
3550 if ( !(flags & REXEC_NOT_FIRST) )
3551 S_reg_set_capture_string(aTHX_ rx,
3552 strbeg, reginfo->strend,
3553 sv, flags, utf8_target);
3558 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3559 PL_colors[4], PL_colors[5]));
3561 /* clean up; this will trigger destructors that will free all slabs
3562 * above the current one, and cleanup the regmatch_info_aux
3563 * and regmatch_info_aux_eval sructs */
3565 LEAVE_SCOPE(oldsave);
3568 /* we failed :-( roll it back */
3569 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3570 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3576 Safefree(prog->offs);
3583 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3584 * Do inc before dec, in case old and new rex are the same */
3585 #define SET_reg_curpm(Re2) \
3586 if (reginfo->info_aux_eval) { \
3587 (void)ReREFCNT_inc(Re2); \
3588 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3589 PM_SETRE((PL_reg_curpm), (Re2)); \
3594 - regtry - try match at specific point
3596 STATIC bool /* 0 failure, 1 success */
3597 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3600 REGEXP *const rx = reginfo->prog;
3601 regexp *const prog = ReANY(rx);
3604 U32 depth = 0; /* used by REGCP_SET */
3606 RXi_GET_DECL(prog,progi);
3607 GET_RE_DEBUG_FLAGS_DECL;
3609 PERL_ARGS_ASSERT_REGTRY;
3611 reginfo->cutpoint=NULL;
3613 prog->offs[0].start = *startposp - reginfo->strbeg;
3614 prog->lastparen = 0;
3615 prog->lastcloseparen = 0;
3617 /* XXXX What this code is doing here?!!! There should be no need
3618 to do this again and again, prog->lastparen should take care of
3621 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3622 * Actually, the code in regcppop() (which Ilya may be meaning by
3623 * prog->lastparen), is not needed at all by the test suite
3624 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3625 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3626 * Meanwhile, this code *is* needed for the
3627 * above-mentioned test suite tests to succeed. The common theme
3628 * on those tests seems to be returning null fields from matches.
3629 * --jhi updated by dapm */
3631 /* After encountering a variant of the issue mentioned above I think
3632 * the point Ilya was making is that if we properly unwind whenever
3633 * we set lastparen to a smaller value then we should not need to do
3634 * this every time, only when needed. So if we have tests that fail if
3635 * we remove this, then it suggests somewhere else we are improperly
3636 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3637 * places it is called, and related regcp() routines. - Yves */
3639 if (prog->nparens) {
3640 regexp_paren_pair *pp = prog->offs;
3642 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3650 result = regmatch(reginfo, *startposp, progi->program + 1);
3652 prog->offs[0].end = result;
3655 if (reginfo->cutpoint)
3656 *startposp= reginfo->cutpoint;
3657 REGCP_UNWIND(lastcp);
3662 #define sayYES goto yes
3663 #define sayNO goto no
3664 #define sayNO_SILENT goto no_silent
3666 /* we dont use STMT_START/END here because it leads to
3667 "unreachable code" warnings, which are bogus, but distracting. */
3668 #define CACHEsayNO \
3669 if (ST.cache_mask) \
3670 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3673 /* this is used to determine how far from the left messages like
3674 'failed...' are printed in regexec.c. It should be set such that
3675 messages are inline with the regop output that created them.
3677 #define REPORT_CODE_OFF 29
3678 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3681 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3685 PerlIO *f= Perl_debug_log;
3686 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3687 va_start(ap, depth);
3688 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3689 result = PerlIO_vprintf(f, fmt, ap);
3693 #endif /* DEBUGGING */
3696 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3697 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3698 #define CHRTEST_NOT_A_CP_1 -999
3699 #define CHRTEST_NOT_A_CP_2 -998
3701 /* grab a new slab and return the first slot in it */
3703 STATIC regmatch_state *
3706 regmatch_slab *s = PL_regmatch_slab->next;
3708 Newx(s, 1, regmatch_slab);
3709 s->prev = PL_regmatch_slab;
3711 PL_regmatch_slab->next = s;
3713 PL_regmatch_slab = s;
3714 return SLAB_FIRST(s);
3718 /* push a new state then goto it */
3720 #define PUSH_STATE_GOTO(state, node, input) \
3721 pushinput = input; \
3723 st->resume_state = state; \
3726 /* push a new state with success backtracking, then goto it */
3728 #define PUSH_YES_STATE_GOTO(state, node, input) \
3729 pushinput = input; \
3731 st->resume_state = state; \
3732 goto push_yes_state;
3739 regmatch() - main matching routine
3741 This is basically one big switch statement in a loop. We execute an op,
3742 set 'next' to point the next op, and continue. If we come to a point which
3743 we may need to backtrack to on failure such as (A|B|C), we push a
3744 backtrack state onto the backtrack stack. On failure, we pop the top
3745 state, and re-enter the loop at the state indicated. If there are no more
3746 states to pop, we return failure.
3748 Sometimes we also need to backtrack on success; for example /A+/, where
3749 after successfully matching one A, we need to go back and try to
3750 match another one; similarly for lookahead assertions: if the assertion
3751 completes successfully, we backtrack to the state just before the assertion
3752 and then carry on. In these cases, the pushed state is marked as
3753 'backtrack on success too'. This marking is in fact done by a chain of
3754 pointers, each pointing to the previous 'yes' state. On success, we pop to
3755 the nearest yes state, discarding any intermediate failure-only states.
3756 Sometimes a yes state is pushed just to force some cleanup code to be
3757 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3758 it to free the inner regex.
3760 Note that failure backtracking rewinds the cursor position, while
3761 success backtracking leaves it alone.
3763 A pattern is complete when the END op is executed, while a subpattern
3764 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3765 ops trigger the "pop to last yes state if any, otherwise return true"
3768 A common convention in this function is to use A and B to refer to the two
3769 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3770 the subpattern to be matched possibly multiple times, while B is the entire
3771 rest of the pattern. Variable and state names reflect this convention.
3773 The states in the main switch are the union of ops and failure/success of
3774 substates associated with with that op. For example, IFMATCH is the op
3775 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3776 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3777 successfully matched A and IFMATCH_A_fail is a state saying that we have
3778 just failed to match A. Resume states always come in pairs. The backtrack
3779 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3780 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3781 on success or failure.
3783 The struct that holds a backtracking state is actually a big union, with
3784 one variant for each major type of op. The variable st points to the
3785 top-most backtrack struct. To make the code clearer, within each
3786 block of code we #define ST to alias the relevant union.
3788 Here's a concrete example of a (vastly oversimplified) IFMATCH
3794 #define ST st->u.ifmatch
3796 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3797 ST.foo = ...; // some state we wish to save
3799 // push a yes backtrack state with a resume value of
3800 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3802 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3805 case IFMATCH_A: // we have successfully executed A; now continue with B
3807 bar = ST.foo; // do something with the preserved value
3810 case IFMATCH_A_fail: // A failed, so the assertion failed
3811 ...; // do some housekeeping, then ...
3812 sayNO; // propagate the failure
3819 For any old-timers reading this who are familiar with the old recursive
3820 approach, the code above is equivalent to:
3822 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3831 ...; // do some housekeeping, then ...
3832 sayNO; // propagate the failure
3835 The topmost backtrack state, pointed to by st, is usually free. If you
3836 want to claim it, populate any ST.foo fields in it with values you wish to
3837 save, then do one of
3839 PUSH_STATE_GOTO(resume_state, node, newinput);
3840 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3842 which sets that backtrack state's resume value to 'resume_state', pushes a
3843 new free entry to the top of the backtrack stack, then goes to 'node'.
3844 On backtracking, the free slot is popped, and the saved state becomes the
3845 new free state. An ST.foo field in this new top state can be temporarily
3846 accessed to retrieve values, but once the main loop is re-entered, it
3847 becomes available for reuse.
3849 Note that the depth of the backtrack stack constantly increases during the
3850 left-to-right execution of the pattern, rather than going up and down with
3851 the pattern nesting. For example the stack is at its maximum at Z at the
3852 end of the pattern, rather than at X in the following:
3854 /(((X)+)+)+....(Y)+....Z/
3856 The only exceptions to this are lookahead/behind assertions and the cut,
3857 (?>A), which pop all the backtrack states associated with A before
3860 Backtrack state structs are allocated in slabs of about 4K in size.
3861 PL_regmatch_state and st always point to the currently active state,
3862 and PL_regmatch_slab points to the slab currently containing
3863 PL_regmatch_state. The first time regmatch() is called, the first slab is
3864 allocated, and is never freed until interpreter destruction. When the slab
3865 is full, a new one is allocated and chained to the end. At exit from
3866 regmatch(), slabs allocated since entry are freed.
3871 #define DEBUG_STATE_pp(pp) \
3873 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
3874 Perl_re_printf( aTHX_ \
3875 "%*s" pp " %s%s%s%s%s\n", \
3876 INDENT_CHARS(depth), "", \
3877 PL_reg_name[st->resume_state], \
3878 ((st==yes_state||st==mark_state) ? "[" : ""), \
3879 ((st==yes_state) ? "Y" : ""), \
3880 ((st==mark_state) ? "M" : ""), \
3881 ((st==yes_state||st==mark_state) ? "]" : "") \
3886 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3891 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3892 const char *start, const char *end, const char *blurb)
3894 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3896 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3901 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3902 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3904 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3905 start, end - start, 60);
3907 Perl_re_printf( aTHX_
3908 "%s%s REx%s %s against %s\n",
3909 PL_colors[4], blurb, PL_colors[5], s0, s1);
3911 if (utf8_target||utf8_pat)
3912 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
3913 utf8_pat ? "pattern" : "",
3914 utf8_pat && utf8_target ? " and " : "",
3915 utf8_target ? "string" : ""
3921 S_dump_exec_pos(pTHX_ const char *locinput,
3922 const regnode *scan,
3923 const char *loc_regeol,
3924 const char *loc_bostr,
3925 const char *loc_reg_starttry,
3926 const bool utf8_target,
3930 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3931 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3932 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3933 /* The part of the string before starttry has one color
3934 (pref0_len chars), between starttry and current
3935 position another one (pref_len - pref0_len chars),
3936 after the current position the third one.
3937 We assume that pref0_len <= pref_len, otherwise we
3938 decrease pref0_len. */
3939 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3940 ? (5 + taill) - l : locinput - loc_bostr;
3943 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3945 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3947 pref0_len = pref_len - (locinput - loc_reg_starttry);
3948 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3949 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3950 ? (5 + taill) - pref_len : loc_regeol - locinput);
3951 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3955 if (pref0_len > pref_len)
3956 pref0_len = pref_len;
3958 const int is_uni = utf8_target ? 1 : 0;
3960 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3961 (locinput - pref_len),pref0_len, 60, 4, 5);
3963 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3964 (locinput - pref_len + pref0_len),
3965 pref_len - pref0_len, 60, 2, 3);
3967 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3968 locinput, loc_regeol - locinput, 10, 0, 1);
3970 const STRLEN tlen=len0+len1+len2;
3971 Perl_re_printf( aTHX_
3972 "%4" IVdf " <%.*s%.*s%s%.*s>%*s|%4u| ",
3973 (IV)(locinput - loc_bostr),
3976 (docolor ? "" : "> <"),
3978 (int)(tlen > 19 ? 0 : 19 - tlen),
3986 /* reg_check_named_buff_matched()
3987 * Checks to see if a named buffer has matched. The data array of
3988 * buffer numbers corresponding to the buffer is expected to reside
3989 * in the regexp->data->data array in the slot stored in the ARG() of
3990 * node involved. Note that this routine doesn't actually care about the
3991 * name, that information is not preserved from compilation to execution.
3992 * Returns the index of the leftmost defined buffer with the given name
3993 * or 0 if non of the buffers matched.
3996 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3999 RXi_GET_DECL(rex,rexi);
4000 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4001 I32 *nums=(I32*)SvPVX(sv_dat);
4003 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
4005 for ( n=0; n<SvIVX(sv_dat); n++ ) {
4006 if ((I32)rex->lastparen >= nums[n] &&
4007 rex->offs[nums[n]].end != -1)
4017 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
4018 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
4020 /* This function determines if there are one or two characters that match
4021 * the first character of the passed-in EXACTish node <text_node>, and if
4022 * so, returns them in the passed-in pointers.
4024 * If it determines that no possible character in the target string can
4025 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4026 * the first character in <text_node> requires UTF-8 to represent, and the
4027 * target string isn't in UTF-8.)
4029 * If there are more than two characters that could match the beginning of
4030 * <text_node>, or if more context is required to determine a match or not,
4031 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4033 * The motiviation behind this function is to allow the caller to set up
4034 * tight loops for matching. If <text_node> is of type EXACT, there is
4035 * only one possible character that can match its first character, and so
4036 * the situation is quite simple. But things get much more complicated if
4037 * folding is involved. It may be that the first character of an EXACTFish
4038 * node doesn't participate in any possible fold, e.g., punctuation, so it
4039 * can be matched only by itself. The vast majority of characters that are
4040 * in folds match just two things, their lower and upper-case equivalents.
4041 * But not all are like that; some have multiple possible matches, or match
4042 * sequences of more than one character. This function sorts all that out.
4044 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4045 * loop of trying to match A*, we know we can't exit where the thing
4046 * following it isn't a B. And something can't be a B unless it is the
4047 * beginning of B. By putting a quick test for that beginning in a tight
4048 * loop, we can rule out things that can't possibly be B without having to
4049 * break out of the loop, thus avoiding work. Similarly, if A is a single
4050 * character, we can make a tight loop matching A*, using the outputs of
4053 * If the target string to match isn't in UTF-8, and there aren't
4054 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4055 * the one or two possible octets (which are characters in this situation)
4056 * that can match. In all cases, if there is only one character that can
4057 * match, *<c1p> and *<c2p> will be identical.
4059 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4060 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4061 * can match the beginning of <text_node>. They should be declared with at
4062 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4063 * undefined what these contain.) If one or both of the buffers are
4064 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4065 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4066 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4067 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4068 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4070 const bool utf8_target = reginfo->is_utf8_target;
4072 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4073 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4074 bool use_chrtest_void = FALSE;
4075 const bool is_utf8_pat = reginfo->is_utf8_pat;
4077 /* Used when we have both utf8 input and utf8 output, to avoid converting
4078 * to/from code points */
4079 bool utf8_has_been_setup = FALSE;
4083 U8 *pat = (U8*)STRING(text_node);
4084 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4086 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4088 /* In an exact node, only one thing can be matched, that first
4089 * character. If both the pat and the target are UTF-8, we can just
4090 * copy the input to the output, avoiding finding the code point of
4095 else if (utf8_target) {
4096 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4097 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4098 utf8_has_been_setup = TRUE;
4101 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4104 else { /* an EXACTFish node */
4105 U8 *pat_end = pat + STR_LEN(text_node);
4107 /* An EXACTFL node has at least some characters unfolded, because what
4108 * they match is not known until now. So, now is the time to fold
4109 * the first few of them, as many as are needed to determine 'c1' and
4110 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4111 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4112 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4113 * need to fold as many characters as a single character can fold to,
4114 * so that later we can check if the first ones are such a multi-char
4115 * fold. But, in such a pattern only locale-problematic characters
4116 * aren't folded, so we can skip this completely if the first character
4117 * in the node isn't one of the tricky ones */
4118 if (OP(text_node) == EXACTFL) {
4120 if (! is_utf8_pat) {
4121 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4123 folded[0] = folded[1] = 's';
4125 pat_end = folded + 2;
4128 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4133 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4135 *(d++) = (U8) toFOLD_LC(*s);
4140 _toFOLD_utf8_flags(s,
4144 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4155 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4156 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4158 /* Multi-character folds require more context to sort out. Also
4159 * PL_utf8_foldclosures used below doesn't handle them, so have to
4160 * be handled outside this routine */
4161 use_chrtest_void = TRUE;
4163 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4164 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4166 /* Load the folds hash, if not already done */
4168 if (! PL_utf8_foldclosures) {
4169 _load_PL_utf8_foldclosures();
4172 /* The fold closures data structure is a hash with the keys
4173 * being the UTF-8 of every character that is folded to, like
4174 * 'k', and the values each an array of all code points that
4175 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4176 * Multi-character folds are not included */
4177 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4182 /* Not found in the hash, therefore there are no folds
4183 * containing it, so there is only a single character that
4187 else { /* Does participate in folds */
4188 AV* list = (AV*) *listp;
4189 if (av_tindex_skip_len_mg(list) != 1) {
4191 /* If there aren't exactly two folds to this, it is
4192 * outside the scope of this function */
4193 use_chrtest_void = TRUE;
4195 else { /* There are two. Get them */
4196 SV** c_p = av_fetch(list, 0, FALSE);
4198 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4202 c_p = av_fetch(list, 1, FALSE);
4204 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4208 /* Folds that cross the 255/256 boundary are forbidden
4209 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4210 * one is ASCIII. Since the pattern character is above
4211 * 255, and its only other match is below 256, the only
4212 * legal match will be to itself. We have thrown away
4213 * the original, so have to compute which is the one
4215 if ((c1 < 256) != (c2 < 256)) {
4216 if ((OP(text_node) == EXACTFL
4217 && ! IN_UTF8_CTYPE_LOCALE)
4218 || ((OP(text_node) == EXACTFA
4219 || OP(text_node) == EXACTFA_NO_TRIE)
4220 && (isASCII(c1) || isASCII(c2))))
4233 else /* Here, c1 is <= 255 */
4235 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4236 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4237 && ((OP(text_node) != EXACTFA
4238 && OP(text_node) != EXACTFA_NO_TRIE)
4241 /* Here, there could be something above Latin1 in the target
4242 * which folds to this character in the pattern. All such
4243 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4244 * than two characters involved in their folds, so are outside
4245 * the scope of this function */
4246 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4247 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4250 use_chrtest_void = TRUE;
4253 else { /* Here nothing above Latin1 can fold to the pattern
4255 switch (OP(text_node)) {
4257 case EXACTFL: /* /l rules */
4258 c2 = PL_fold_locale[c1];
4261 case EXACTF: /* This node only generated for non-utf8
4263 assert(! is_utf8_pat);
4264 if (! utf8_target) { /* /d rules */
4269 /* /u rules for all these. This happens to work for
4270 * EXACTFA as nothing in Latin1 folds to ASCII */
4271 case EXACTFA_NO_TRIE: /* This node only generated for
4272 non-utf8 patterns */
4273 assert(! is_utf8_pat);
4278 c2 = PL_fold_latin1[c1];
4282 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4283 NOT_REACHED; /* NOTREACHED */
4289 /* Here have figured things out. Set up the returns */
4290 if (use_chrtest_void) {
4291 *c2p = *c1p = CHRTEST_VOID;
4293 else if (utf8_target) {
4294 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4295 uvchr_to_utf8(c1_utf8, c1);
4296 uvchr_to_utf8(c2_utf8, c2);
4299 /* Invariants are stored in both the utf8 and byte outputs; Use
4300 * negative numbers otherwise for the byte ones. Make sure that the
4301 * byte ones are the same iff the utf8 ones are the same */
4302 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4303 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4306 ? CHRTEST_NOT_A_CP_1
4307 : CHRTEST_NOT_A_CP_2;
4309 else if (c1 > 255) {
4310 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4315 *c1p = *c2p = c2; /* c2 is the only representable value */
4317 else { /* c1 is representable; see about c2 */
4319 *c2p = (c2 < 256) ? c2 : c1;
4326 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4328 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4329 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4331 PERL_ARGS_ASSERT_ISGCB;
4333 switch (GCB_table[before][after]) {
4340 case GCB_RI_then_RI:
4343 U8 * temp_pos = (U8 *) curpos;
4345 /* Do not break within emoji flag sequences. That is, do not
4346 * break between regional indicator (RI) symbols if there is an
4347 * odd number of RI characters before the break point.
4348 * GB12 sot (RI RI)* RI × RI
4349 * GB13 [^RI] (RI RI)* RI × RI */
4351 while (backup_one_GCB(strbeg,
4353 utf8_target) == GCB_Regional_Indicator)
4358 return RI_count % 2 != 1;
4361 case GCB_EX_then_EM:
4363 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4365 U8 * temp_pos = (U8 *) curpos;
4369 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4371 while (prev == GCB_Extend);
4373 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4381 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4382 before, after, GCB_table[before][after]);
4389 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4393 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4395 if (*curpos < strbeg) {
4400 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4401 U8 * prev_prev_char_pos;
4403 if (! prev_char_pos) {
4407 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4408 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4409 *curpos = prev_char_pos;
4410 prev_char_pos = prev_prev_char_pos;
4413 *curpos = (U8 *) strbeg;
4418 if (*curpos - 2 < strbeg) {
4419 *curpos = (U8 *) strbeg;
4423 gcb = getGCB_VAL_CP(*(*curpos - 1));
4429 /* Combining marks attach to most classes that precede them, but this defines
4430 * the exceptions (from TR14) */
4431 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4432 || prev == LB_Mandatory_Break \
4433 || prev == LB_Carriage_Return \
4434 || prev == LB_Line_Feed \
4435 || prev == LB_Next_Line \
4436 || prev == LB_Space \
4437 || prev == LB_ZWSpace))
4440 S_isLB(pTHX_ LB_enum before,
4442 const U8 * const strbeg,
4443 const U8 * const curpos,
4444 const U8 * const strend,
4445 const bool utf8_target)
4447 U8 * temp_pos = (U8 *) curpos;
4448 LB_enum prev = before;
4450 /* Is the boundary between 'before' and 'after' line-breakable?
4451 * Most of this is just a table lookup of a generated table from Unicode
4452 * rules. But some rules require context to decide, and so have to be
4453 * implemented in code */
4455 PERL_ARGS_ASSERT_ISLB;
4457 /* Rule numbers in the comments below are as of Unicode 9.0 */
4461 switch (LB_table[before][after]) {
4466 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4469 case LB_SP_foo + LB_BREAKABLE:
4470 case LB_SP_foo + LB_NOBREAK:
4471 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4473 /* When we have something following a SP, we have to look at the
4474 * context in order to know what to do.
4476 * SP SP should not reach here because LB7: Do not break before
4477 * spaces. (For two spaces in a row there is nothing that
4478 * overrides that) */
4479 assert(after != LB_Space);
4481 /* Here we have a space followed by a non-space. Mostly this is a
4482 * case of LB18: "Break after spaces". But there are complications
4483 * as the handling of spaces is somewhat tricky. They are in a
4484 * number of rules, which have to be applied in priority order, but
4485 * something earlier in the string can cause a rule to be skipped
4486 * and a lower priority rule invoked. A prime example is LB7 which
4487 * says don't break before a space. But rule LB8 (lower priority)
4488 * says that the first break opportunity after a ZW is after any
4489 * span of spaces immediately after it. If a ZW comes before a SP
4490 * in the input, rule LB8 applies, and not LB7. Other such rules
4491 * involve combining marks which are rules 9 and 10, but they may
4492 * override higher priority rules if they come earlier in the
4493 * string. Since we're doing random access into the middle of the
4494 * string, we have to look for rules that should get applied based
4495 * on both string position and priority. Combining marks do not
4496 * attach to either ZW nor SP, so we don't have to consider them
4499 * To check for LB8, we have to find the first non-space character
4500 * before this span of spaces */
4502 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4504 while (prev == LB_Space);
4506 /* LB8 Break before any character following a zero-width space,
4507 * even if one or more spaces intervene.
4509 * So if we have a ZW just before this span, and to get here this
4510 * is the final space in the span. */
4511 if (prev == LB_ZWSpace) {
4515 /* Here, not ZW SP+. There are several rules that have higher
4516 * priority than LB18 and can be resolved now, as they don't depend
4517 * on anything earlier in the string (except ZW, which we have
4518 * already handled). One of these rules is LB11 Do not break
4519 * before Word joiner, but we have specially encoded that in the
4520 * lookup table so it is caught by the single test below which
4521 * catches the other ones. */
4522 if (LB_table[LB_Space][after] - LB_SP_foo
4523 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4528 /* If we get here, we have to XXX consider combining marks. */
4529 if (prev == LB_Combining_Mark) {
4531 /* What happens with these depends on the character they
4534 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4536 while (prev == LB_Combining_Mark);
4538 /* Most times these attach to and inherit the characteristics
4539 * of that character, but not always, and when not, they are to
4540 * be treated as AL by rule LB10. */
4541 if (! LB_CM_ATTACHES_TO(prev)) {
4542 prev = LB_Alphabetic;
4546 /* Here, we have the character preceding the span of spaces all set
4547 * up. We follow LB18: "Break after spaces" unless the table shows
4548 * that is overriden */
4549 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4553 /* We don't know how to treat the CM except by looking at the first
4554 * non-CM character preceding it. ZWJ is treated as CM */
4556 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4558 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4560 /* Here, 'prev' is that first earlier non-CM character. If the CM
4561 * attatches to it, then it inherits the behavior of 'prev'. If it
4562 * doesn't attach, it is to be treated as an AL */
4563 if (! LB_CM_ATTACHES_TO(prev)) {
4564 prev = LB_Alphabetic;
4569 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4570 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4572 /* LB21a Don't break after Hebrew + Hyphen.
4573 * HL (HY | BA) × */
4575 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4576 == LB_Hebrew_Letter)
4581 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4583 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4584 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4586 /* LB25a (PR | PO) × ( OP | HY )? NU */
4587 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4591 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4594 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4595 case LB_SY_or_IS_then_various + LB_NOBREAK:
4597 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4599 LB_enum temp = prev;
4601 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4603 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4604 if (temp == LB_Numeric) {
4608 return LB_table[prev][after] - LB_SY_or_IS_then_various
4612 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4613 case LB_various_then_PO_or_PR + LB_NOBREAK:
4615 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4617 LB_enum temp = prev;
4618 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4620 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4622 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4623 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4625 if (temp == LB_Numeric) {
4628 return LB_various_then_PO_or_PR;
4631 case LB_RI_then_RI + LB_NOBREAK:
4632 case LB_RI_then_RI + LB_BREAKABLE:
4636 /* LB30a Break between two regional indicator symbols if and
4637 * only if there are an even number of regional indicators
4638 * preceding the position of the break.
4640 * sot (RI RI)* RI × RI
4641 * [^RI] (RI RI)* RI × RI */
4643 while (backup_one_LB(strbeg,
4645 utf8_target) == LB_Regional_Indicator)
4650 return RI_count % 2 == 0;
4658 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4659 before, after, LB_table[before][after]);
4666 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4670 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4672 if (*curpos >= strend) {
4677 *curpos += UTF8SKIP(*curpos);
4678 if (*curpos >= strend) {
4681 lb = getLB_VAL_UTF8(*curpos, strend);
4685 if (*curpos >= strend) {
4688 lb = getLB_VAL_CP(**curpos);
4695 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4699 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4701 if (*curpos < strbeg) {
4706 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4707 U8 * prev_prev_char_pos;
4709 if (! prev_char_pos) {
4713 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4714 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4715 *curpos = prev_char_pos;
4716 prev_char_pos = prev_prev_char_pos;
4719 *curpos = (U8 *) strbeg;
4724 if (*curpos - 2 < strbeg) {
4725 *curpos = (U8 *) strbeg;
4729 lb = getLB_VAL_CP(*(*curpos - 1));
4736 S_isSB(pTHX_ SB_enum before,
4738 const U8 * const strbeg,
4739 const U8 * const curpos,
4740 const U8 * const strend,
4741 const bool utf8_target)
4743 /* returns a boolean indicating if there is a Sentence Boundary Break
4744 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4746 U8 * lpos = (U8 *) curpos;
4747 bool has_para_sep = FALSE;
4748 bool has_sp = FALSE;
4750 PERL_ARGS_ASSERT_ISSB;
4752 /* Break at the start and end of text.
4755 But unstated in Unicode is don't break if the text is empty */
4756 if (before == SB_EDGE || after == SB_EDGE) {
4757 return before != after;
4760 /* SB 3: Do not break within CRLF. */
4761 if (before == SB_CR && after == SB_LF) {
4765 /* Break after paragraph separators. CR and LF are considered
4766 * so because Unicode views text as like word processing text where there
4767 * are no newlines except between paragraphs, and the word processor takes
4768 * care of wrapping without there being hard line-breaks in the text *./
4769 SB4. Sep | CR | LF ÷ */
4770 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4774 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4775 * (See Section 6.2, Replacing Ignore Rules.)
4776 SB5. X (Extend | Format)* → X */
4777 if (after == SB_Extend || after == SB_Format) {
4779 /* Implied is that the these characters attach to everything
4780 * immediately prior to them except for those separator-type
4781 * characters. And the rules earlier have already handled the case
4782 * when one of those immediately precedes the extend char */
4786 if (before == SB_Extend || before == SB_Format) {
4787 U8 * temp_pos = lpos;
4788 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4789 if ( backup != SB_EDGE
4798 /* Here, both 'before' and 'backup' are these types; implied is that we
4799 * don't break between them */
4800 if (backup == SB_Extend || backup == SB_Format) {
4805 /* Do not break after ambiguous terminators like period, if they are
4806 * immediately followed by a number or lowercase letter, if they are
4807 * between uppercase letters, if the first following letter (optionally
4808 * after certain punctuation) is lowercase, or if they are followed by
4809 * "continuation" punctuation such as comma, colon, or semicolon. For
4810 * example, a period may be an abbreviation or numeric period, and thus may
4811 * not mark the end of a sentence.
4813 * SB6. ATerm × Numeric */
4814 if (before == SB_ATerm && after == SB_Numeric) {
4818 /* SB7. (Upper | Lower) ATerm × Upper */
4819 if (before == SB_ATerm && after == SB_Upper) {
4820 U8 * temp_pos = lpos;
4821 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4822 if (backup == SB_Upper || backup == SB_Lower) {
4827 /* The remaining rules that aren't the final one, all require an STerm or
4828 * an ATerm after having backed up over some Close* Sp*, and in one case an
4829 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4830 * So do that backup now, setting flags if either Sp or a paragraph
4831 * separator are found */
4833 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4834 has_para_sep = TRUE;
4835 before = backup_one_SB(strbeg, &lpos, utf8_target);
4838 if (before == SB_Sp) {
4841 before = backup_one_SB(strbeg, &lpos, utf8_target);
4843 while (before == SB_Sp);
4846 while (before == SB_Close) {
4847 before = backup_one_SB(strbeg, &lpos, utf8_target);
4850 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4851 * most cases an STerm */
4852 if (before == SB_STerm || before == SB_ATerm) {
4854 /* So, here the lhs matches
4855 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4856 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4857 * The rules that apply here are:
4859 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4860 | LF | STerm | ATerm) )* Lower
4861 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4862 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4863 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4864 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4867 /* And all but SB11 forbid having seen a paragraph separator */
4868 if (! has_para_sep) {
4869 if (before == SB_ATerm) { /* SB8 */
4870 U8 * rpos = (U8 *) curpos;
4871 SB_enum later = after;
4873 while ( later != SB_OLetter
4874 && later != SB_Upper
4875 && later != SB_Lower
4879 && later != SB_STerm
4880 && later != SB_ATerm
4881 && later != SB_EDGE)
4883 later = advance_one_SB(&rpos, strend, utf8_target);
4885 if (later == SB_Lower) {
4890 if ( after == SB_SContinue /* SB8a */
4891 || after == SB_STerm
4892 || after == SB_ATerm)
4897 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4898 if ( after == SB_Close
4908 /* SB10. This and SB9 could probably be combined some way, but khw
4909 * has decided to follow the Unicode rule book precisely for
4910 * simplified maintenance */
4924 /* Otherwise, do not break.
4931 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4935 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4937 if (*curpos >= strend) {
4943 *curpos += UTF8SKIP(*curpos);
4944 if (*curpos >= strend) {
4947 sb = getSB_VAL_UTF8(*curpos, strend);
4948 } while (sb == SB_Extend || sb == SB_Format);
4953 if (*curpos >= strend) {
4956 sb = getSB_VAL_CP(**curpos);
4957 } while (sb == SB_Extend || sb == SB_Format);
4964 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4968 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4970 if (*curpos < strbeg) {
4975 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4976 if (! prev_char_pos) {
4980 /* Back up over Extend and Format. curpos is always just to the right
4981 * of the characater whose value we are getting */
4983 U8 * prev_prev_char_pos;
4984 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4987 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4988 *curpos = prev_char_pos;
4989 prev_char_pos = prev_prev_char_pos;
4992 *curpos = (U8 *) strbeg;
4995 } while (sb == SB_Extend || sb == SB_Format);
4999 if (*curpos - 2 < strbeg) {
5000 *curpos = (U8 *) strbeg;
5004 sb = getSB_VAL_CP(*(*curpos - 1));
5005 } while (sb == SB_Extend || sb == SB_Format);
5012 S_isWB(pTHX_ WB_enum previous,
5015 const U8 * const strbeg,
5016 const U8 * const curpos,
5017 const U8 * const strend,
5018 const bool utf8_target)
5020 /* Return a boolean as to if the boundary between 'before' and 'after' is
5021 * a Unicode word break, using their published algorithm, but tailored for
5022 * Perl by treating spans of white space as one unit. Context may be
5023 * needed to make this determination. If the value for the character
5024 * before 'before' is known, it is passed as 'previous'; otherwise that
5025 * should be set to WB_UNKNOWN. The other input parameters give the
5026 * boundaries and current position in the matching of the string. That
5027 * is, 'curpos' marks the position where the character whose wb value is
5028 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5030 U8 * before_pos = (U8 *) curpos;
5031 U8 * after_pos = (U8 *) curpos;
5032 WB_enum prev = before;
5035 PERL_ARGS_ASSERT_ISWB;
5037 /* Rule numbers in the comments below are as of Unicode 9.0 */
5041 switch (WB_table[before][after]) {
5048 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5049 next = advance_one_WB(&after_pos, strend, utf8_target,
5050 FALSE /* Don't skip Extend nor Format */ );
5051 /* A space immediately preceeding an Extend or Format is attached
5052 * to by them, and hence gets separated from previous spaces.
5053 * Otherwise don't break between horizontal white space */
5054 return next == WB_Extend || next == WB_Format;
5056 /* WB4 Ignore Format and Extend characters, except when they appear at
5057 * the beginning of a region of text. This code currently isn't
5058 * general purpose, but it works as the rules are currently and likely
5059 * to be laid out. The reason it works is that when 'they appear at
5060 * the beginning of a region of text', the rule is to break before
5061 * them, just like any other character. Therefore, the default rule
5062 * applies and we don't have to look in more depth. Should this ever
5063 * change, we would have to have 2 'case' statements, like in the rules
5064 * below, and backup a single character (not spacing over the extend
5065 * ones) and then see if that is one of the region-end characters and
5067 case WB_Ex_or_FO_or_ZWJ_then_foo:
5068 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5071 case WB_DQ_then_HL + WB_BREAKABLE:
5072 case WB_DQ_then_HL + WB_NOBREAK:
5074 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5076 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5077 == WB_Hebrew_Letter)
5082 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5084 case WB_HL_then_DQ + WB_BREAKABLE:
5085 case WB_HL_then_DQ + WB_NOBREAK:
5087 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5089 if (advance_one_WB(&after_pos, strend, utf8_target,
5090 TRUE /* Do skip Extend and Format */ )
5091 == WB_Hebrew_Letter)
5096 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5098 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5099 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5101 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5102 * | Single_Quote) (ALetter | Hebrew_Letter) */
5104 next = advance_one_WB(&after_pos, strend, utf8_target,
5105 TRUE /* Do skip Extend and Format */ );
5107 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5112 return WB_table[before][after]
5113 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5115 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5116 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5118 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5119 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5121 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5122 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5127 return WB_table[before][after]
5128 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5130 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5131 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5133 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5136 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5142 return WB_table[before][after]
5143 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5145 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5146 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5148 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5150 if (advance_one_WB(&after_pos, strend, utf8_target,
5151 TRUE /* Do skip Extend and Format */ )
5157 return WB_table[before][after]
5158 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5160 case WB_RI_then_RI + WB_NOBREAK:
5161 case WB_RI_then_RI + WB_BREAKABLE:
5165 /* Do not break within emoji flag sequences. That is, do not
5166 * break between regional indicator (RI) symbols if there is an
5167 * odd number of RI characters before the potential break
5170 * WB15 sot (RI RI)* RI × RI
5171 * WB16 [^RI] (RI RI)* RI × RI */
5173 while (backup_one_WB(&previous,
5176 utf8_target) == WB_Regional_Indicator)
5181 return RI_count % 2 != 1;
5189 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5190 before, after, WB_table[before][after]);
5197 S_advance_one_WB(pTHX_ U8 ** curpos,
5198 const U8 * const strend,
5199 const bool utf8_target,
5200 const bool skip_Extend_Format)
5204 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5206 if (*curpos >= strend) {
5212 /* Advance over Extend and Format */
5214 *curpos += UTF8SKIP(*curpos);
5215 if (*curpos >= strend) {
5218 wb = getWB_VAL_UTF8(*curpos, strend);
5219 } while ( skip_Extend_Format
5220 && (wb == WB_Extend || wb == WB_Format));
5225 if (*curpos >= strend) {
5228 wb = getWB_VAL_CP(**curpos);
5229 } while ( skip_Extend_Format
5230 && (wb == WB_Extend || wb == WB_Format));
5237 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5241 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5243 /* If we know what the previous character's break value is, don't have
5245 if (*previous != WB_UNKNOWN) {
5248 /* But we need to move backwards by one */
5250 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5252 *previous = WB_EDGE;
5253 *curpos = (U8 *) strbeg;
5256 *previous = WB_UNKNOWN;
5261 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5264 /* And we always back up over these three types */
5265 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5270 if (*curpos < strbeg) {
5275 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5276 if (! prev_char_pos) {
5280 /* Back up over Extend and Format. curpos is always just to the right
5281 * of the characater whose value we are getting */
5283 U8 * prev_prev_char_pos;
5284 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5288 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5289 *curpos = prev_char_pos;
5290 prev_char_pos = prev_prev_char_pos;
5293 *curpos = (U8 *) strbeg;
5296 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5300 if (*curpos - 2 < strbeg) {
5301 *curpos = (U8 *) strbeg;
5305 wb = getWB_VAL_CP(*(*curpos - 1));
5306 } while (wb == WB_Extend || wb == WB_Format);
5312 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5315 ( ( st )->u.eval.close_paren ) && \
5316 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5319 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5322 ( ( st )->u.eval.close_paren ) && \
5324 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5328 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5329 (st)->u.eval.close_paren = ( (expr) + 1 )
5331 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5332 (st)->u.eval.close_paren = 0
5334 /* returns -1 on failure, $+[0] on success */
5336 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5339 const bool utf8_target = reginfo->is_utf8_target;
5340 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5341 REGEXP *rex_sv = reginfo->prog;
5342 regexp *rex = ReANY(rex_sv);
5343 RXi_GET_DECL(rex,rexi);
5344 /* the current state. This is a cached copy of PL_regmatch_state */
5346 /* cache heavy used fields of st in registers */
5349 U32 n = 0; /* general value; init to avoid compiler warning */
5350 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5351 SSize_t endref = 0; /* offset of end of backref when ln is start */
5352 char *locinput = startpos;
5353 char *pushinput; /* where to continue after a PUSH */
5354 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5356 bool result = 0; /* return value of S_regmatch */
5357 U32 depth = 0; /* depth of backtrack stack */
5358 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5359 const U32 max_nochange_depth =
5360 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5361 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5362 regmatch_state *yes_state = NULL; /* state to pop to on success of
5364 /* mark_state piggy backs on the yes_state logic so that when we unwind
5365 the stack on success we can update the mark_state as we go */
5366 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5367 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5368 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5370 bool no_final = 0; /* prevent failure from backtracking? */
5371 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5372 char *startpoint = locinput;
5373 SV *popmark = NULL; /* are we looking for a mark? */
5374 SV *sv_commit = NULL; /* last mark name seen in failure */
5375 SV *sv_yes_mark = NULL; /* last mark name we have seen
5376 during a successful match */
5377 U32 lastopen = 0; /* last open we saw */
5378 bool has_cutgroup = RXp_HAS_CUTGROUP(rex) ? 1 : 0;
5379 SV* const oreplsv = GvSVn(PL_replgv);
5380 /* these three flags are set by various ops to signal information to
5381 * the very next op. They have a useful lifetime of exactly one loop
5382 * iteration, and are not preserved or restored by state pushes/pops
5384 bool sw = 0; /* the condition value in (?(cond)a|b) */
5385 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5386 int logical = 0; /* the following EVAL is:
5390 or the following IFMATCH/UNLESSM is:
5391 false: plain (?=foo)
5392 true: used as a condition: (?(?=foo))
5394 PAD* last_pad = NULL;
5396 U8 gimme = G_SCALAR;
5397 CV *caller_cv = NULL; /* who called us */
5398 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5399 U32 maxopenparen = 0; /* max '(' index seen so far */
5400 int to_complement; /* Invert the result? */
5401 _char_class_number classnum;
5402 bool is_utf8_pat = reginfo->is_utf8_pat;
5404 I32 orig_savestack_ix = PL_savestack_ix;
5406 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5407 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5408 # define SOLARIS_BAD_OPTIMIZER
5409 const U32 *pl_charclass_dup = PL_charclass;
5410 # define PL_charclass pl_charclass_dup
5414 GET_RE_DEBUG_FLAGS_DECL;
5417 /* protect against undef(*^R) */
5418 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5420 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5421 multicall_oldcatch = 0;
5422 PERL_UNUSED_VAR(multicall_cop);
5424 PERL_ARGS_ASSERT_REGMATCH;
5426 st = PL_regmatch_state;
5428 /* Note that nextchr is a byte even in UTF */
5432 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5433 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5434 Perl_re_printf( aTHX_ "regmatch start\n" );
5437 while (scan != NULL) {
5440 next = scan + NEXT_OFF(scan);
5443 state_num = OP(scan);
5447 if (state_num <= REGNODE_MAX) {
5448 SV * const prop = sv_newmortal();
5449 regnode *rnext = regnext(scan);
5451 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5452 regprop(rex, prop, scan, reginfo, NULL);
5453 Perl_re_printf( aTHX_
5454 "%*s%" IVdf ":%s(%" IVdf ")\n",
5455 INDENT_CHARS(depth), "",
5456 (IV)(scan - rexi->program),
5458 (PL_regkind[OP(scan)] == END || !rnext) ?
5459 0 : (IV)(rnext - rexi->program));
5466 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5468 switch (state_num) {
5469 case SBOL: /* /^../ and /\A../ */
5470 if (locinput == reginfo->strbeg)
5474 case MBOL: /* /^../m */
5475 if (locinput == reginfo->strbeg ||
5476 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5483 if (locinput == reginfo->ganch)
5487 case KEEPS: /* \K */
5488 /* update the startpoint */
5489 st->u.keeper.val = rex->offs[0].start;
5490 rex->offs[0].start = locinput - reginfo->strbeg;
5491 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5492 NOT_REACHED; /* NOTREACHED */
5494 case KEEPS_next_fail:
5495 /* rollback the start point change */
5496 rex->offs[0].start = st->u.keeper.val;
5498 NOT_REACHED; /* NOTREACHED */
5500 case MEOL: /* /..$/m */
5501 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5505 case SEOL: /* /..$/ */
5506 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5508 if (reginfo->strend - locinput > 1)
5513 if (!NEXTCHR_IS_EOS)
5517 case SANY: /* /./s */
5520 goto increment_locinput;
5522 case REG_ANY: /* /./ */
5523 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5525 goto increment_locinput;
5529 #define ST st->u.trie
5530 case TRIEC: /* (ab|cd) with known charclass */
5531 /* In this case the charclass data is available inline so
5532 we can fail fast without a lot of extra overhead.
5534 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5536 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5537 depth, PL_colors[4], PL_colors[5])
5540 NOT_REACHED; /* NOTREACHED */
5543 case TRIE: /* (ab|cd) */
5544 /* the basic plan of execution of the trie is:
5545 * At the beginning, run though all the states, and
5546 * find the longest-matching word. Also remember the position
5547 * of the shortest matching word. For example, this pattern:
5550 * when matched against the string "abcde", will generate
5551 * accept states for all words except 3, with the longest
5552 * matching word being 4, and the shortest being 2 (with
5553 * the position being after char 1 of the string).
5555 * Then for each matching word, in word order (i.e. 1,2,4,5),
5556 * we run the remainder of the pattern; on each try setting
5557 * the current position to the character following the word,
5558 * returning to try the next word on failure.
5560 * We avoid having to build a list of words at runtime by
5561 * using a compile-time structure, wordinfo[].prev, which
5562 * gives, for each word, the previous accepting word (if any).
5563 * In the case above it would contain the mappings 1->2, 2->0,
5564 * 3->0, 4->5, 5->1. We can use this table to generate, from
5565 * the longest word (4 above), a list of all words, by
5566 * following the list of prev pointers; this gives us the
5567 * unordered list 4,5,1,2. Then given the current word we have
5568 * just tried, we can go through the list and find the
5569 * next-biggest word to try (so if we just failed on word 2,
5570 * the next in the list is 4).
5572 * Since at runtime we don't record the matching position in
5573 * the string for each word, we have to work that out for
5574 * each word we're about to process. The wordinfo table holds
5575 * the character length of each word; given that we recorded
5576 * at the start: the position of the shortest word and its
5577 * length in chars, we just need to move the pointer the
5578 * difference between the two char lengths. Depending on
5579 * Unicode status and folding, that's cheap or expensive.
5581 * This algorithm is optimised for the case where are only a
5582 * small number of accept states, i.e. 0,1, or maybe 2.
5583 * With lots of accepts states, and having to try all of them,
5584 * it becomes quadratic on number of accept states to find all
5589 /* what type of TRIE am I? (utf8 makes this contextual) */
5590 DECL_TRIE_TYPE(scan);
5592 /* what trie are we using right now */
5593 reg_trie_data * const trie
5594 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5595 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5596 U32 state = trie->startstate;
5598 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5599 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5601 && nextchr >= 0 /* guard against negative EOS value in nextchr */
5602 && UTF8_IS_ABOVE_LATIN1(nextchr)
5603 && scan->flags == EXACTL)
5605 /* We only output for EXACTL, as we let the folder
5606 * output this message for EXACTFLU8 to avoid
5608 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5613 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5615 if (trie->states[ state ].wordnum) {
5617 Perl_re_exec_indentf( aTHX_ "%smatched empty string...%s\n",
5618 depth, PL_colors[4], PL_colors[5])
5624 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5625 depth, PL_colors[4], PL_colors[5])
5632 U8 *uc = ( U8* )locinput;
5636 U8 *uscan = (U8*)NULL;
5637 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5638 U32 charcount = 0; /* how many input chars we have matched */
5639 U32 accepted = 0; /* have we seen any accepting states? */
5641 ST.jump = trie->jump;
5644 ST.longfold = FALSE; /* char longer if folded => it's harder */
5647 /* fully traverse the TRIE; note the position of the
5648 shortest accept state and the wordnum of the longest
5651 while ( state && uc <= (U8*)(reginfo->strend) ) {
5652 U32 base = trie->states[ state ].trans.base;
5656 wordnum = trie->states[ state ].wordnum;
5658 if (wordnum) { /* it's an accept state */
5661 /* record first match position */
5663 ST.firstpos = (U8*)locinput;
5668 ST.firstchars = charcount;
5671 if (!ST.nextword || wordnum < ST.nextword)
5672 ST.nextword = wordnum;
5673 ST.topword = wordnum;
5676 DEBUG_TRIE_EXECUTE_r({
5677 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
5679 PerlIO_printf( Perl_debug_log,
5680 "%*s%sState: %4" UVxf " Accepted: %c ",
5681 INDENT_CHARS(depth), "", PL_colors[4],
5682 (UV)state, (accepted ? 'Y' : 'N'));
5685 /* read a char and goto next state */
5686 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5688 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5689 uscan, len, uvc, charid, foldlen,
5696 base + charid - 1 - trie->uniquecharcount)) >= 0)
5698 && ((U32)offset < trie->lasttrans)
5699 && trie->trans[offset].check == state)
5701 state = trie->trans[offset].next;
5712 DEBUG_TRIE_EXECUTE_r(
5713 Perl_re_printf( aTHX_
5714 "Charid:%3x CP:%4" UVxf " After State: %4" UVxf "%s\n",
5715 charid, uvc, (UV)state, PL_colors[5] );
5721 /* calculate total number of accept states */
5726 w = trie->wordinfo[w].prev;
5729 ST.accepted = accepted;
5733 Perl_re_exec_indentf( aTHX_ "%sgot %" IVdf " possible matches%s\n",
5735 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5737 goto trie_first_try; /* jump into the fail handler */
5739 NOT_REACHED; /* NOTREACHED */
5741 case TRIE_next_fail: /* we failed - try next alternative */
5745 /* undo any captures done in the tail part of a branch,
5747 * /(?:X(.)(.)|Y(.)).../
5748 * where the trie just matches X then calls out to do the
5749 * rest of the branch */
5750 REGCP_UNWIND(ST.cp);
5751 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5753 if (!--ST.accepted) {
5755 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
5763 /* Find next-highest word to process. Note that this code
5764 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5767 U16 const nextword = ST.nextword;
5768 reg_trie_wordinfo * const wordinfo
5769 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5770 for (word=ST.topword; word; word=wordinfo[word].prev) {
5771 if (word > nextword && (!min || word < min))
5784 ST.lastparen = rex->lastparen;
5785 ST.lastcloseparen = rex->lastcloseparen;
5789 /* find start char of end of current word */
5791 U32 chars; /* how many chars to skip */
5792 reg_trie_data * const trie
5793 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5795 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5797 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5802 /* the hard option - fold each char in turn and find
5803 * its folded length (which may be different */
5804 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5812 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5820 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5825 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5841 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5842 ? ST.jump[ST.nextword]
5846 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
5854 if ( ST.accepted > 1 || has_cutgroup || ST.jump ) {
5855 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5856 NOT_REACHED; /* NOTREACHED */
5858 /* only one choice left - just continue */
5860 AV *const trie_words
5861 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5862 SV ** const tmp = trie_words
5863 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5864 SV *sv= tmp ? sv_newmortal() : NULL;
5866 Perl_re_exec_indentf( aTHX_ "%sonly one match left, short-circuiting: #%d <%s>%s\n",
5867 depth, PL_colors[4],
5869 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5870 PL_colors[0], PL_colors[1],
5871 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5873 : "not compiled under -Dr",
5877 locinput = (char*)uc;
5878 continue; /* execute rest of RE */
5883 case EXACTL: /* /abc/l */
5884 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5886 /* Complete checking would involve going through every character
5887 * matched by the string to see if any is above latin1. But the
5888 * comparision otherwise might very well be a fast assembly
5889 * language routine, and I (khw) don't think slowing things down
5890 * just to check for this warning is worth it. So this just checks
5891 * the first character */
5892 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5893 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5896 case EXACT: { /* /abc/ */
5897 char *s = STRING(scan);
5899 if (utf8_target != is_utf8_pat) {
5900 /* The target and the pattern have differing utf8ness. */
5902 const char * const e = s + ln;
5905 /* The target is utf8, the pattern is not utf8.
5906 * Above-Latin1 code points can't match the pattern;
5907 * invariants match exactly, and the other Latin1 ones need
5908 * to be downgraded to a single byte in order to do the
5909 * comparison. (If we could be confident that the target
5910 * is not malformed, this could be refactored to have fewer
5911 * tests by just assuming that if the first bytes match, it
5912 * is an invariant, but there are tests in the test suite
5913 * dealing with (??{...}) which violate this) */
5915 if (l >= reginfo->strend
5916 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5920 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5927 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5937 /* The target is not utf8, the pattern is utf8. */
5939 if (l >= reginfo->strend
5940 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5944 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5951 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5963 /* The target and the pattern have the same utf8ness. */
5964 /* Inline the first character, for speed. */
5965 if (reginfo->strend - locinput < ln
5966 || UCHARAT(s) != nextchr
5967 || (ln > 1 && memNE(s, locinput, ln)))
5976 case EXACTFL: { /* /abc/il */
5978 const U8 * fold_array;
5980 U32 fold_utf8_flags;
5982 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5983 folder = foldEQ_locale;
5984 fold_array = PL_fold_locale;
5985 fold_utf8_flags = FOLDEQ_LOCALE;
5988 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5989 is effectively /u; hence to match, target
5991 if (! utf8_target) {
5994 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5995 | FOLDEQ_S1_FOLDS_SANE;
5996 folder = foldEQ_latin1;
5997 fold_array = PL_fold_latin1;
6000 case EXACTFU_SS: /* /\x{df}/iu */
6001 case EXACTFU: /* /abc/iu */
6002 folder = foldEQ_latin1;
6003 fold_array = PL_fold_latin1;
6004 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
6007 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
6009 assert(! is_utf8_pat);
6011 case EXACTFA: /* /abc/iaa */
6012 folder = foldEQ_latin1;
6013 fold_array = PL_fold_latin1;
6014 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6017 case EXACTF: /* /abc/i This node only generated for
6018 non-utf8 patterns */
6019 assert(! is_utf8_pat);
6021 fold_array = PL_fold;
6022 fold_utf8_flags = 0;
6030 || state_num == EXACTFU_SS
6031 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6033 /* Either target or the pattern are utf8, or has the issue where
6034 * the fold lengths may differ. */
6035 const char * const l = locinput;
6036 char *e = reginfo->strend;
6038 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6039 l, &e, 0, utf8_target, fold_utf8_flags))
6047 /* Neither the target nor the pattern are utf8 */
6048 if (UCHARAT(s) != nextchr
6050 && UCHARAT(s) != fold_array[nextchr])
6054 if (reginfo->strend - locinput < ln)
6056 if (ln > 1 && ! folder(s, locinput, ln))
6062 case NBOUNDL: /* /\B/l */
6066 case BOUNDL: /* /\b/l */
6069 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6071 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6072 if (! IN_UTF8_CTYPE_LOCALE) {
6073 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6074 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6080 if (locinput == reginfo->strbeg)
6081 b1 = isWORDCHAR_LC('\n');
6083 b1 = isWORDCHAR_LC_utf8_safe(reghop3((U8*)locinput, -1,
6084 (U8*)(reginfo->strbeg)),
6085 (U8*)(reginfo->strend));
6087 b2 = (NEXTCHR_IS_EOS)
6088 ? isWORDCHAR_LC('\n')
6089 : isWORDCHAR_LC_utf8_safe((U8*) locinput,
6090 (U8*) reginfo->strend);
6092 else { /* Here the string isn't utf8 */
6093 b1 = (locinput == reginfo->strbeg)
6094 ? isWORDCHAR_LC('\n')
6095 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6096 b2 = (NEXTCHR_IS_EOS)
6097 ? isWORDCHAR_LC('\n')
6098 : isWORDCHAR_LC(nextchr);
6100 if (to_complement ^ (b1 == b2)) {
6106 case NBOUND: /* /\B/ */
6110 case BOUND: /* /\b/ */
6114 goto bound_ascii_match_only;
6116 case NBOUNDA: /* /\B/a */
6120 case BOUNDA: /* /\b/a */
6124 bound_ascii_match_only:
6125 /* Here the string isn't utf8, or is utf8 and only ascii characters
6126 * are to match \w. In the latter case looking at the byte just
6127 * prior to the current one may be just the final byte of a
6128 * multi-byte character. This is ok. There are two cases:
6129 * 1) it is a single byte character, and then the test is doing
6130 * just what it's supposed to.
6131 * 2) it is a multi-byte character, in which case the final byte is
6132 * never mistakable for ASCII, and so the test will say it is
6133 * not a word character, which is the correct answer. */
6134 b1 = (locinput == reginfo->strbeg)
6135 ? isWORDCHAR_A('\n')
6136 : isWORDCHAR_A(UCHARAT(locinput - 1));
6137 b2 = (NEXTCHR_IS_EOS)
6138 ? isWORDCHAR_A('\n')
6139 : isWORDCHAR_A(nextchr);
6140 if (to_complement ^ (b1 == b2)) {
6146 case NBOUNDU: /* /\B/u */
6150 case BOUNDU: /* /\b/u */
6153 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6156 else if (utf8_target) {
6158 switch((bound_type) FLAGS(scan)) {
6159 case TRADITIONAL_BOUND:
6162 b1 = (locinput == reginfo->strbeg)
6163 ? 0 /* isWORDCHAR_L1('\n') */
6164 : isWORDCHAR_utf8_safe(
6165 reghop3((U8*)locinput,
6167 (U8*)(reginfo->strbeg)),
6168 (U8*) reginfo->strend);
6169 b2 = (NEXTCHR_IS_EOS)
6170 ? 0 /* isWORDCHAR_L1('\n') */
6171 : isWORDCHAR_utf8_safe((U8*)locinput,
6172 (U8*) reginfo->strend);
6173 match = cBOOL(b1 != b2);
6177 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6178 match = TRUE; /* GCB always matches at begin and
6182 /* Find the gcb values of previous and current
6183 * chars, then see if is a break point */
6184 match = isGCB(getGCB_VAL_UTF8(
6185 reghop3((U8*)locinput,
6187 (U8*)(reginfo->strbeg)),
6188 (U8*) reginfo->strend),
6189 getGCB_VAL_UTF8((U8*) locinput,
6190 (U8*) reginfo->strend),
6191 (U8*) reginfo->strbeg,
6198 if (locinput == reginfo->strbeg) {
6201 else if (NEXTCHR_IS_EOS) {
6205 match = isLB(getLB_VAL_UTF8(
6206 reghop3((U8*)locinput,
6208 (U8*)(reginfo->strbeg)),
6209 (U8*) reginfo->strend),
6210 getLB_VAL_UTF8((U8*) locinput,
6211 (U8*) reginfo->strend),
6212 (U8*) reginfo->strbeg,
6214 (U8*) reginfo->strend,
6219 case SB_BOUND: /* Always matches at begin and end */
6220 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6224 match = isSB(getSB_VAL_UTF8(
6225 reghop3((U8*)locinput,
6227 (U8*)(reginfo->strbeg)),
6228 (U8*) reginfo->strend),
6229 getSB_VAL_UTF8((U8*) locinput,
6230 (U8*) reginfo->strend),
6231 (U8*) reginfo->strbeg,
6233 (U8*) reginfo->strend,
6239 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6243 match = isWB(WB_UNKNOWN,
6245 reghop3((U8*)locinput,
6247 (U8*)(reginfo->strbeg)),
6248 (U8*) reginfo->strend),
6249 getWB_VAL_UTF8((U8*) locinput,
6250 (U8*) reginfo->strend),
6251 (U8*) reginfo->strbeg,
6253 (U8*) reginfo->strend,
6259 else { /* Not utf8 target */
6260 switch((bound_type) FLAGS(scan)) {
6261 case TRADITIONAL_BOUND:
6264 b1 = (locinput == reginfo->strbeg)
6265 ? 0 /* isWORDCHAR_L1('\n') */
6266 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6267 b2 = (NEXTCHR_IS_EOS)
6268 ? 0 /* isWORDCHAR_L1('\n') */
6269 : isWORDCHAR_L1(nextchr);
6270 match = cBOOL(b1 != b2);
6275 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6276 match = TRUE; /* GCB always matches at begin and
6279 else { /* Only CR-LF combo isn't a GCB in 0-255
6281 match = UCHARAT(locinput - 1) != '\r'
6282 || UCHARAT(locinput) != '\n';
6287 if (locinput == reginfo->strbeg) {
6290 else if (NEXTCHR_IS_EOS) {
6294 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6295 getLB_VAL_CP(UCHARAT(locinput)),
6296 (U8*) reginfo->strbeg,
6298 (U8*) reginfo->strend,
6303 case SB_BOUND: /* Always matches at begin and end */
6304 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6308 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6309 getSB_VAL_CP(UCHARAT(locinput)),
6310 (U8*) reginfo->strbeg,
6312 (U8*) reginfo->strend,
6318 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6322 match = isWB(WB_UNKNOWN,
6323 getWB_VAL_CP(UCHARAT(locinput -1)),
6324 getWB_VAL_CP(UCHARAT(locinput)),
6325 (U8*) reginfo->strbeg,
6327 (U8*) reginfo->strend,
6334 if (to_complement ^ ! match) {
6339 case ANYOFL: /* /[abc]/l */
6340 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6342 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6344 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6347 case ANYOFD: /* /[abc]/d */
6348 case ANYOF: /* /[abc]/ */
6351 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6352 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6355 locinput += UTF8SKIP(locinput);
6358 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6364 /* The argument (FLAGS) to all the POSIX node types is the class number
6367 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6371 case POSIXL: /* \w or [:punct:] etc. under /l */
6372 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6376 /* Use isFOO_lc() for characters within Latin1. (Note that
6377 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6378 * wouldn't be invariant) */
6379 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6380 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6388 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6389 /* An above Latin-1 code point, or malformed */
6390 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
6392 goto utf8_posix_above_latin1;
6395 /* Here is a UTF-8 variant code point below 256 and the target is
6397 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6398 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6399 *(locinput + 1))))))
6404 goto increment_locinput;
6406 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6410 case POSIXD: /* \w or [:punct:] etc. under /d */
6416 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6418 if (NEXTCHR_IS_EOS) {
6422 /* All UTF-8 variants match */
6423 if (! UTF8_IS_INVARIANT(nextchr)) {
6424 goto increment_locinput;
6430 case POSIXA: /* \w or [:punct:] etc. under /a */
6433 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6434 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6435 * character is a single byte */
6437 if (NEXTCHR_IS_EOS) {
6443 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6449 /* Here we are either not in utf8, or we matched a utf8-invariant,
6450 * so the next char is the next byte */
6454 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6458 case POSIXU: /* \w or [:punct:] etc. under /u */
6460 if (NEXTCHR_IS_EOS) {
6464 /* Use _generic_isCC() for characters within Latin1. (Note that
6465 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6466 * wouldn't be invariant) */
6467 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6468 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6475 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6476 if (! (to_complement
6477 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6485 else { /* Handle above Latin-1 code points */
6486 utf8_posix_above_latin1:
6487 classnum = (_char_class_number) FLAGS(scan);
6488 if (classnum < _FIRST_NON_SWASH_CC) {
6490 /* Here, uses a swash to find such code points. Load if if
6491 * not done already */
6492 if (! PL_utf8_swash_ptrs[classnum]) {
6493 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6494 PL_utf8_swash_ptrs[classnum]
6495 = _core_swash_init("utf8",
6498 PL_XPosix_ptrs[classnum], &flags);
6500 if (! (to_complement
6501 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6502 (U8 *) locinput, TRUE))))
6507 else { /* Here, uses macros to find above Latin-1 code points */
6509 case _CC_ENUM_SPACE:
6510 if (! (to_complement
6511 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6516 case _CC_ENUM_BLANK:
6517 if (! (to_complement
6518 ^ cBOOL(is_HORIZWS_high(locinput))))
6523 case _CC_ENUM_XDIGIT:
6524 if (! (to_complement
6525 ^ cBOOL(is_XDIGIT_high(locinput))))
6530 case _CC_ENUM_VERTSPACE:
6531 if (! (to_complement
6532 ^ cBOOL(is_VERTWS_high(locinput))))
6537 default: /* The rest, e.g. [:cntrl:], can't match
6539 if (! to_complement) {
6545 locinput += UTF8SKIP(locinput);
6549 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6550 a Unicode extended Grapheme Cluster */
6553 if (! utf8_target) {
6555 /* Match either CR LF or '.', as all the other possibilities
6557 locinput++; /* Match the . or CR */
6558 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6560 && locinput < reginfo->strend
6561 && UCHARAT(locinput) == '\n')
6568 /* Get the gcb type for the current character */
6569 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6570 (U8*) reginfo->strend);
6572 /* Then scan through the input until we get to the first
6573 * character whose type is supposed to be a gcb with the
6574 * current character. (There is always a break at the
6576 locinput += UTF8SKIP(locinput);
6577 while (locinput < reginfo->strend) {
6578 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6579 (U8*) reginfo->strend);
6580 if (isGCB(prev_gcb, cur_gcb,
6581 (U8*) reginfo->strbeg, (U8*) locinput,
6588 locinput += UTF8SKIP(locinput);
6595 case NREFFL: /* /\g{name}/il */
6596 { /* The capture buffer cases. The ones beginning with N for the
6597 named buffers just convert to the equivalent numbered and
6598 pretend they were called as the corresponding numbered buffer
6600 /* don't initialize these in the declaration, it makes C++
6605 const U8 *fold_array;
6608 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6609 folder = foldEQ_locale;
6610 fold_array = PL_fold_locale;
6612 utf8_fold_flags = FOLDEQ_LOCALE;
6615 case NREFFA: /* /\g{name}/iaa */
6616 folder = foldEQ_latin1;
6617 fold_array = PL_fold_latin1;
6619 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6622 case NREFFU: /* /\g{name}/iu */
6623 folder = foldEQ_latin1;
6624 fold_array = PL_fold_latin1;
6626 utf8_fold_flags = 0;
6629 case NREFF: /* /\g{name}/i */
6631 fold_array = PL_fold;
6633 utf8_fold_flags = 0;
6636 case NREF: /* /\g{name}/ */
6640 utf8_fold_flags = 0;
6643 /* For the named back references, find the corresponding buffer
6645 n = reg_check_named_buff_matched(rex,scan);
6650 goto do_nref_ref_common;
6652 case REFFL: /* /\1/il */
6653 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6654 folder = foldEQ_locale;
6655 fold_array = PL_fold_locale;
6656 utf8_fold_flags = FOLDEQ_LOCALE;
6659 case REFFA: /* /\1/iaa */
6660 folder = foldEQ_latin1;
6661 fold_array = PL_fold_latin1;
6662 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6665 case REFFU: /* /\1/iu */
6666 folder = foldEQ_latin1;
6667 fold_array = PL_fold_latin1;
6668 utf8_fold_flags = 0;
6671 case REFF: /* /\1/i */
6673 fold_array = PL_fold;
6674 utf8_fold_flags = 0;
6677 case REF: /* /\1/ */
6680 utf8_fold_flags = 0;
6684 n = ARG(scan); /* which paren pair */
6687 ln = rex->offs[n].start;
6688 endref = rex->offs[n].end;
6689 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6690 if (rex->lastparen < n || ln == -1 || endref == -1)
6691 sayNO; /* Do not match unless seen CLOSEn. */
6695 s = reginfo->strbeg + ln;
6696 if (type != REF /* REF can do byte comparison */
6697 && (utf8_target || type == REFFU || type == REFFL))
6699 char * limit = reginfo->strend;
6701 /* This call case insensitively compares the entire buffer
6702 * at s, with the current input starting at locinput, but
6703 * not going off the end given by reginfo->strend, and
6704 * returns in <limit> upon success, how much of the
6705 * current input was matched */
6706 if (! foldEQ_utf8_flags(s, NULL, endref - ln, utf8_target,
6707 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6715 /* Not utf8: Inline the first character, for speed. */
6716 if (!NEXTCHR_IS_EOS &&
6717 UCHARAT(s) != nextchr &&
6719 UCHARAT(s) != fold_array[nextchr]))
6722 if (locinput + ln > reginfo->strend)
6724 if (ln > 1 && (type == REF
6725 ? memNE(s, locinput, ln)
6726 : ! folder(s, locinput, ln)))
6732 case NOTHING: /* null op; e.g. the 'nothing' following
6733 * the '*' in m{(a+|b)*}' */
6735 case TAIL: /* placeholder while compiling (A|B|C) */
6739 #define ST st->u.eval
6740 #define CUR_EVAL cur_eval->u.eval
6746 regexp_internal *rei;
6747 regnode *startpoint;
6750 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6751 arg= (U32)ARG(scan);
6752 if (cur_eval && cur_eval->locinput == locinput) {
6753 if ( ++nochange_depth > max_nochange_depth )
6755 "Pattern subroutine nesting without pos change"
6756 " exceeded limit in regex");
6763 startpoint = scan + ARG2L(scan);
6764 EVAL_CLOSE_PAREN_SET( st, arg );
6765 /* Detect infinite recursion
6767 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
6768 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
6769 * So we track the position in the string we are at each time
6770 * we recurse and if we try to enter the same routine twice from
6771 * the same position we throw an error.
6773 if ( rex->recurse_locinput[arg] == locinput ) {
6774 /* FIXME: we should show the regop that is failing as part
6775 * of the error message. */
6776 Perl_croak(aTHX_ "Infinite recursion in regex");
6778 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
6779 rex->recurse_locinput[arg]= locinput;
6782 GET_RE_DEBUG_FLAGS_DECL;
6784 Perl_re_exec_indentf( aTHX_
6785 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
6786 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
6792 /* Save all the positions seen so far. */
6793 ST.cp = regcppush(rex, 0, maxopenparen);
6794 REGCP_SET(ST.lastcp);
6796 /* and then jump to the code we share with EVAL */
6797 goto eval_recurse_doit;
6800 case EVAL: /* /(?{...})B/ /(??{A})B/ and /(?(?{...})X|Y)B/ */
6801 if (cur_eval && cur_eval->locinput==locinput) {
6802 if ( ++nochange_depth > max_nochange_depth )
6803 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6808 /* execute the code in the {...} */
6812 OP * const oop = PL_op;
6813 COP * const ocurcop = PL_curcop;
6817 /* save *all* paren positions */
6818 regcppush(rex, 0, maxopenparen);
6819 REGCP_SET(ST.lastcp);
6822 caller_cv = find_runcv(NULL);
6826 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6828 (REGEXP*)(rexi->data->data[n])
6830 nop = (OP*)rexi->data->data[n+1];
6832 else if (rexi->data->what[n] == 'l') { /* literal code */
6834 nop = (OP*)rexi->data->data[n];
6835 assert(CvDEPTH(newcv));
6838 /* literal with own CV */
6839 assert(rexi->data->what[n] == 'L');
6840 newcv = rex->qr_anoncv;
6841 nop = (OP*)rexi->data->data[n];
6844 /* Some notes about MULTICALL and the context and save stacks.
6847 * /...(?{ my $x)}...(?{ my $y)}...(?{ my $z)}.../
6848 * since codeblocks don't introduce a new scope (so that
6849 * local() etc accumulate), at the end of a successful
6850 * match there will be a SAVEt_CLEARSV on the savestack
6851 * for each of $x, $y, $z. If the three code blocks above
6852 * happen to have come from different CVs (e.g. via
6853 * embedded qr//s), then we must ensure that during any
6854 * savestack unwinding, PL_comppad always points to the
6855 * right pad at each moment. We achieve this by
6856 * interleaving SAVEt_COMPPAD's on the savestack whenever
6857 * there is a change of pad.
6858 * In theory whenever we call a code block, we should
6859 * push a CXt_SUB context, then pop it on return from
6860 * that code block. This causes a bit of an issue in that
6861 * normally popping a context also clears the savestack
6862 * back to cx->blk_oldsaveix, but here we specifically
6863 * don't want to clear the save stack on exit from the
6865 * Also for efficiency we don't want to keep pushing and
6866 * popping the single SUB context as we backtrack etc.
6867 * So instead, we push a single context the first time
6868 * we need, it, then hang onto it until the end of this
6869 * function. Whenever we encounter a new code block, we
6870 * update the CV etc if that's changed. During the times
6871 * in this function where we're not executing a code
6872 * block, having the SUB context still there is a bit
6873 * naughty - but we hope that no-one notices.
6874 * When the SUB context is initially pushed, we fake up
6875 * cx->blk_oldsaveix to be as if we'd pushed this context
6876 * on first entry to S_regmatch rather than at some random
6877 * point during the regexe execution. That way if we
6878 * croak, popping the context stack will ensure that
6879 * *everything* SAVEd by this function is undone and then
6880 * the context popped, rather than e.g., popping the
6881 * context (and restoring the original PL_comppad) then
6882 * popping more of the savestack and restoring a bad
6886 /* If this is the first EVAL, push a MULTICALL. On
6887 * subsequent calls, if we're executing a different CV, or
6888 * if PL_comppad has got messed up from backtracking
6889 * through SAVECOMPPADs, then refresh the context.
6891 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6893 U8 flags = (CXp_SUB_RE |
6894 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6896 if (last_pushed_cv) {
6897 CHANGE_MULTICALL_FLAGS(newcv, flags);
6900 PUSH_MULTICALL_FLAGS(newcv, flags);
6902 /* see notes above */
6903 CX_CUR()->blk_oldsaveix = orig_savestack_ix;
6905 last_pushed_cv = newcv;
6908 /* these assignments are just to silence compiler
6910 multicall_cop = NULL;
6912 last_pad = PL_comppad;
6914 /* the initial nextstate you would normally execute
6915 * at the start of an eval (which would cause error
6916 * messages to come from the eval), may be optimised
6917 * away from the execution path in the regex code blocks;
6918 * so manually set PL_curcop to it initially */
6920 OP *o = cUNOPx(nop)->op_first;
6921 assert(o->op_type == OP_NULL);
6922 if (o->op_targ == OP_SCOPE) {
6923 o = cUNOPo->op_first;
6926 assert(o->op_targ == OP_LEAVE);
6927 o = cUNOPo->op_first;
6928 assert(o->op_type == OP_ENTER);
6932 if (o->op_type != OP_STUB) {
6933 assert( o->op_type == OP_NEXTSTATE
6934 || o->op_type == OP_DBSTATE
6935 || (o->op_type == OP_NULL
6936 && ( o->op_targ == OP_NEXTSTATE
6937 || o->op_targ == OP_DBSTATE
6941 PL_curcop = (COP*)o;
6946 DEBUG_STATE_r( Perl_re_printf( aTHX_
6947 " re EVAL PL_op=0x%" UVxf "\n", PTR2UV(nop)) );
6949 rex->offs[0].end = locinput - reginfo->strbeg;
6950 if (reginfo->info_aux_eval->pos_magic)
6951 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6952 reginfo->sv, reginfo->strbeg,
6953 locinput - reginfo->strbeg);
6956 SV *sv_mrk = get_sv("REGMARK", 1);
6957 sv_setsv(sv_mrk, sv_yes_mark);
6960 /* we don't use MULTICALL here as we want to call the
6961 * first op of the block of interest, rather than the
6962 * first op of the sub. Also, we don't want to free
6963 * the savestack frame */
6964 before = (IV)(SP-PL_stack_base);
6966 CALLRUNOPS(aTHX); /* Scalar context. */
6968 if ((IV)(SP-PL_stack_base) == before)
6969 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6975 /* before restoring everything, evaluate the returned
6976 * value, so that 'uninit' warnings don't use the wrong
6977 * PL_op or pad. Also need to process any magic vars
6978 * (e.g. $1) *before* parentheses are restored */
6983 if (logical == 0) /* (?{})/ */
6984 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6985 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6986 sw = cBOOL(SvTRUE_NN(ret));
6989 else { /* /(??{}) */
6990 /* if its overloaded, let the regex compiler handle
6991 * it; otherwise extract regex, or stringify */
6992 if (SvGMAGICAL(ret))
6993 ret = sv_mortalcopy(ret);
6994 if (!SvAMAGIC(ret)) {
6998 if (SvTYPE(sv) == SVt_REGEXP)
6999 re_sv = (REGEXP*) sv;
7000 else if (SvSMAGICAL(ret)) {
7001 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
7003 re_sv = (REGEXP *) mg->mg_obj;
7006 /* force any undef warnings here */
7007 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
7008 ret = sv_mortalcopy(ret);
7009 (void) SvPV_force_nolen(ret);
7015 /* *** Note that at this point we don't restore
7016 * PL_comppad, (or pop the CxSUB) on the assumption it may
7017 * be used again soon. This is safe as long as nothing
7018 * in the regexp code uses the pad ! */
7020 PL_curcop = ocurcop;
7021 regcp_restore(rex, ST.lastcp, &maxopenparen);
7022 PL_curpm_under = PL_curpm;
7023 PL_curpm = PL_reg_curpm;
7026 PUSH_STATE_GOTO(EVAL_B, next, locinput);
7031 /* only /(??{})/ from now on */
7034 /* extract RE object from returned value; compiling if
7038 re_sv = reg_temp_copy(NULL, re_sv);
7043 if (SvUTF8(ret) && IN_BYTES) {
7044 /* In use 'bytes': make a copy of the octet
7045 * sequence, but without the flag on */
7047 const char *const p = SvPV(ret, len);
7048 ret = newSVpvn_flags(p, len, SVs_TEMP);
7050 if (rex->intflags & PREGf_USE_RE_EVAL)
7051 pm_flags |= PMf_USE_RE_EVAL;
7053 /* if we got here, it should be an engine which
7054 * supports compiling code blocks and stuff */
7055 assert(rex->engine && rex->engine->op_comp);
7056 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
7057 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
7058 rex->engine, NULL, NULL,
7059 /* copy /msixn etc to inner pattern */
7064 & (SVs_TEMP | SVs_GMG | SVf_ROK))
7065 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
7066 /* This isn't a first class regexp. Instead, it's
7067 caching a regexp onto an existing, Perl visible
7069 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
7075 RXp_MATCH_COPIED_off(re);
7076 re->subbeg = rex->subbeg;
7077 re->sublen = rex->sublen;
7078 re->suboffset = rex->suboffset;
7079 re->subcoffset = rex->subcoffset;
7081 re->lastcloseparen = 0;
7084 debug_start_match(re_sv, utf8_target, locinput,
7085 reginfo->strend, "Matching embedded");
7087 startpoint = rei->program + 1;
7088 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7089 * close_paren only for GOSUB */
7090 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7091 /* Save all the seen positions so far. */
7092 ST.cp = regcppush(rex, 0, maxopenparen);
7093 REGCP_SET(ST.lastcp);
7094 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7096 /* run the pattern returned from (??{...}) */
7098 eval_recurse_doit: /* Share code with GOSUB below this line
7099 * At this point we expect the stack context to be
7100 * set up correctly */
7102 /* invalidate the S-L poscache. We're now executing a
7103 * different set of WHILEM ops (and their associated
7104 * indexes) against the same string, so the bits in the
7105 * cache are meaningless. Setting maxiter to zero forces
7106 * the cache to be invalidated and zeroed before reuse.
7107 * XXX This is too dramatic a measure. Ideally we should
7108 * save the old cache and restore when running the outer
7110 reginfo->poscache_maxiter = 0;
7112 /* the new regexp might have a different is_utf8_pat than we do */
7113 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7115 ST.prev_rex = rex_sv;
7116 ST.prev_curlyx = cur_curlyx;
7118 SET_reg_curpm(rex_sv);
7123 ST.prev_eval = cur_eval;
7125 /* now continue from first node in postoned RE */
7126 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, startpoint, locinput);
7127 NOT_REACHED; /* NOTREACHED */
7130 case EVAL_postponed_AB: /* cleanup after a successful (??{A})B */
7131 /* note: this is called twice; first after popping B, then A */
7133 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7134 depth, cur_eval, ST.prev_eval);
7137 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7138 if ( cur_eval && CUR_EVAL.close_paren ) {\
7140 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7142 CUR_EVAL.close_paren - 1,\
7146 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7149 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7151 rex_sv = ST.prev_rex;
7152 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7153 SET_reg_curpm(rex_sv);
7154 rex = ReANY(rex_sv);
7155 rexi = RXi_GET(rex);
7157 /* preserve $^R across LEAVE's. See Bug 121070. */
7158 SV *save_sv= GvSV(PL_replgv);
7159 SvREFCNT_inc(save_sv);
7160 regcpblow(ST.cp); /* LEAVE in disguise */
7161 sv_setsv(GvSV(PL_replgv), save_sv);
7162 SvREFCNT_dec(save_sv);
7164 cur_eval = ST.prev_eval;
7165 cur_curlyx = ST.prev_curlyx;
7167 /* Invalidate cache. See "invalidate" comment above. */
7168 reginfo->poscache_maxiter = 0;
7169 if ( nochange_depth )
7172 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7176 case EVAL_B_fail: /* unsuccessful B in (?{...})B */
7177 REGCP_UNWIND(ST.lastcp);
7180 case EVAL_postponed_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7181 /* note: this is called twice; first after popping B, then A */
7183 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7184 depth, cur_eval, ST.prev_eval);
7187 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7189 rex_sv = ST.prev_rex;
7190 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7191 SET_reg_curpm(rex_sv);
7192 rex = ReANY(rex_sv);
7193 rexi = RXi_GET(rex);
7195 REGCP_UNWIND(ST.lastcp);
7196 regcppop(rex, &maxopenparen);
7197 cur_eval = ST.prev_eval;
7198 cur_curlyx = ST.prev_curlyx;
7200 /* Invalidate cache. See "invalidate" comment above. */
7201 reginfo->poscache_maxiter = 0;
7202 if ( nochange_depth )
7205 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7210 n = ARG(scan); /* which paren pair */
7211 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7212 if (n > maxopenparen)
7214 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
7215 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf " tmp; maxopenparen=%" UVuf "\n",
7220 (IV)rex->offs[n].start_tmp,
7226 /* XXX really need to log other places start/end are set too */
7227 #define CLOSE_CAPTURE \
7228 rex->offs[n].start = rex->offs[n].start_tmp; \
7229 rex->offs[n].end = locinput - reginfo->strbeg; \
7230 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
7231 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf "\n", \
7234 PTR2UV(rex->offs), \
7236 (IV)rex->offs[n].start, \
7237 (IV)rex->offs[n].end \
7241 n = ARG(scan); /* which paren pair */
7243 if (n > rex->lastparen)
7245 rex->lastcloseparen = n;
7246 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7251 case ACCEPT: /* (*ACCEPT) */
7253 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7257 cursor && OP(cursor)!=END;
7258 cursor=regnext(cursor))
7260 if ( OP(cursor)==CLOSE ){
7262 if ( n <= lastopen ) {
7264 if (n > rex->lastparen)
7266 rex->lastcloseparen = n;
7267 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7276 case GROUPP: /* (?(1)) */
7277 n = ARG(scan); /* which paren pair */
7278 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7281 case NGROUPP: /* (?(<name>)) */
7282 /* reg_check_named_buff_matched returns 0 for no match */
7283 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7286 case INSUBP: /* (?(R)) */
7288 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7289 * of SCAN is already set up as matches a eval.close_paren */
7290 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7293 case DEFINEP: /* (?(DEFINE)) */
7297 case IFTHEN: /* (?(cond)A|B) */
7298 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7300 next = NEXTOPER(NEXTOPER(scan));
7302 next = scan + ARG(scan);
7303 if (OP(next) == IFTHEN) /* Fake one. */
7304 next = NEXTOPER(NEXTOPER(next));
7308 case LOGICAL: /* modifier for EVAL and IFMATCH */
7309 logical = scan->flags;
7312 /*******************************************************************
7314 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7315 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7316 STAR/PLUS/CURLY/CURLYN are used instead.)
7318 A*B is compiled as <CURLYX><A><WHILEM><B>
7320 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7321 state, which contains the current count, initialised to -1. It also sets
7322 cur_curlyx to point to this state, with any previous value saved in the
7325 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7326 since the pattern may possibly match zero times (i.e. it's a while {} loop
7327 rather than a do {} while loop).
7329 Each entry to WHILEM represents a successful match of A. The count in the
7330 CURLYX block is incremented, another WHILEM state is pushed, and execution
7331 passes to A or B depending on greediness and the current count.
7333 For example, if matching against the string a1a2a3b (where the aN are
7334 substrings that match /A/), then the match progresses as follows: (the
7335 pushed states are interspersed with the bits of strings matched so far):
7338 <CURLYX cnt=0><WHILEM>
7339 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7340 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7341 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7342 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7344 (Contrast this with something like CURLYM, which maintains only a single
7348 a1 <CURLYM cnt=1> a2
7349 a1 a2 <CURLYM cnt=2> a3
7350 a1 a2 a3 <CURLYM cnt=3> b
7353 Each WHILEM state block marks a point to backtrack to upon partial failure
7354 of A or B, and also contains some minor state data related to that
7355 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7356 overall state, such as the count, and pointers to the A and B ops.
7358 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7359 must always point to the *current* CURLYX block, the rules are:
7361 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7362 and set cur_curlyx to point the new block.
7364 When popping the CURLYX block after a successful or unsuccessful match,
7365 restore the previous cur_curlyx.
7367 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7368 to the outer one saved in the CURLYX block.
7370 When popping the WHILEM block after a successful or unsuccessful B match,
7371 restore the previous cur_curlyx.
7373 Here's an example for the pattern (AI* BI)*BO
7374 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7377 curlyx backtrack stack
7378 ------ ---------------
7380 CO <CO prev=NULL> <WO>
7381 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7382 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7383 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7385 At this point the pattern succeeds, and we work back down the stack to
7386 clean up, restoring as we go:
7388 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7389 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7390 CO <CO prev=NULL> <WO>
7393 *******************************************************************/
7395 #define ST st->u.curlyx
7397 case CURLYX: /* start of /A*B/ (for complex A) */
7399 /* No need to save/restore up to this paren */
7400 I32 parenfloor = scan->flags;
7402 assert(next); /* keep Coverity happy */
7403 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7406 /* XXXX Probably it is better to teach regpush to support
7407 parenfloor > maxopenparen ... */
7408 if (parenfloor > (I32)rex->lastparen)
7409 parenfloor = rex->lastparen; /* Pessimization... */
7411 ST.prev_curlyx= cur_curlyx;
7413 ST.cp = PL_savestack_ix;
7415 /* these fields contain the state of the current curly.
7416 * they are accessed by subsequent WHILEMs */
7417 ST.parenfloor = parenfloor;
7422 ST.count = -1; /* this will be updated by WHILEM */
7423 ST.lastloc = NULL; /* this will be updated by WHILEM */
7425 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7426 NOT_REACHED; /* NOTREACHED */
7429 case CURLYX_end: /* just finished matching all of A*B */
7430 cur_curlyx = ST.prev_curlyx;
7432 NOT_REACHED; /* NOTREACHED */
7434 case CURLYX_end_fail: /* just failed to match all of A*B */
7436 cur_curlyx = ST.prev_curlyx;
7438 NOT_REACHED; /* NOTREACHED */
7442 #define ST st->u.whilem
7444 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7446 /* see the discussion above about CURLYX/WHILEM */
7451 assert(cur_curlyx); /* keep Coverity happy */
7453 min = ARG1(cur_curlyx->u.curlyx.me);
7454 max = ARG2(cur_curlyx->u.curlyx.me);
7455 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7456 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7457 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7458 ST.cache_offset = 0;
7462 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: matched %ld out of %d..%d\n",
7463 depth, (long)n, min, max)
7466 /* First just match a string of min A's. */
7469 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor, maxopenparen);
7470 cur_curlyx->u.curlyx.lastloc = locinput;
7471 REGCP_SET(ST.lastcp);
7473 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7474 NOT_REACHED; /* NOTREACHED */
7477 /* If degenerate A matches "", assume A done. */
7479 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7480 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: empty match detected, trying continuation...\n",
7483 goto do_whilem_B_max;
7486 /* super-linear cache processing.
7488 * The idea here is that for certain types of CURLYX/WHILEM -
7489 * principally those whose upper bound is infinity (and
7490 * excluding regexes that have things like \1 and other very
7491 * non-regular expresssiony things), then if a pattern like
7492 * /....A*.../ fails and we backtrack to the WHILEM, then we
7493 * make a note that this particular WHILEM op was at string
7494 * position 47 (say) when the rest of pattern failed. Then, if
7495 * we ever find ourselves back at that WHILEM, and at string
7496 * position 47 again, we can just fail immediately rather than
7497 * running the rest of the pattern again.
7499 * This is very handy when patterns start to go
7500 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7501 * with a combinatorial explosion of backtracking.
7503 * The cache is implemented as a bit array, with one bit per
7504 * string byte position per WHILEM op (up to 16) - so its
7505 * between 0.25 and 2x the string size.
7507 * To avoid allocating a poscache buffer every time, we do an
7508 * initially countdown; only after we have executed a WHILEM
7509 * op (string-length x #WHILEMs) times do we allocate the
7512 * The top 4 bits of scan->flags byte say how many different
7513 * relevant CURLLYX/WHILEM op pairs there are, while the
7514 * bottom 4-bits is the identifying index number of this
7520 if (!reginfo->poscache_maxiter) {
7521 /* start the countdown: Postpone detection until we
7522 * know the match is not *that* much linear. */
7523 reginfo->poscache_maxiter
7524 = (reginfo->strend - reginfo->strbeg + 1)
7526 /* possible overflow for long strings and many CURLYX's */
7527 if (reginfo->poscache_maxiter < 0)
7528 reginfo->poscache_maxiter = I32_MAX;
7529 reginfo->poscache_iter = reginfo->poscache_maxiter;
7532 if (reginfo->poscache_iter-- == 0) {
7533 /* initialise cache */
7534 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7535 regmatch_info_aux *const aux = reginfo->info_aux;
7536 if (aux->poscache) {
7537 if ((SSize_t)reginfo->poscache_size < size) {
7538 Renew(aux->poscache, size, char);
7539 reginfo->poscache_size = size;
7541 Zero(aux->poscache, size, char);
7544 reginfo->poscache_size = size;
7545 Newxz(aux->poscache, size, char);
7547 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7548 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7549 PL_colors[4], PL_colors[5])
7553 if (reginfo->poscache_iter < 0) {
7554 /* have we already failed at this position? */
7555 SSize_t offset, mask;
7557 reginfo->poscache_iter = -1; /* stop eventual underflow */
7558 offset = (scan->flags & 0xf) - 1
7559 + (locinput - reginfo->strbeg)
7561 mask = 1 << (offset % 8);
7563 if (reginfo->info_aux->poscache[offset] & mask) {
7564 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: (cache) already tried at this position...\n",
7567 cur_curlyx->u.curlyx.count--;
7568 sayNO; /* cache records failure */
7570 ST.cache_offset = offset;
7571 ST.cache_mask = mask;
7575 /* Prefer B over A for minimal matching. */
7577 if (cur_curlyx->u.curlyx.minmod) {
7578 ST.save_curlyx = cur_curlyx;
7579 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7580 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7582 NOT_REACHED; /* NOTREACHED */
7585 /* Prefer A over B for maximal matching. */
7587 if (n < max) { /* More greed allowed? */
7588 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7590 cur_curlyx->u.curlyx.lastloc = locinput;
7591 REGCP_SET(ST.lastcp);
7592 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7593 NOT_REACHED; /* NOTREACHED */
7595 goto do_whilem_B_max;
7597 NOT_REACHED; /* NOTREACHED */
7599 case WHILEM_B_min: /* just matched B in a minimal match */
7600 case WHILEM_B_max: /* just matched B in a maximal match */
7601 cur_curlyx = ST.save_curlyx;
7603 NOT_REACHED; /* NOTREACHED */
7605 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7606 cur_curlyx = ST.save_curlyx;
7607 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7608 cur_curlyx->u.curlyx.count--;
7610 NOT_REACHED; /* NOTREACHED */
7612 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7613 REGCP_UNWIND(ST.lastcp);
7614 regcppop(rex, &maxopenparen);
7616 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7617 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7618 cur_curlyx->u.curlyx.count--;
7620 NOT_REACHED; /* NOTREACHED */
7622 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7623 REGCP_UNWIND(ST.lastcp);
7624 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7625 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "whilem: failed, trying continuation...\n",
7629 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7630 && ckWARN(WARN_REGEXP)
7631 && !reginfo->warned)
7633 reginfo->warned = TRUE;
7634 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7635 "Complex regular subexpression recursion limit (%d) "
7641 ST.save_curlyx = cur_curlyx;
7642 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7643 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7645 NOT_REACHED; /* NOTREACHED */
7647 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7648 cur_curlyx = ST.save_curlyx;
7650 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7651 /* Maximum greed exceeded */
7652 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7653 && ckWARN(WARN_REGEXP)
7654 && !reginfo->warned)
7656 reginfo->warned = TRUE;
7657 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7658 "Complex regular subexpression recursion "
7659 "limit (%d) exceeded",
7662 cur_curlyx->u.curlyx.count--;
7666 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "trying longer...\n", depth)
7668 /* Try grabbing another A and see if it helps. */
7669 cur_curlyx->u.curlyx.lastloc = locinput;
7670 PUSH_STATE_GOTO(WHILEM_A_min,
7671 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7673 NOT_REACHED; /* NOTREACHED */
7676 #define ST st->u.branch
7678 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7679 next = scan + ARG(scan);
7682 scan = NEXTOPER(scan);
7685 case BRANCH: /* /(...|A|...)/ */
7686 scan = NEXTOPER(scan); /* scan now points to inner node */
7687 ST.lastparen = rex->lastparen;
7688 ST.lastcloseparen = rex->lastcloseparen;
7689 ST.next_branch = next;
7692 /* Now go into the branch */
7694 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7696 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7698 NOT_REACHED; /* NOTREACHED */
7700 case CUTGROUP: /* /(*THEN)/ */
7701 sv_yes_mark = st->u.mark.mark_name = scan->flags
7702 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7704 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7705 NOT_REACHED; /* NOTREACHED */
7707 case CUTGROUP_next_fail:
7710 if (st->u.mark.mark_name)
7711 sv_commit = st->u.mark.mark_name;
7713 NOT_REACHED; /* NOTREACHED */
7717 NOT_REACHED; /* NOTREACHED */
7719 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7724 REGCP_UNWIND(ST.cp);
7725 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7726 scan = ST.next_branch;
7727 /* no more branches? */
7728 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7730 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
7737 continue; /* execute next BRANCH[J] op */
7740 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7745 #define ST st->u.curlym
7747 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7749 /* This is an optimisation of CURLYX that enables us to push
7750 * only a single backtracking state, no matter how many matches
7751 * there are in {m,n}. It relies on the pattern being constant
7752 * length, with no parens to influence future backrefs
7756 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7758 ST.lastparen = rex->lastparen;
7759 ST.lastcloseparen = rex->lastcloseparen;
7761 /* if paren positive, emulate an OPEN/CLOSE around A */
7763 U32 paren = ST.me->flags;
7764 if (paren > maxopenparen)
7765 maxopenparen = paren;
7766 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7774 ST.c1 = CHRTEST_UNINIT;
7777 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7780 curlym_do_A: /* execute the A in /A{m,n}B/ */
7781 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7782 NOT_REACHED; /* NOTREACHED */
7784 case CURLYM_A: /* we've just matched an A */
7786 /* after first match, determine A's length: u.curlym.alen */
7787 if (ST.count == 1) {
7788 if (reginfo->is_utf8_target) {
7789 char *s = st->locinput;
7790 while (s < locinput) {
7796 ST.alen = locinput - st->locinput;
7799 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7802 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %" IVdf " times, len=%" IVdf "...\n",
7803 depth, (IV) ST.count, (IV)ST.alen)
7806 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7810 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7811 if ( max == REG_INFTY || ST.count < max )
7812 goto curlym_do_A; /* try to match another A */
7814 goto curlym_do_B; /* try to match B */
7816 case CURLYM_A_fail: /* just failed to match an A */
7817 REGCP_UNWIND(ST.cp);
7820 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7821 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7824 curlym_do_B: /* execute the B in /A{m,n}B/ */
7825 if (ST.c1 == CHRTEST_UNINIT) {
7826 /* calculate c1 and c2 for possible match of 1st char
7827 * following curly */
7828 ST.c1 = ST.c2 = CHRTEST_VOID;
7830 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7831 regnode *text_node = ST.B;
7832 if (! HAS_TEXT(text_node))
7833 FIND_NEXT_IMPT(text_node);
7836 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7838 But the former is redundant in light of the latter.
7840 if this changes back then the macro for
7841 IS_TEXT and friends need to change.
7843 if (PL_regkind[OP(text_node)] == EXACT) {
7844 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7845 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7855 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%" IVdf "...\n",
7856 depth, (IV)ST.count)
7858 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7859 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7860 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7861 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7863 /* simulate B failing */
7865 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%" UVXf " c1=0x%" UVXf " c2=0x%" UVXf "\n",
7867 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7868 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7869 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7871 state_num = CURLYM_B_fail;
7872 goto reenter_switch;
7875 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7876 /* simulate B failing */
7878 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7880 (int) nextchr, ST.c1, ST.c2)
7882 state_num = CURLYM_B_fail;
7883 goto reenter_switch;
7888 /* emulate CLOSE: mark current A as captured */
7889 I32 paren = ST.me->flags;
7891 rex->offs[paren].start
7892 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7893 rex->offs[paren].end = locinput - reginfo->strbeg;
7894 if ((U32)paren > rex->lastparen)
7895 rex->lastparen = paren;
7896 rex->lastcloseparen = paren;
7899 rex->offs[paren].end = -1;
7901 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7910 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7911 NOT_REACHED; /* NOTREACHED */
7913 case CURLYM_B_fail: /* just failed to match a B */
7914 REGCP_UNWIND(ST.cp);
7915 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7917 I32 max = ARG2(ST.me);
7918 if (max != REG_INFTY && ST.count == max)
7920 goto curlym_do_A; /* try to match a further A */
7922 /* backtrack one A */
7923 if (ST.count == ARG1(ST.me) /* min */)
7926 SET_locinput(HOPc(locinput, -ST.alen));
7927 goto curlym_do_B; /* try to match B */
7930 #define ST st->u.curly
7932 #define CURLY_SETPAREN(paren, success) \
7935 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7936 rex->offs[paren].end = locinput - reginfo->strbeg; \
7937 if (paren > rex->lastparen) \
7938 rex->lastparen = paren; \
7939 rex->lastcloseparen = paren; \
7942 rex->offs[paren].end = -1; \
7943 rex->lastparen = ST.lastparen; \
7944 rex->lastcloseparen = ST.lastcloseparen; \
7948 case STAR: /* /A*B/ where A is width 1 char */
7952 scan = NEXTOPER(scan);
7955 case PLUS: /* /A+B/ where A is width 1 char */
7959 scan = NEXTOPER(scan);
7962 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7963 ST.paren = scan->flags; /* Which paren to set */
7964 ST.lastparen = rex->lastparen;
7965 ST.lastcloseparen = rex->lastcloseparen;
7966 if (ST.paren > maxopenparen)
7967 maxopenparen = ST.paren;
7968 ST.min = ARG1(scan); /* min to match */
7969 ST.max = ARG2(scan); /* max to match */
7970 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
7975 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7978 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7980 ST.min = ARG1(scan); /* min to match */
7981 ST.max = ARG2(scan); /* max to match */
7982 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7985 * Lookahead to avoid useless match attempts
7986 * when we know what character comes next.
7988 * Used to only do .*x and .*?x, but now it allows
7989 * for )'s, ('s and (?{ ... })'s to be in the way
7990 * of the quantifier and the EXACT-like node. -- japhy
7993 assert(ST.min <= ST.max);
7994 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7995 ST.c1 = ST.c2 = CHRTEST_VOID;
7998 regnode *text_node = next;
8000 if (! HAS_TEXT(text_node))
8001 FIND_NEXT_IMPT(text_node);
8003 if (! HAS_TEXT(text_node))
8004 ST.c1 = ST.c2 = CHRTEST_VOID;
8006 if ( PL_regkind[OP(text_node)] != EXACT ) {
8007 ST.c1 = ST.c2 = CHRTEST_VOID;
8011 /* Currently we only get here when
8013 PL_rekind[OP(text_node)] == EXACT
8015 if this changes back then the macro for IS_TEXT and
8016 friends need to change. */
8017 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8018 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8030 char *li = locinput;
8033 regrepeat(rex, &li, ST.A, reginfo, ST.min)
8039 if (ST.c1 == CHRTEST_VOID)
8040 goto curly_try_B_min;
8042 ST.oldloc = locinput;
8044 /* set ST.maxpos to the furthest point along the
8045 * string that could possibly match */
8046 if (ST.max == REG_INFTY) {
8047 ST.maxpos = reginfo->strend - 1;
8049 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
8052 else if (utf8_target) {
8053 int m = ST.max - ST.min;
8054 for (ST.maxpos = locinput;
8055 m >0 && ST.maxpos < reginfo->strend; m--)
8056 ST.maxpos += UTF8SKIP(ST.maxpos);
8059 ST.maxpos = locinput + ST.max - ST.min;
8060 if (ST.maxpos >= reginfo->strend)
8061 ST.maxpos = reginfo->strend - 1;
8063 goto curly_try_B_min_known;
8067 /* avoid taking address of locinput, so it can remain
8069 char *li = locinput;
8070 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max);
8071 if (ST.count < ST.min)
8074 if ((ST.count > ST.min)
8075 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
8077 /* A{m,n} must come at the end of the string, there's
8078 * no point in backing off ... */
8080 /* ...except that $ and \Z can match before *and* after
8081 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8082 We may back off by one in this case. */
8083 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8087 goto curly_try_B_max;
8089 NOT_REACHED; /* NOTREACHED */
8091 case CURLY_B_min_known_fail:
8092 /* failed to find B in a non-greedy match where c1,c2 valid */
8094 REGCP_UNWIND(ST.cp);
8096 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8098 /* Couldn't or didn't -- move forward. */
8099 ST.oldloc = locinput;
8101 locinput += UTF8SKIP(locinput);
8105 curly_try_B_min_known:
8106 /* find the next place where 'B' could work, then call B */
8110 n = (ST.oldloc == locinput) ? 0 : 1;
8111 if (ST.c1 == ST.c2) {
8112 /* set n to utf8_distance(oldloc, locinput) */
8113 while (locinput <= ST.maxpos
8114 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8116 locinput += UTF8SKIP(locinput);
8121 /* set n to utf8_distance(oldloc, locinput) */
8122 while (locinput <= ST.maxpos
8123 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8124 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8126 locinput += UTF8SKIP(locinput);
8131 else { /* Not utf8_target */
8132 if (ST.c1 == ST.c2) {
8133 while (locinput <= ST.maxpos &&
8134 UCHARAT(locinput) != ST.c1)
8138 while (locinput <= ST.maxpos
8139 && UCHARAT(locinput) != ST.c1
8140 && UCHARAT(locinput) != ST.c2)
8143 n = locinput - ST.oldloc;
8145 if (locinput > ST.maxpos)
8148 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8149 * at b; check that everything between oldloc and
8150 * locinput matches */
8151 char *li = ST.oldloc;
8153 if (regrepeat(rex, &li, ST.A, reginfo, n) < n)
8155 assert(n == REG_INFTY || locinput == li);
8157 CURLY_SETPAREN(ST.paren, ST.count);
8158 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8160 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8162 NOT_REACHED; /* NOTREACHED */
8164 case CURLY_B_min_fail:
8165 /* failed to find B in a non-greedy match where c1,c2 invalid */
8167 REGCP_UNWIND(ST.cp);
8169 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8171 /* failed -- move forward one */
8173 char *li = locinput;
8174 if (!regrepeat(rex, &li, ST.A, reginfo, 1)) {
8181 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8182 ST.count > 0)) /* count overflow ? */
8185 CURLY_SETPAREN(ST.paren, ST.count);
8186 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8188 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8192 NOT_REACHED; /* NOTREACHED */
8195 /* a successful greedy match: now try to match B */
8196 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8199 bool could_match = locinput < reginfo->strend;
8201 /* If it could work, try it. */
8202 if (ST.c1 != CHRTEST_VOID && could_match) {
8203 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8205 could_match = memEQ(locinput,
8210 UTF8SKIP(locinput));
8213 could_match = UCHARAT(locinput) == ST.c1
8214 || UCHARAT(locinput) == ST.c2;
8217 if (ST.c1 == CHRTEST_VOID || could_match) {
8218 CURLY_SETPAREN(ST.paren, ST.count);
8219 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8220 NOT_REACHED; /* NOTREACHED */
8225 case CURLY_B_max_fail:
8226 /* failed to find B in a greedy match */
8228 REGCP_UNWIND(ST.cp);
8230 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8233 if (--ST.count < ST.min)
8235 locinput = HOPc(locinput, -1);
8236 goto curly_try_B_max;
8240 case END: /* last op of main pattern */
8243 /* we've just finished A in /(??{A})B/; now continue with B */
8244 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8245 st->u.eval.prev_rex = rex_sv; /* inner */
8247 /* Save *all* the positions. */
8248 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8249 rex_sv = CUR_EVAL.prev_rex;
8250 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8251 SET_reg_curpm(rex_sv);
8252 rex = ReANY(rex_sv);
8253 rexi = RXi_GET(rex);
8255 st->u.eval.prev_curlyx = cur_curlyx;
8256 cur_curlyx = CUR_EVAL.prev_curlyx;
8258 REGCP_SET(st->u.eval.lastcp);
8260 /* Restore parens of the outer rex without popping the
8262 regcp_restore(rex, CUR_EVAL.lastcp, &maxopenparen);
8264 st->u.eval.prev_eval = cur_eval;
8265 cur_eval = CUR_EVAL.prev_eval;
8267 Perl_re_exec_indentf( aTHX_ "EVAL trying tail ... (cur_eval=%p)\n",
8269 if ( nochange_depth )
8272 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8274 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, st->u.eval.prev_eval->u.eval.B,
8275 locinput); /* match B */
8278 if (locinput < reginfo->till) {
8279 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8280 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8282 (long)(locinput - startpos),
8283 (long)(reginfo->till - startpos),
8286 sayNO_SILENT; /* Cannot match: too short. */
8288 sayYES; /* Success! */
8290 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8292 Perl_re_exec_indentf( aTHX_ "%ssubpattern success...%s\n",
8293 depth, PL_colors[4], PL_colors[5]));
8294 sayYES; /* Success! */
8297 #define ST st->u.ifmatch
8302 case SUSPEND: /* (?>A) */
8304 newstart = locinput;
8307 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8309 goto ifmatch_trivial_fail_test;
8311 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8313 ifmatch_trivial_fail_test:
8315 char * const s = HOPBACKc(locinput, scan->flags);
8320 sw = 1 - cBOOL(ST.wanted);
8324 next = scan + ARG(scan);
8332 newstart = locinput;
8336 ST.logical = logical;
8337 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8339 /* execute body of (?...A) */
8340 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8341 NOT_REACHED; /* NOTREACHED */
8344 case IFMATCH_A_fail: /* body of (?...A) failed */
8345 ST.wanted = !ST.wanted;
8348 case IFMATCH_A: /* body of (?...A) succeeded */
8350 sw = cBOOL(ST.wanted);
8352 else if (!ST.wanted)
8355 if (OP(ST.me) != SUSPEND) {
8356 /* restore old position except for (?>...) */
8357 locinput = st->locinput;
8359 scan = ST.me + ARG(ST.me);
8362 continue; /* execute B */
8366 case LONGJMP: /* alternative with many branches compiles to
8367 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8368 next = scan + ARG(scan);
8373 case COMMIT: /* (*COMMIT) */
8374 reginfo->cutpoint = reginfo->strend;
8377 case PRUNE: /* (*PRUNE) */
8379 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8380 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8381 NOT_REACHED; /* NOTREACHED */
8383 case COMMIT_next_fail:
8387 NOT_REACHED; /* NOTREACHED */
8389 case OPFAIL: /* (*FAIL) */
8391 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8393 /* deal with (?(?!)X|Y) properly,
8394 * make sure we trigger the no branch
8395 * of the trailing IFTHEN structure*/
8401 NOT_REACHED; /* NOTREACHED */
8403 #define ST st->u.mark
8404 case MARKPOINT: /* (*MARK:foo) */
8405 ST.prev_mark = mark_state;
8406 ST.mark_name = sv_commit = sv_yes_mark
8407 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8409 ST.mark_loc = locinput;
8410 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8411 NOT_REACHED; /* NOTREACHED */
8413 case MARKPOINT_next:
8414 mark_state = ST.prev_mark;
8416 NOT_REACHED; /* NOTREACHED */
8418 case MARKPOINT_next_fail:
8419 if (popmark && sv_eq(ST.mark_name,popmark))
8421 if (ST.mark_loc > startpoint)
8422 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8423 popmark = NULL; /* we found our mark */
8424 sv_commit = ST.mark_name;
8427 Perl_re_exec_indentf( aTHX_ "%ssetting cutpoint to mark:%" SVf "...%s\n",
8429 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8432 mark_state = ST.prev_mark;
8433 sv_yes_mark = mark_state ?
8434 mark_state->u.mark.mark_name : NULL;
8436 NOT_REACHED; /* NOTREACHED */
8438 case SKIP: /* (*SKIP) */
8440 /* (*SKIP) : if we fail we cut here*/
8441 ST.mark_name = NULL;
8442 ST.mark_loc = locinput;
8443 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8445 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8446 otherwise do nothing. Meaning we need to scan
8448 regmatch_state *cur = mark_state;
8449 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8452 if ( sv_eq( cur->u.mark.mark_name,
8455 ST.mark_name = find;
8456 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8458 cur = cur->u.mark.prev_mark;
8461 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8464 case SKIP_next_fail:
8466 /* (*CUT:NAME) - Set up to search for the name as we
8467 collapse the stack*/
8468 popmark = ST.mark_name;
8470 /* (*CUT) - No name, we cut here.*/
8471 if (ST.mark_loc > startpoint)
8472 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8473 /* but we set sv_commit to latest mark_name if there
8474 is one so they can test to see how things lead to this
8477 sv_commit=mark_state->u.mark.mark_name;
8481 NOT_REACHED; /* NOTREACHED */
8484 case LNBREAK: /* \R */
8485 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8492 PerlIO_printf(Perl_error_log, "%" UVxf " %d\n",
8493 PTR2UV(scan), OP(scan));
8494 Perl_croak(aTHX_ "regexp memory corruption");
8496 /* this is a point to jump to in order to increment
8497 * locinput by one character */
8499 assert(!NEXTCHR_IS_EOS);
8501 locinput += PL_utf8skip[nextchr];
8502 /* locinput is allowed to go 1 char off the end (signifying
8503 * EOS), but not 2+ */
8504 if (locinput > reginfo->strend)
8513 /* switch break jumps here */
8514 scan = next; /* prepare to execute the next op and ... */
8515 continue; /* ... jump back to the top, reusing st */
8519 /* push a state that backtracks on success */
8520 st->u.yes.prev_yes_state = yes_state;
8524 /* push a new regex state, then continue at scan */
8526 regmatch_state *newst;
8529 regmatch_state *cur = st;
8530 regmatch_state *curyes = yes_state;
8532 regmatch_slab *slab = PL_regmatch_slab;
8533 for (i = 0; i < 3 && i <= depth; cur--,i++) {
8534 if (cur < SLAB_FIRST(slab)) {
8536 cur = SLAB_LAST(slab);
8538 Perl_re_exec_indentf( aTHX_ "%4s #%-3d %-10s %s\n",
8541 depth - i, PL_reg_name[cur->resume_state],
8542 (curyes == cur) ? "yes" : ""
8545 curyes = cur->u.yes.prev_yes_state;
8548 DEBUG_STATE_pp("push")
8551 st->locinput = locinput;
8553 if (newst > SLAB_LAST(PL_regmatch_slab))
8554 newst = S_push_slab(aTHX);
8555 PL_regmatch_state = newst;
8557 locinput = pushinput;
8563 #ifdef SOLARIS_BAD_OPTIMIZER
8564 # undef PL_charclass
8568 * We get here only if there's trouble -- normally "case END" is
8569 * the terminating point.
8571 Perl_croak(aTHX_ "corrupted regexp pointers");
8572 NOT_REACHED; /* NOTREACHED */
8576 /* we have successfully completed a subexpression, but we must now
8577 * pop to the state marked by yes_state and continue from there */
8578 assert(st != yes_state);
8580 while (st != yes_state) {
8582 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8583 PL_regmatch_slab = PL_regmatch_slab->prev;
8584 st = SLAB_LAST(PL_regmatch_slab);
8588 DEBUG_STATE_pp("pop (no final)");
8590 DEBUG_STATE_pp("pop (yes)");
8596 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8597 || yes_state > SLAB_LAST(PL_regmatch_slab))
8599 /* not in this slab, pop slab */
8600 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8601 PL_regmatch_slab = PL_regmatch_slab->prev;
8602 st = SLAB_LAST(PL_regmatch_slab);
8604 depth -= (st - yes_state);
8607 yes_state = st->u.yes.prev_yes_state;
8608 PL_regmatch_state = st;
8611 locinput= st->locinput;
8612 state_num = st->resume_state + no_final;
8613 goto reenter_switch;
8616 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
8617 PL_colors[4], PL_colors[5]));
8619 if (reginfo->info_aux_eval) {
8620 /* each successfully executed (?{...}) block does the equivalent of
8621 * local $^R = do {...}
8622 * When popping the save stack, all these locals would be undone;
8623 * bypass this by setting the outermost saved $^R to the latest
8625 /* I dont know if this is needed or works properly now.
8626 * see code related to PL_replgv elsewhere in this file.
8629 if (oreplsv != GvSV(PL_replgv))
8630 sv_setsv(oreplsv, GvSV(PL_replgv));
8637 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
8639 PL_colors[4], PL_colors[5])
8651 /* there's a previous state to backtrack to */
8653 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8654 PL_regmatch_slab = PL_regmatch_slab->prev;
8655 st = SLAB_LAST(PL_regmatch_slab);
8657 PL_regmatch_state = st;
8658 locinput= st->locinput;
8660 DEBUG_STATE_pp("pop");
8662 if (yes_state == st)
8663 yes_state = st->u.yes.prev_yes_state;
8665 state_num = st->resume_state + 1; /* failure = success + 1 */
8667 goto reenter_switch;
8672 if (rex->intflags & PREGf_VERBARG_SEEN) {
8673 SV *sv_err = get_sv("REGERROR", 1);
8674 SV *sv_mrk = get_sv("REGMARK", 1);
8676 sv_commit = &PL_sv_no;
8678 sv_yes_mark = &PL_sv_yes;
8681 sv_commit = &PL_sv_yes;
8682 sv_yes_mark = &PL_sv_no;
8686 sv_setsv(sv_err, sv_commit);
8687 sv_setsv(sv_mrk, sv_yes_mark);
8691 if (last_pushed_cv) {
8693 /* see "Some notes about MULTICALL" above */
8695 PERL_UNUSED_VAR(SP);
8698 LEAVE_SCOPE(orig_savestack_ix);
8700 assert(!result || locinput - reginfo->strbeg >= 0);
8701 return result ? locinput - reginfo->strbeg : -1;
8705 - regrepeat - repeatedly match something simple, report how many
8707 * What 'simple' means is a node which can be the operand of a quantifier like
8710 * startposp - pointer a pointer to the start position. This is updated
8711 * to point to the byte following the highest successful
8713 * p - the regnode to be repeatedly matched against.
8714 * reginfo - struct holding match state, such as strend
8715 * max - maximum number of things to match.
8716 * depth - (for debugging) backtracking depth.
8719 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8720 regmatch_info *const reginfo, I32 max _pDEPTH)
8722 char *scan; /* Pointer to current position in target string */
8724 char *loceol = reginfo->strend; /* local version */
8725 I32 hardcount = 0; /* How many matches so far */
8726 bool utf8_target = reginfo->is_utf8_target;
8727 unsigned int to_complement = 0; /* Invert the result? */
8729 _char_class_number classnum;
8731 PERL_ARGS_ASSERT_REGREPEAT;
8734 if (max == REG_INFTY)
8736 else if (! utf8_target && loceol - scan > max)
8737 loceol = scan + max;
8739 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8740 * to the maximum of how far we should go in it (leaving it set to the real
8741 * end, if the maximum permissible would take us beyond that). This allows
8742 * us to make the loop exit condition that we haven't gone past <loceol> to
8743 * also mean that we haven't exceeded the max permissible count, saving a
8744 * test each time through the loop. But it assumes that the OP matches a
8745 * single byte, which is true for most of the OPs below when applied to a
8746 * non-UTF-8 target. Those relatively few OPs that don't have this
8747 * characteristic will have to compensate.
8749 * There is no adjustment for UTF-8 targets, as the number of bytes per
8750 * character varies. OPs will have to test both that the count is less
8751 * than the max permissible (using <hardcount> to keep track), and that we
8752 * are still within the bounds of the string (using <loceol>. A few OPs
8753 * match a single byte no matter what the encoding. They can omit the max
8754 * test if, for the UTF-8 case, they do the adjustment that was skipped
8757 * Thus, the code above sets things up for the common case; and exceptional
8758 * cases need extra work; the common case is to make sure <scan> doesn't
8759 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8760 * count doesn't exceed the maximum permissible */
8765 while (scan < loceol && hardcount < max && *scan != '\n') {
8766 scan += UTF8SKIP(scan);
8770 while (scan < loceol && *scan != '\n')
8776 while (scan < loceol && hardcount < max) {
8777 scan += UTF8SKIP(scan);
8785 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8786 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8787 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8791 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8795 /* Can use a simple loop if the pattern char to match on is invariant
8796 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8797 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8798 * true iff it doesn't matter if the argument is in UTF-8 or not */
8799 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8800 if (utf8_target && loceol - scan > max) {
8801 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8802 * since here, to match at all, 1 char == 1 byte */
8803 loceol = scan + max;
8805 while (scan < loceol && UCHARAT(scan) == c) {
8809 else if (reginfo->is_utf8_pat) {
8811 STRLEN scan_char_len;
8813 /* When both target and pattern are UTF-8, we have to do
8815 while (hardcount < max
8817 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8818 && memEQ(scan, STRING(p), scan_char_len))
8820 scan += scan_char_len;
8824 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8826 /* Target isn't utf8; convert the character in the UTF-8
8827 * pattern to non-UTF8, and do a simple loop */
8828 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8829 while (scan < loceol && UCHARAT(scan) == c) {
8832 } /* else pattern char is above Latin1, can't possibly match the
8837 /* Here, the string must be utf8; pattern isn't, and <c> is
8838 * different in utf8 than not, so can't compare them directly.
8839 * Outside the loop, find the two utf8 bytes that represent c, and
8840 * then look for those in sequence in the utf8 string */
8841 U8 high = UTF8_TWO_BYTE_HI(c);
8842 U8 low = UTF8_TWO_BYTE_LO(c);
8844 while (hardcount < max
8845 && scan + 1 < loceol
8846 && UCHARAT(scan) == high
8847 && UCHARAT(scan + 1) == low)
8855 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8856 assert(! reginfo->is_utf8_pat);
8859 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8863 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8864 utf8_flags = FOLDEQ_LOCALE;
8867 case EXACTF: /* This node only generated for non-utf8 patterns */
8868 assert(! reginfo->is_utf8_pat);
8873 if (! utf8_target) {
8876 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8877 | FOLDEQ_S2_FOLDS_SANE;
8882 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8886 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8888 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8890 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8893 if (c1 == CHRTEST_VOID) {
8894 /* Use full Unicode fold matching */
8895 char *tmpeol = reginfo->strend;
8896 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8897 while (hardcount < max
8898 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8899 STRING(p), NULL, pat_len,
8900 reginfo->is_utf8_pat, utf8_flags))
8903 tmpeol = reginfo->strend;
8907 else if (utf8_target) {
8909 while (scan < loceol
8911 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8913 scan += UTF8SKIP(scan);
8918 while (scan < loceol
8920 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8921 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8923 scan += UTF8SKIP(scan);
8928 else if (c1 == c2) {
8929 while (scan < loceol && UCHARAT(scan) == c1) {
8934 while (scan < loceol &&
8935 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8944 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8946 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8947 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8953 while (hardcount < max
8955 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8957 scan += UTF8SKIP(scan);
8961 else if (ANYOF_FLAGS(p)) {
8962 while (scan < loceol
8963 && reginclass(prog, p, (U8*)scan, (U8*)scan+1, 0))
8967 while (scan < loceol && ANYOF_BITMAP_TEST(p, *((U8*)scan)))
8972 /* The argument (FLAGS) to all the POSIX node types is the class number */
8979 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8980 if (! utf8_target) {
8981 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8987 while (hardcount < max && scan < loceol
8988 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8991 scan += UTF8SKIP(scan);
9004 if (utf8_target && loceol - scan > max) {
9006 /* We didn't adjust <loceol> at the beginning of this routine
9007 * because is UTF-8, but it is actually ok to do so, since here, to
9008 * match, 1 char == 1 byte. */
9009 loceol = scan + max;
9011 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
9024 if (! utf8_target) {
9025 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
9031 /* The complement of something that matches only ASCII matches all
9032 * non-ASCII, plus everything in ASCII that isn't in the class. */
9033 while (hardcount < max && scan < loceol
9034 && ( ! isASCII_utf8_safe(scan, reginfo->strend)
9035 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
9037 scan += UTF8SKIP(scan);
9048 if (! utf8_target) {
9049 while (scan < loceol && to_complement
9050 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
9057 classnum = (_char_class_number) FLAGS(p);
9058 if (classnum < _FIRST_NON_SWASH_CC) {
9060 /* Here, a swash is needed for above-Latin1 code points.
9061 * Process as many Latin1 code points using the built-in rules.
9062 * Go to another loop to finish processing upon encountering
9063 * the first Latin1 code point. We could do that in this loop
9064 * as well, but the other way saves having to test if the swash
9065 * has been loaded every time through the loop: extra space to
9067 while (hardcount < max && scan < loceol) {
9068 if (UTF8_IS_INVARIANT(*scan)) {
9069 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
9076 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
9077 if (! (to_complement
9078 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
9087 goto found_above_latin1;
9094 /* For these character classes, the knowledge of how to handle
9095 * every code point is compiled in to Perl via a macro. This
9096 * code is written for making the loops as tight as possible.
9097 * It could be refactored to save space instead */
9099 case _CC_ENUM_SPACE:
9100 while (hardcount < max
9103 ^ cBOOL(isSPACE_utf8_safe(scan, loceol))))
9105 scan += UTF8SKIP(scan);
9109 case _CC_ENUM_BLANK:
9110 while (hardcount < max
9113 ^ cBOOL(isBLANK_utf8_safe(scan, loceol))))
9115 scan += UTF8SKIP(scan);
9119 case _CC_ENUM_XDIGIT:
9120 while (hardcount < max
9123 ^ cBOOL(isXDIGIT_utf8_safe(scan, loceol))))
9125 scan += UTF8SKIP(scan);
9129 case _CC_ENUM_VERTSPACE:
9130 while (hardcount < max
9133 ^ cBOOL(isVERTWS_utf8_safe(scan, loceol))))
9135 scan += UTF8SKIP(scan);
9139 case _CC_ENUM_CNTRL:
9140 while (hardcount < max
9143 ^ cBOOL(isCNTRL_utf8_safe(scan, loceol))))
9145 scan += UTF8SKIP(scan);
9150 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
9156 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
9158 /* Load the swash if not already present */
9159 if (! PL_utf8_swash_ptrs[classnum]) {
9160 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
9161 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
9165 PL_XPosix_ptrs[classnum], &flags);
9168 while (hardcount < max && scan < loceol
9169 && to_complement ^ cBOOL(_generic_utf8_safe(
9173 swash_fetch(PL_utf8_swash_ptrs[classnum],
9177 scan += UTF8SKIP(scan);
9184 while (hardcount < max && scan < loceol &&
9185 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9190 /* LNBREAK can match one or two latin chars, which is ok, but we
9191 * have to use hardcount in this situation, and throw away the
9192 * adjustment to <loceol> done before the switch statement */
9193 loceol = reginfo->strend;
9194 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9203 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9217 /* These are all 0 width, so match right here or not at all. */
9221 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9222 NOT_REACHED; /* NOTREACHED */
9229 c = scan - *startposp;
9233 GET_RE_DEBUG_FLAGS_DECL;
9235 SV * const prop = sv_newmortal();
9236 regprop(prog, prop, p, reginfo, NULL);
9237 Perl_re_exec_indentf( aTHX_ "%s can match %" IVdf " times out of %" IVdf "...\n",
9238 depth, SvPVX_const(prop),(IV)c,(IV)max);
9246 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9248 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9249 create a copy so that changes the caller makes won't change the shared one.
9250 If <altsvp> is non-null, will return NULL in it, for back-compat.
9253 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9255 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9261 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9264 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9267 - reginclass - determine if a character falls into a character class
9269 n is the ANYOF-type regnode
9270 p is the target string
9271 p_end points to one byte beyond the end of the target string
9272 utf8_target tells whether p is in UTF-8.
9274 Returns true if matched; false otherwise.
9276 Note that this can be a synthetic start class, a combination of various
9277 nodes, so things you think might be mutually exclusive, such as locale,
9278 aren't. It can match both locale and non-locale
9283 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9286 const char flags = ANYOF_FLAGS(n);
9290 PERL_ARGS_ASSERT_REGINCLASS;
9292 /* If c is not already the code point, get it. Note that
9293 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9294 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9296 const U32 utf8n_flags = UTF8_ALLOW_DEFAULT;
9297 c = utf8n_to_uvchr(p, p_end - p, &c_len, utf8n_flags | UTF8_CHECK_ONLY);
9298 if (c_len == (STRLEN)-1) {
9299 _force_out_malformed_utf8_message(p, p_end,
9301 1 /* 1 means die */ );
9302 NOT_REACHED; /* NOTREACHED */
9304 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9305 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9309 /* If this character is potentially in the bitmap, check it */
9310 if (c < NUM_ANYOF_CODE_POINTS) {
9311 if (ANYOF_BITMAP_TEST(n, c))
9314 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9321 else if (flags & ANYOF_LOCALE_FLAGS) {
9322 if ((flags & ANYOFL_FOLD)
9324 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9328 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9332 /* The data structure is arranged so bits 0, 2, 4, ... are set
9333 * if the class includes the Posix character class given by
9334 * bit/2; and 1, 3, 5, ... are set if the class includes the
9335 * complemented Posix class given by int(bit/2). So we loop
9336 * through the bits, each time changing whether we complement
9337 * the result or not. Suppose for the sake of illustration
9338 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9339 * is set, it means there is a match for this ANYOF node if the
9340 * character is in the class given by the expression (0 / 2 = 0
9341 * = \w). If it is in that class, isFOO_lc() will return 1,
9342 * and since 'to_complement' is 0, the result will stay TRUE,
9343 * and we exit the loop. Suppose instead that bit 0 is 0, but
9344 * bit 1 is 1. That means there is a match if the character
9345 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9346 * but will on bit 1. On the second iteration 'to_complement'
9347 * will be 1, so the exclusive or will reverse things, so we
9348 * are testing for \W. On the third iteration, 'to_complement'
9349 * will be 0, and we would be testing for \s; the fourth
9350 * iteration would test for \S, etc.
9352 * Note that this code assumes that all the classes are closed
9353 * under folding. For example, if a character matches \w, then
9354 * its fold does too; and vice versa. This should be true for
9355 * any well-behaved locale for all the currently defined Posix
9356 * classes, except for :lower: and :upper:, which are handled
9357 * by the pseudo-class :cased: which matches if either of the
9358 * other two does. To get rid of this assumption, an outer
9359 * loop could be used below to iterate over both the source
9360 * character, and its fold (if different) */
9363 int to_complement = 0;
9365 while (count < ANYOF_MAX) {
9366 if (ANYOF_POSIXL_TEST(n, count)
9367 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9380 /* If the bitmap didn't (or couldn't) match, and something outside the
9381 * bitmap could match, try that. */
9383 if (c >= NUM_ANYOF_CODE_POINTS
9384 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9386 match = TRUE; /* Everything above the bitmap matches */
9388 /* Here doesn't match everything above the bitmap. If there is
9389 * some information available beyond the bitmap, we may find a
9390 * match in it. If so, this is most likely because the code point
9391 * is outside the bitmap range. But rarely, it could be because of
9392 * some other reason. If so, various flags are set to indicate
9393 * this possibility. On ANYOFD nodes, there may be matches that
9394 * happen only when the target string is UTF-8; or for other node
9395 * types, because runtime lookup is needed, regardless of the
9396 * UTF-8ness of the target string. Finally, under /il, there may
9397 * be some matches only possible if the locale is a UTF-8 one. */
9398 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9399 && ( c >= NUM_ANYOF_CODE_POINTS
9400 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9401 && ( UNLIKELY(OP(n) != ANYOFD)
9402 || (utf8_target && ! isASCII_uni(c)
9403 # if NUM_ANYOF_CODE_POINTS > 256
9407 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9408 && IN_UTF8_CTYPE_LOCALE)))
9410 SV* only_utf8_locale = NULL;
9411 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9412 &only_utf8_locale, NULL);
9418 } else { /* Convert to utf8 */
9419 utf8_p = utf8_buffer;
9420 append_utf8_from_native_byte(*p, &utf8_p);
9421 utf8_p = utf8_buffer;
9424 if (swash_fetch(sw, utf8_p, TRUE)) {
9428 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9429 match = _invlist_contains_cp(only_utf8_locale, c);
9433 if (UNICODE_IS_SUPER(c)
9435 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9437 && ckWARN_d(WARN_NON_UNICODE))
9439 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9440 "Matched non-Unicode code point 0x%04" UVXf " against Unicode property; may not be portable", c);
9444 #if ANYOF_INVERT != 1
9445 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9447 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9450 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9451 return (flags & ANYOF_INVERT) ^ match;
9455 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9457 /* return the position 'off' UTF-8 characters away from 's', forward if
9458 * 'off' >= 0, backwards if negative. But don't go outside of position
9459 * 'lim', which better be < s if off < 0 */
9461 PERL_ARGS_ASSERT_REGHOP3;
9464 while (off-- && s < lim) {
9465 /* XXX could check well-formedness here */
9470 while (off++ && s > lim) {
9472 if (UTF8_IS_CONTINUED(*s)) {
9473 while (s > lim && UTF8_IS_CONTINUATION(*s))
9475 if (! UTF8_IS_START(*s)) {
9476 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9479 /* XXX could check well-formedness here */
9486 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9488 PERL_ARGS_ASSERT_REGHOP4;
9491 while (off-- && s < rlim) {
9492 /* XXX could check well-formedness here */
9497 while (off++ && s > llim) {
9499 if (UTF8_IS_CONTINUED(*s)) {
9500 while (s > llim && UTF8_IS_CONTINUATION(*s))
9502 if (! UTF8_IS_START(*s)) {
9503 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9506 /* XXX could check well-formedness here */
9512 /* like reghop3, but returns NULL on overrun, rather than returning last
9516 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9518 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9521 while (off-- && s < lim) {
9522 /* XXX could check well-formedness here */
9529 while (off++ && s > lim) {
9531 if (UTF8_IS_CONTINUED(*s)) {
9532 while (s > lim && UTF8_IS_CONTINUATION(*s))
9534 if (! UTF8_IS_START(*s)) {
9535 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9538 /* XXX could check well-formedness here */
9547 /* when executing a regex that may have (?{}), extra stuff needs setting
9548 up that will be visible to the called code, even before the current
9549 match has finished. In particular:
9551 * $_ is localised to the SV currently being matched;
9552 * pos($_) is created if necessary, ready to be updated on each call-out
9554 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9555 isn't set until the current pattern is successfully finished), so that
9556 $1 etc of the match-so-far can be seen;
9557 * save the old values of subbeg etc of the current regex, and set then
9558 to the current string (again, this is normally only done at the end
9563 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9566 regexp *const rex = ReANY(reginfo->prog);
9567 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9569 eval_state->rex = rex;
9572 /* Make $_ available to executed code. */
9573 if (reginfo->sv != DEFSV) {
9575 DEFSV_set(reginfo->sv);
9578 if (!(mg = mg_find_mglob(reginfo->sv))) {
9579 /* prepare for quick setting of pos */
9580 mg = sv_magicext_mglob(reginfo->sv);
9583 eval_state->pos_magic = mg;
9584 eval_state->pos = mg->mg_len;
9585 eval_state->pos_flags = mg->mg_flags;
9588 eval_state->pos_magic = NULL;
9590 if (!PL_reg_curpm) {
9591 /* PL_reg_curpm is a fake PMOP that we can attach the current
9592 * regex to and point PL_curpm at, so that $1 et al are visible
9593 * within a /(?{})/. It's just allocated once per interpreter the
9594 * first time its needed */
9595 Newxz(PL_reg_curpm, 1, PMOP);
9598 SV* const repointer = &PL_sv_undef;
9599 /* this regexp is also owned by the new PL_reg_curpm, which
9600 will try to free it. */
9601 av_push(PL_regex_padav, repointer);
9602 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9603 PL_regex_pad = AvARRAY(PL_regex_padav);
9607 SET_reg_curpm(reginfo->prog);
9608 eval_state->curpm = PL_curpm;
9609 PL_curpm_under = PL_curpm;
9610 PL_curpm = PL_reg_curpm;
9611 if (RXp_MATCH_COPIED(rex)) {
9612 /* Here is a serious problem: we cannot rewrite subbeg,
9613 since it may be needed if this match fails. Thus
9614 $` inside (?{}) could fail... */
9615 eval_state->subbeg = rex->subbeg;
9616 eval_state->sublen = rex->sublen;
9617 eval_state->suboffset = rex->suboffset;
9618 eval_state->subcoffset = rex->subcoffset;
9620 eval_state->saved_copy = rex->saved_copy;
9622 RXp_MATCH_COPIED_off(rex);
9625 eval_state->subbeg = NULL;
9626 rex->subbeg = (char *)reginfo->strbeg;
9628 rex->subcoffset = 0;
9629 rex->sublen = reginfo->strend - reginfo->strbeg;
9633 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9636 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9638 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9639 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9642 Safefree(aux->poscache);
9646 /* undo the effects of S_setup_eval_state() */
9648 if (eval_state->subbeg) {
9649 regexp * const rex = eval_state->rex;
9650 rex->subbeg = eval_state->subbeg;
9651 rex->sublen = eval_state->sublen;
9652 rex->suboffset = eval_state->suboffset;
9653 rex->subcoffset = eval_state->subcoffset;
9655 rex->saved_copy = eval_state->saved_copy;
9657 RXp_MATCH_COPIED_on(rex);
9659 if (eval_state->pos_magic)
9661 eval_state->pos_magic->mg_len = eval_state->pos;
9662 eval_state->pos_magic->mg_flags =
9663 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9664 | (eval_state->pos_flags & MGf_BYTES);
9667 PL_curpm = eval_state->curpm;
9670 PL_regmatch_state = aux->old_regmatch_state;
9671 PL_regmatch_slab = aux->old_regmatch_slab;
9673 /* free all slabs above current one - this must be the last action
9674 * of this function, as aux and eval_state are allocated within
9675 * slabs and may be freed here */
9677 s = PL_regmatch_slab->next;
9679 PL_regmatch_slab->next = NULL;
9681 regmatch_slab * const osl = s;
9690 S_to_utf8_substr(pTHX_ regexp *prog)
9692 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9693 * on the converted value */
9697 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9700 if (prog->substrs->data[i].substr
9701 && !prog->substrs->data[i].utf8_substr) {
9702 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9703 prog->substrs->data[i].utf8_substr = sv;
9704 sv_utf8_upgrade(sv);
9705 if (SvVALID(prog->substrs->data[i].substr)) {
9706 if (SvTAIL(prog->substrs->data[i].substr)) {
9707 /* Trim the trailing \n that fbm_compile added last
9709 SvCUR_set(sv, SvCUR(sv) - 1);
9710 /* Whilst this makes the SV technically "invalid" (as its
9711 buffer is no longer followed by "\0") when fbm_compile()
9712 adds the "\n" back, a "\0" is restored. */
9713 fbm_compile(sv, FBMcf_TAIL);
9717 if (prog->substrs->data[i].substr == prog->check_substr)
9718 prog->check_utf8 = sv;
9724 S_to_byte_substr(pTHX_ regexp *prog)
9726 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9727 * on the converted value; returns FALSE if can't be converted. */
9731 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9734 if (prog->substrs->data[i].utf8_substr
9735 && !prog->substrs->data[i].substr) {
9736 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9737 if (! sv_utf8_downgrade(sv, TRUE)) {
9740 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9741 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9742 /* Trim the trailing \n that fbm_compile added last
9744 SvCUR_set(sv, SvCUR(sv) - 1);
9745 fbm_compile(sv, FBMcf_TAIL);
9749 prog->substrs->data[i].substr = sv;
9750 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9751 prog->check_substr = sv;
9758 #ifndef PERL_IN_XSUB_RE
9761 Perl__is_grapheme(pTHX_ const U8 * strbeg, const U8 * s, const U8 * strend, const UV cp)
9763 /* Temporary helper function for toke.c. Verify that the code point 'cp'
9764 * is a stand-alone grapheme. The UTF-8 for 'cp' begins at position 's' in
9765 * the larger string bounded by 'strbeg' and 'strend'.
9767 * 'cp' needs to be assigned (if not a future version of the Unicode
9768 * Standard could make it something that combines with adjacent characters,
9769 * so code using it would then break), and there has to be a GCB break
9770 * before and after the character. */
9772 GCB_enum cp_gcb_val, prev_cp_gcb_val, next_cp_gcb_val;
9773 const U8 * prev_cp_start;
9775 PERL_ARGS_ASSERT__IS_GRAPHEME;
9777 /* Unassigned code points are forbidden */
9778 if (UNLIKELY(! ELEMENT_RANGE_MATCHES_INVLIST(
9779 _invlist_search(PL_Assigned_invlist, cp))))
9784 cp_gcb_val = getGCB_VAL_CP(cp);
9786 /* Find the GCB value of the previous code point in the input */
9787 prev_cp_start = utf8_hop_back(s, -1, strbeg);
9788 if (UNLIKELY(prev_cp_start == s)) {
9789 prev_cp_gcb_val = GCB_EDGE;
9792 prev_cp_gcb_val = getGCB_VAL_UTF8(prev_cp_start, strend);
9795 /* And check that is a grapheme boundary */
9796 if (! isGCB(prev_cp_gcb_val, cp_gcb_val, strbeg, s,
9797 TRUE /* is UTF-8 encoded */ ))
9802 /* Similarly verify there is a break between the current character and the
9806 next_cp_gcb_val = GCB_EDGE;
9809 next_cp_gcb_val = getGCB_VAL_UTF8(s, strend);
9812 return isGCB(cp_gcb_val, next_cp_gcb_val, strbeg, s, TRUE);
9820 * ex: set ts=8 sts=4 sw=4 et: