5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
40 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
41 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
44 * pregcomp and pregexec -- regsub and regerror are not used in perl
46 * Copyright (c) 1986 by University of Toronto.
47 * Written by Henry Spencer. Not derived from licensed software.
49 * Permission is granted to anyone to use this software for any
50 * purpose on any computer system, and to redistribute it freely,
51 * subject to the following restrictions:
53 * 1. The author is not responsible for the consequences of use of
54 * this software, no matter how awful, even if they arise
57 * 2. The origin of this software must not be misrepresented, either
58 * by explicit claim or by omission.
60 * 3. Altered versions must be plainly marked as such, and must not
61 * be misrepresented as being the original software.
63 **** Alterations to Henry's code are...
65 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
66 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
67 **** by Larry Wall and others
69 **** You may distribute under the terms of either the GNU General Public
70 **** License or the Artistic License, as specified in the README file.
72 * Beware that some of this code is subtly aware of the way operator
73 * precedence is structured in regular expressions. Serious changes in
74 * regular-expression syntax might require a total rethink.
77 #define PERL_IN_REGEXEC_C
81 #ifdef PERL_IN_XSUB_RE
87 #include "inline_invlist.c"
88 #include "unicode_constants.h"
91 /* At least one required character in the target string is expressible only in
93 static const char* const non_utf8_target_but_utf8_required
94 = "Can't match, because target string needs to be in UTF-8\n";
97 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
98 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
102 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
105 #define STATIC static
108 /* Valid only for non-utf8 strings: avoids the reginclass
109 * call if there are no complications: i.e., if everything matchable is
110 * straight forward in the bitmap */
111 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
112 : ANYOF_BITMAP_TEST(p,*(c)))
118 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
119 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
121 #define HOPc(pos,off) \
122 (char *)(reginfo->is_utf8_target \
123 ? reghop3((U8*)pos, off, \
124 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
127 #define HOPBACKc(pos, off) \
128 (char*)(reginfo->is_utf8_target \
129 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
130 : (pos - off >= reginfo->strbeg) \
134 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
135 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
137 /* lim must be +ve. Returns NULL on overshoot */
138 #define HOPMAYBE3(pos,off,lim) \
139 (reginfo->is_utf8_target \
140 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
141 : ((U8*)pos + off <= lim) \
145 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
146 * off must be >=0; args should be vars rather than expressions */
147 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
148 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
149 : (U8*)((pos + off) > lim ? lim : (pos + off)))
151 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
152 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
154 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
156 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
157 #define NEXTCHR_IS_EOS (nextchr < 0)
159 #define SET_nextchr \
160 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
162 #define SET_locinput(p) \
167 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
169 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
170 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
171 1, 0, invlist, &flags); \
176 /* If in debug mode, we test that a known character properly matches */
178 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
181 utf8_char_in_property) \
182 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
183 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
185 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
188 utf8_char_in_property) \
189 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
192 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
193 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
195 PL_XPosix_ptrs[_CC_WORDCHAR], \
196 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
198 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
199 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
201 /* for use after a quantifier and before an EXACT-like node -- japhy */
202 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
204 * NOTE that *nothing* that affects backtracking should be in here, specifically
205 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
206 * node that is in between two EXACT like nodes when ascertaining what the required
207 * "follow" character is. This should probably be moved to regex compile time
208 * although it may be done at run time beause of the REF possibility - more
209 * investigation required. -- demerphq
211 #define JUMPABLE(rn) ( \
213 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
215 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
216 OP(rn) == PLUS || OP(rn) == MINMOD || \
218 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
220 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
222 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
225 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
226 we don't need this definition. XXX These are now out-of-sync*/
227 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
228 #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 )
229 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
232 /* ... so we use this as its faster. */
233 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
234 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
235 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
236 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
241 Search for mandatory following text node; for lookahead, the text must
242 follow but for lookbehind (rn->flags != 0) we skip to the next step.
244 #define FIND_NEXT_IMPT(rn) STMT_START { \
245 while (JUMPABLE(rn)) { \
246 const OPCODE type = OP(rn); \
247 if (type == SUSPEND || PL_regkind[type] == CURLY) \
248 rn = NEXTOPER(NEXTOPER(rn)); \
249 else if (type == PLUS) \
251 else if (type == IFMATCH) \
252 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
253 else rn += NEXT_OFF(rn); \
257 #define SLAB_FIRST(s) (&(s)->states[0])
258 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
260 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
261 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
262 static regmatch_state * S_push_slab(pTHX);
264 #define REGCP_PAREN_ELEMS 3
265 #define REGCP_OTHER_ELEMS 3
266 #define REGCP_FRAME_ELEMS 1
267 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
268 * are needed for the regexp context stack bookkeeping. */
271 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
273 const int retval = PL_savestack_ix;
274 const int paren_elems_to_push =
275 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
276 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
277 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
279 GET_RE_DEBUG_FLAGS_DECL;
281 PERL_ARGS_ASSERT_REGCPPUSH;
283 if (paren_elems_to_push < 0)
284 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
285 (int)paren_elems_to_push, (int)maxopenparen,
286 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
288 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
289 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
290 " out of range (%lu-%ld)",
292 (unsigned long)maxopenparen,
295 SSGROW(total_elems + REGCP_FRAME_ELEMS);
298 if ((int)maxopenparen > (int)parenfloor)
299 PerlIO_printf(Perl_debug_log,
300 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
305 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
306 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
307 SSPUSHIV(rex->offs[p].end);
308 SSPUSHIV(rex->offs[p].start);
309 SSPUSHINT(rex->offs[p].start_tmp);
310 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
311 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
313 (IV)rex->offs[p].start,
314 (IV)rex->offs[p].start_tmp,
318 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
319 SSPUSHINT(maxopenparen);
320 SSPUSHINT(rex->lastparen);
321 SSPUSHINT(rex->lastcloseparen);
322 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
327 /* These are needed since we do not localize EVAL nodes: */
328 #define REGCP_SET(cp) \
330 PerlIO_printf(Perl_debug_log, \
331 " Setting an EVAL scope, savestack=%"IVdf"\n", \
332 (IV)PL_savestack_ix)); \
335 #define REGCP_UNWIND(cp) \
337 if (cp != PL_savestack_ix) \
338 PerlIO_printf(Perl_debug_log, \
339 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
340 (IV)(cp), (IV)PL_savestack_ix)); \
343 #define UNWIND_PAREN(lp, lcp) \
344 for (n = rex->lastparen; n > lp; n--) \
345 rex->offs[n].end = -1; \
346 rex->lastparen = n; \
347 rex->lastcloseparen = lcp;
351 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
355 GET_RE_DEBUG_FLAGS_DECL;
357 PERL_ARGS_ASSERT_REGCPPOP;
359 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
361 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
362 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
363 rex->lastcloseparen = SSPOPINT;
364 rex->lastparen = SSPOPINT;
365 *maxopenparen_p = SSPOPINT;
367 i -= REGCP_OTHER_ELEMS;
368 /* Now restore the parentheses context. */
370 if (i || rex->lastparen + 1 <= rex->nparens)
371 PerlIO_printf(Perl_debug_log,
372 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
377 paren = *maxopenparen_p;
378 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
380 rex->offs[paren].start_tmp = SSPOPINT;
381 rex->offs[paren].start = SSPOPIV;
383 if (paren <= rex->lastparen)
384 rex->offs[paren].end = tmps;
385 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
386 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
388 (IV)rex->offs[paren].start,
389 (IV)rex->offs[paren].start_tmp,
390 (IV)rex->offs[paren].end,
391 (paren > rex->lastparen ? "(skipped)" : ""));
396 /* It would seem that the similar code in regtry()
397 * already takes care of this, and in fact it is in
398 * a better location to since this code can #if 0-ed out
399 * but the code in regtry() is needed or otherwise tests
400 * requiring null fields (pat.t#187 and split.t#{13,14}
401 * (as of patchlevel 7877) will fail. Then again,
402 * this code seems to be necessary or otherwise
403 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
404 * --jhi updated by dapm */
405 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
406 if (i > *maxopenparen_p)
407 rex->offs[i].start = -1;
408 rex->offs[i].end = -1;
409 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
410 " \\%"UVuf": %s ..-1 undeffing\n",
412 (i > *maxopenparen_p) ? "-1" : " "
418 /* restore the parens and associated vars at savestack position ix,
419 * but without popping the stack */
422 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
424 I32 tmpix = PL_savestack_ix;
425 PL_savestack_ix = ix;
426 regcppop(rex, maxopenparen_p);
427 PL_savestack_ix = tmpix;
430 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
433 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
435 /* Returns a boolean as to whether or not 'character' is a member of the
436 * Posix character class given by 'classnum' that should be equivalent to a
437 * value in the typedef '_char_class_number'.
439 * Ideally this could be replaced by a just an array of function pointers
440 * to the C library functions that implement the macros this calls.
441 * However, to compile, the precise function signatures are required, and
442 * these may vary from platform to to platform. To avoid having to figure
443 * out what those all are on each platform, I (khw) am using this method,
444 * which adds an extra layer of function call overhead (unless the C
445 * optimizer strips it away). But we don't particularly care about
446 * performance with locales anyway. */
448 switch ((_char_class_number) classnum) {
449 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
450 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
451 case _CC_ENUM_ASCII: return isASCII_LC(character);
452 case _CC_ENUM_BLANK: return isBLANK_LC(character);
453 case _CC_ENUM_CASED: return isLOWER_LC(character)
454 || isUPPER_LC(character);
455 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
456 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
457 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
458 case _CC_ENUM_LOWER: return isLOWER_LC(character);
459 case _CC_ENUM_PRINT: return isPRINT_LC(character);
460 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
461 case _CC_ENUM_SPACE: return isSPACE_LC(character);
462 case _CC_ENUM_UPPER: return isUPPER_LC(character);
463 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
464 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
465 default: /* VERTSPACE should never occur in locales */
466 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
469 NOT_REACHED; /* NOTREACHED */
474 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
476 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
477 * 'character' is a member of the Posix character class given by 'classnum'
478 * that should be equivalent to a value in the typedef
479 * '_char_class_number'.
481 * This just calls isFOO_lc on the code point for the character if it is in
482 * the range 0-255. Outside that range, all characters use Unicode
483 * rules, ignoring any locale. So use the Unicode function if this class
484 * requires a swash, and use the Unicode macro otherwise. */
486 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
488 if (UTF8_IS_INVARIANT(*character)) {
489 return isFOO_lc(classnum, *character);
491 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
492 return isFOO_lc(classnum,
493 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
496 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
498 if (classnum < _FIRST_NON_SWASH_CC) {
500 /* Initialize the swash unless done already */
501 if (! PL_utf8_swash_ptrs[classnum]) {
502 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
503 PL_utf8_swash_ptrs[classnum] =
504 _core_swash_init("utf8",
507 PL_XPosix_ptrs[classnum], &flags);
510 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
512 TRUE /* is UTF */ ));
515 switch ((_char_class_number) classnum) {
516 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
517 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
518 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
519 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
523 return FALSE; /* Things like CNTRL are always below 256 */
527 * pregexec and friends
530 #ifndef PERL_IN_XSUB_RE
532 - pregexec - match a regexp against a string
535 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
536 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
537 /* stringarg: the point in the string at which to begin matching */
538 /* strend: pointer to null at end of string */
539 /* strbeg: real beginning of string */
540 /* minend: end of match must be >= minend bytes after stringarg. */
541 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
542 * itself is accessed via the pointers above */
543 /* nosave: For optimizations. */
545 PERL_ARGS_ASSERT_PREGEXEC;
548 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
549 nosave ? 0 : REXEC_COPY_STR);
555 /* re_intuit_start():
557 * Based on some optimiser hints, try to find the earliest position in the
558 * string where the regex could match.
560 * rx: the regex to match against
561 * sv: the SV being matched: only used for utf8 flag; the string
562 * itself is accessed via the pointers below. Note that on
563 * something like an overloaded SV, SvPOK(sv) may be false
564 * and the string pointers may point to something unrelated to
566 * strbeg: real beginning of string
567 * strpos: the point in the string at which to begin matching
568 * strend: pointer to the byte following the last char of the string
569 * flags currently unused; set to 0
570 * data: currently unused; set to NULL
572 * The basic idea of re_intuit_start() is to use some known information
573 * about the pattern, namely:
575 * a) the longest known anchored substring (i.e. one that's at a
576 * constant offset from the beginning of the pattern; but not
577 * necessarily at a fixed offset from the beginning of the
579 * b) the longest floating substring (i.e. one that's not at a constant
580 * offset from the beginning of the pattern);
581 * c) Whether the pattern is anchored to the string; either
582 * an absolute anchor: /^../, or anchored to \n: /^.../m,
583 * or anchored to pos(): /\G/;
584 * d) A start class: a real or synthetic character class which
585 * represents which characters are legal at the start of the pattern;
587 * to either quickly reject the match, or to find the earliest position
588 * within the string at which the pattern might match, thus avoiding
589 * running the full NFA engine at those earlier locations, only to
590 * eventually fail and retry further along.
592 * Returns NULL if the pattern can't match, or returns the address within
593 * the string which is the earliest place the match could occur.
595 * The longest of the anchored and floating substrings is called 'check'
596 * and is checked first. The other is called 'other' and is checked
597 * second. The 'other' substring may not be present. For example,
599 * /(abc|xyz)ABC\d{0,3}DEFG/
603 * check substr (float) = "DEFG", offset 6..9 chars
604 * other substr (anchored) = "ABC", offset 3..3 chars
607 * Be aware that during the course of this function, sometimes 'anchored'
608 * refers to a substring being anchored relative to the start of the
609 * pattern, and sometimes to the pattern itself being anchored relative to
610 * the string. For example:
612 * /\dabc/: "abc" is anchored to the pattern;
613 * /^\dabc/: "abc" is anchored to the pattern and the string;
614 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
615 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
616 * but the pattern is anchored to the string.
620 Perl_re_intuit_start(pTHX_
623 const char * const strbeg,
627 re_scream_pos_data *data)
629 struct regexp *const prog = ReANY(rx);
630 SSize_t start_shift = prog->check_offset_min;
631 /* Should be nonnegative! */
632 SSize_t end_shift = 0;
633 /* current lowest pos in string where the regex can start matching */
634 char *rx_origin = strpos;
636 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
637 U8 other_ix = 1 - prog->substrs->check_ix;
639 char *other_last = strpos;/* latest pos 'other' substr already checked to */
640 char *check_at = NULL; /* check substr found at this pos */
641 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
642 RXi_GET_DECL(prog,progi);
643 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
644 regmatch_info *const reginfo = ®info_buf;
645 GET_RE_DEBUG_FLAGS_DECL;
647 PERL_ARGS_ASSERT_RE_INTUIT_START;
648 PERL_UNUSED_ARG(flags);
649 PERL_UNUSED_ARG(data);
651 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
652 "Intuit: trying to determine minimum start position...\n"));
654 /* for now, assume that all substr offsets are positive. If at some point
655 * in the future someone wants to do clever things with look-behind and
656 * -ve offsets, they'll need to fix up any code in this function
657 * which uses these offsets. See the thread beginning
658 * <20140113145929.GF27210@iabyn.com>
660 assert(prog->substrs->data[0].min_offset >= 0);
661 assert(prog->substrs->data[0].max_offset >= 0);
662 assert(prog->substrs->data[1].min_offset >= 0);
663 assert(prog->substrs->data[1].max_offset >= 0);
664 assert(prog->substrs->data[2].min_offset >= 0);
665 assert(prog->substrs->data[2].max_offset >= 0);
667 /* for now, assume that if both present, that the floating substring
668 * doesn't start before the anchored substring.
669 * If you break this assumption (e.g. doing better optimisations
670 * with lookahead/behind), then you'll need to audit the code in this
671 * function carefully first
674 ! ( (prog->anchored_utf8 || prog->anchored_substr)
675 && (prog->float_utf8 || prog->float_substr))
676 || (prog->float_min_offset >= prog->anchored_offset));
678 /* byte rather than char calculation for efficiency. It fails
679 * to quickly reject some cases that can't match, but will reject
680 * them later after doing full char arithmetic */
681 if (prog->minlen > strend - strpos) {
682 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
683 " String too short...\n"));
687 RX_MATCH_UTF8_set(rx,utf8_target);
688 reginfo->is_utf8_target = cBOOL(utf8_target);
689 reginfo->info_aux = NULL;
690 reginfo->strbeg = strbeg;
691 reginfo->strend = strend;
692 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
694 /* not actually used within intuit, but zero for safety anyway */
695 reginfo->poscache_maxiter = 0;
698 if (!prog->check_utf8 && prog->check_substr)
699 to_utf8_substr(prog);
700 check = prog->check_utf8;
702 if (!prog->check_substr && prog->check_utf8) {
703 if (! to_byte_substr(prog)) {
704 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
707 check = prog->check_substr;
710 /* dump the various substring data */
711 DEBUG_OPTIMISE_MORE_r({
713 for (i=0; i<=2; i++) {
714 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
715 : prog->substrs->data[i].substr);
719 PerlIO_printf(Perl_debug_log,
720 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
721 " useful=%"IVdf" utf8=%d [%s]\n",
723 (IV)prog->substrs->data[i].min_offset,
724 (IV)prog->substrs->data[i].max_offset,
725 (IV)prog->substrs->data[i].end_shift,
732 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
734 /* ml_anch: check after \n?
736 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
737 * with /.*.../, these flags will have been added by the
739 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
740 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
742 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
743 && !(prog->intflags & PREGf_IMPLICIT);
745 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
746 /* we are only allowed to match at BOS or \G */
748 /* trivially reject if there's a BOS anchor and we're not at BOS.
750 * Note that we don't try to do a similar quick reject for
751 * \G, since generally the caller will have calculated strpos
752 * based on pos() and gofs, so the string is already correctly
753 * anchored by definition; and handling the exceptions would
754 * be too fiddly (e.g. REXEC_IGNOREPOS).
756 if ( strpos != strbeg
757 && (prog->intflags & PREGf_ANCH_SBOL))
759 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
760 " Not at start...\n"));
764 /* in the presence of an anchor, the anchored (relative to the
765 * start of the regex) substr must also be anchored relative
766 * to strpos. So quickly reject if substr isn't found there.
767 * This works for \G too, because the caller will already have
768 * subtracted gofs from pos, and gofs is the offset from the
769 * \G to the start of the regex. For example, in /.abc\Gdef/,
770 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
771 * caller will have set strpos=pos()-4; we look for the substr
772 * at position pos()-4+1, which lines up with the "a" */
774 if (prog->check_offset_min == prog->check_offset_max
775 && !(prog->intflags & PREGf_CANY_SEEN))
777 /* Substring at constant offset from beg-of-str... */
778 SSize_t slen = SvCUR(check);
779 char *s = HOP3c(strpos, prog->check_offset_min, strend);
781 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
782 " Looking for check substr at fixed offset %"IVdf"...\n",
783 (IV)prog->check_offset_min));
786 /* In this case, the regex is anchored at the end too.
787 * Unless it's a multiline match, the lengths must match
788 * exactly, give or take a \n. NB: slen >= 1 since
789 * the last char of check is \n */
791 && ( strend - s > slen
792 || strend - s < slen - 1
793 || (strend - s == slen && strend[-1] != '\n')))
795 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
796 " String too long...\n"));
799 /* Now should match s[0..slen-2] */
802 if (slen && (*SvPVX_const(check) != *s
803 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
805 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
806 " String not equal...\n"));
811 goto success_at_start;
816 end_shift = prog->check_end_shift;
818 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
820 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
821 (IV)end_shift, RX_PRECOMP(prog));
826 /* This is the (re)entry point of the main loop in this function.
827 * The goal of this loop is to:
828 * 1) find the "check" substring in the region rx_origin..strend
829 * (adjusted by start_shift / end_shift). If not found, reject
831 * 2) If it exists, look for the "other" substr too if defined; for
832 * example, if the check substr maps to the anchored substr, then
833 * check the floating substr, and vice-versa. If not found, go
834 * back to (1) with rx_origin suitably incremented.
835 * 3) If we find an rx_origin position that doesn't contradict
836 * either of the substrings, then check the possible additional
837 * constraints on rx_origin of /^.../m or a known start class.
838 * If these fail, then depending on which constraints fail, jump
839 * back to here, or to various other re-entry points further along
840 * that skip some of the first steps.
841 * 4) If we pass all those tests, update the BmUSEFUL() count on the
842 * substring. If the start position was determined to be at the
843 * beginning of the string - so, not rejected, but not optimised,
844 * since we have to run regmatch from position 0 - decrement the
845 * BmUSEFUL() count. Otherwise increment it.
849 /* first, look for the 'check' substring */
855 DEBUG_OPTIMISE_MORE_r({
856 PerlIO_printf(Perl_debug_log,
857 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
858 " Start shift: %"IVdf" End shift %"IVdf
859 " Real end Shift: %"IVdf"\n",
860 (IV)(rx_origin - strbeg),
861 (IV)prog->check_offset_min,
864 (IV)prog->check_end_shift);
867 if (prog->intflags & PREGf_CANY_SEEN) {
868 start_point= (U8*)(rx_origin + start_shift);
869 end_point= (U8*)(strend - end_shift);
870 if (start_point > end_point)
873 end_point = HOP3(strend, -end_shift, strbeg);
874 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
880 /* If the regex is absolutely anchored to either the start of the
881 * string (SBOL) or to pos() (ANCH_GPOS), then
882 * check_offset_max represents an upper bound on the string where
883 * the substr could start. For the ANCH_GPOS case, we assume that
884 * the caller of intuit will have already set strpos to
885 * pos()-gofs, so in this case strpos + offset_max will still be
886 * an upper bound on the substr.
889 && prog->intflags & PREGf_ANCH
890 && prog->check_offset_max != SSize_t_MAX)
892 SSize_t len = SvCUR(check) - !!SvTAIL(check);
893 const char * const anchor =
894 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
896 /* do a bytes rather than chars comparison. It's conservative;
897 * so it skips doing the HOP if the result can't possibly end
898 * up earlier than the old value of end_point.
900 if ((char*)end_point - anchor > prog->check_offset_max) {
901 end_point = HOP3lim((U8*)anchor,
902 prog->check_offset_max,
908 check_at = fbm_instr( start_point, end_point,
909 check, multiline ? FBMrf_MULTILINE : 0);
911 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
912 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
913 (IV)((char*)start_point - strbeg),
914 (IV)((char*)end_point - strbeg),
915 (IV)(check_at ? check_at - strbeg : -1)
918 /* Update the count-of-usability, remove useless subpatterns,
922 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
923 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
924 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
925 (check_at ? "Found" : "Did not find"),
926 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
927 ? "anchored" : "floating"),
930 (check_at ? " at offset " : "...\n") );
935 /* set rx_origin to the minimum position where the regex could start
936 * matching, given the constraint of the just-matched check substring.
937 * But don't set it lower than previously.
940 if (check_at - rx_origin > prog->check_offset_max)
941 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
942 /* Finish the diagnostic message */
943 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
944 "%ld (rx_origin now %"IVdf")...\n",
945 (long)(check_at - strbeg),
946 (IV)(rx_origin - strbeg)
951 /* now look for the 'other' substring if defined */
953 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
954 : prog->substrs->data[other_ix].substr)
956 /* Take into account the "other" substring. */
960 struct reg_substr_datum *other;
963 other = &prog->substrs->data[other_ix];
965 /* if "other" is anchored:
966 * we've previously found a floating substr starting at check_at.
967 * This means that the regex origin must lie somewhere
968 * between min (rx_origin): HOP3(check_at, -check_offset_max)
969 * and max: HOP3(check_at, -check_offset_min)
970 * (except that min will be >= strpos)
971 * So the fixed substr must lie somewhere between
972 * HOP3(min, anchored_offset)
973 * HOP3(max, anchored_offset) + SvCUR(substr)
976 /* if "other" is floating
977 * Calculate last1, the absolute latest point where the
978 * floating substr could start in the string, ignoring any
979 * constraints from the earlier fixed match. It is calculated
982 * strend - prog->minlen (in chars) is the absolute latest
983 * position within the string where the origin of the regex
984 * could appear. The latest start point for the floating
985 * substr is float_min_offset(*) on from the start of the
986 * regex. last1 simply combines thee two offsets.
988 * (*) You might think the latest start point should be
989 * float_max_offset from the regex origin, and technically
990 * you'd be correct. However, consider
992 * Here, float min, max are 3,5 and minlen is 7.
993 * This can match either
997 * In the first case, the regex matches minlen chars; in the
998 * second, minlen+1, in the third, minlen+2.
999 * In the first case, the floating offset is 3 (which equals
1000 * float_min), in the second, 4, and in the third, 5 (which
1001 * equals float_max). In all cases, the floating string bcd
1002 * can never start more than 4 chars from the end of the
1003 * string, which equals minlen - float_min. As the substring
1004 * starts to match more than float_min from the start of the
1005 * regex, it makes the regex match more than minlen chars,
1006 * and the two cancel each other out. So we can always use
1007 * float_min - minlen, rather than float_max - minlen for the
1008 * latest position in the string.
1010 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1011 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1014 assert(prog->minlen >= other->min_offset);
1015 last1 = HOP3c(strend,
1016 other->min_offset - prog->minlen, strbeg);
1018 if (other_ix) {/* i.e. if (other-is-float) */
1019 /* last is the latest point where the floating substr could
1020 * start, *given* any constraints from the earlier fixed
1021 * match. This constraint is that the floating string starts
1022 * <= float_max_offset chars from the regex origin (rx_origin).
1023 * If this value is less than last1, use it instead.
1025 assert(rx_origin <= last1);
1027 /* this condition handles the offset==infinity case, and
1028 * is a short-cut otherwise. Although it's comparing a
1029 * byte offset to a char length, it does so in a safe way,
1030 * since 1 char always occupies 1 or more bytes,
1031 * so if a string range is (last1 - rx_origin) bytes,
1032 * it will be less than or equal to (last1 - rx_origin)
1033 * chars; meaning it errs towards doing the accurate HOP3
1034 * rather than just using last1 as a short-cut */
1035 (last1 - rx_origin) < other->max_offset
1037 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1040 assert(strpos + start_shift <= check_at);
1041 last = HOP4c(check_at, other->min_offset - start_shift,
1045 s = HOP3c(rx_origin, other->min_offset, strend);
1046 if (s < other_last) /* These positions already checked */
1049 must = utf8_target ? other->utf8_substr : other->substr;
1050 assert(SvPOK(must));
1053 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1057 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1058 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1059 (IV)(from - strbeg),
1065 (unsigned char*)from,
1068 multiline ? FBMrf_MULTILINE : 0
1070 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1071 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1072 (IV)(from - strbeg),
1074 (IV)(s ? s - strbeg : -1)
1080 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1081 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1082 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1083 s ? "Found" : "Contradicts",
1084 other_ix ? "floating" : "anchored",
1085 quoted, RE_SV_TAIL(must));
1090 /* last1 is latest possible substr location. If we didn't
1091 * find it before there, we never will */
1092 if (last >= last1) {
1093 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1094 "; giving up...\n"));
1098 /* try to find the check substr again at a later
1099 * position. Maybe next time we'll find the "other" substr
1101 other_last = HOP3c(last, 1, strend) /* highest failure */;
1103 other_ix /* i.e. if other-is-float */
1104 ? HOP3c(rx_origin, 1, strend)
1105 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1106 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1107 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1108 (other_ix ? "floating" : "anchored"),
1109 (long)(HOP3c(check_at, 1, strend) - strbeg),
1110 (IV)(rx_origin - strbeg)
1115 if (other_ix) { /* if (other-is-float) */
1116 /* other_last is set to s, not s+1, since its possible for
1117 * a floating substr to fail first time, then succeed
1118 * second time at the same floating position; e.g.:
1119 * "-AB--AABZ" =~ /\wAB\d*Z/
1120 * The first time round, anchored and float match at
1121 * "-(AB)--AAB(Z)" then fail on the initial \w character
1122 * class. Second time round, they match at "-AB--A(AB)(Z)".
1127 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1128 other_last = HOP3c(s, 1, strend);
1130 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1131 " at offset %ld (rx_origin now %"IVdf")...\n",
1133 (IV)(rx_origin - strbeg)
1139 DEBUG_OPTIMISE_MORE_r(
1140 PerlIO_printf(Perl_debug_log,
1141 " Check-only match: offset min:%"IVdf" max:%"IVdf
1142 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1143 " strend:%"IVdf"\n",
1144 (IV)prog->check_offset_min,
1145 (IV)prog->check_offset_max,
1146 (IV)(check_at-strbeg),
1147 (IV)(rx_origin-strbeg),
1148 (IV)(rx_origin-check_at),
1154 postprocess_substr_matches:
1156 /* handle the extra constraint of /^.../m if present */
1158 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1161 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1162 " looking for /^/m anchor"));
1164 /* we have failed the constraint of a \n before rx_origin.
1165 * Find the next \n, if any, even if it's beyond the current
1166 * anchored and/or floating substrings. Whether we should be
1167 * scanning ahead for the next \n or the next substr is debatable.
1168 * On the one hand you'd expect rare substrings to appear less
1169 * often than \n's. On the other hand, searching for \n means
1170 * we're effectively flipping between check_substr and "\n" on each
1171 * iteration as the current "rarest" string candidate, which
1172 * means for example that we'll quickly reject the whole string if
1173 * hasn't got a \n, rather than trying every substr position
1177 s = HOP3c(strend, - prog->minlen, strpos);
1178 if (s <= rx_origin ||
1179 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1181 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1182 " Did not find /%s^%s/m...\n",
1183 PL_colors[0], PL_colors[1]));
1187 /* earliest possible origin is 1 char after the \n.
1188 * (since *rx_origin == '\n', it's safe to ++ here rather than
1189 * HOP(rx_origin, 1)) */
1192 if (prog->substrs->check_ix == 0 /* check is anchored */
1193 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1195 /* Position contradicts check-string; either because
1196 * check was anchored (and thus has no wiggle room),
1197 * or check was float and rx_origin is above the float range */
1198 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1199 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1200 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1204 /* if we get here, the check substr must have been float,
1205 * is in range, and we may or may not have had an anchored
1206 * "other" substr which still contradicts */
1207 assert(prog->substrs->check_ix); /* check is float */
1209 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1210 /* whoops, the anchored "other" substr exists, so we still
1211 * contradict. On the other hand, the float "check" substr
1212 * didn't contradict, so just retry the anchored "other"
1214 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1215 " Found /%s^%s/m, rescanning for anchored from offset %ld (rx_origin now %"IVdf")...\n",
1216 PL_colors[0], PL_colors[1],
1217 (long)(rx_origin - strbeg + prog->anchored_offset),
1218 (long)(rx_origin - strbeg)
1220 goto do_other_substr;
1223 /* success: we don't contradict the found floating substring
1224 * (and there's no anchored substr). */
1225 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1226 " Found /%s^%s/m with rx_origin %ld...\n",
1227 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1230 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1231 " (multiline anchor test skipped)\n"));
1237 /* if we have a starting character class, then test that extra constraint.
1238 * (trie stclasses are too expensive to use here, we are better off to
1239 * leave it to regmatch itself) */
1241 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1242 const U8* const str = (U8*)STRING(progi->regstclass);
1244 /* XXX this value could be pre-computed */
1245 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1246 ? (reginfo->is_utf8_pat
1247 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1248 : STR_LEN(progi->regstclass))
1252 /* latest pos that a matching float substr constrains rx start to */
1253 char *rx_max_float = NULL;
1255 /* if the current rx_origin is anchored, either by satisfying an
1256 * anchored substring constraint, or a /^.../m constraint, then we
1257 * can reject the current origin if the start class isn't found
1258 * at the current position. If we have a float-only match, then
1259 * rx_origin is constrained to a range; so look for the start class
1260 * in that range. if neither, then look for the start class in the
1261 * whole rest of the string */
1263 /* XXX DAPM it's not clear what the minlen test is for, and why
1264 * it's not used in the floating case. Nothing in the test suite
1265 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1266 * Here are some old comments, which may or may not be correct:
1268 * minlen == 0 is possible if regstclass is \b or \B,
1269 * and the fixed substr is ''$.
1270 * Since minlen is already taken into account, rx_origin+1 is
1271 * before strend; accidentally, minlen >= 1 guaranties no false
1272 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1273 * 0) below assumes that regstclass does not come from lookahead...
1274 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1275 * This leaves EXACTF-ish only, which are dealt with in
1279 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1280 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1281 else if (prog->float_substr || prog->float_utf8) {
1282 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1283 endpos= HOP3c(rx_max_float, cl_l, strend);
1288 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1289 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1290 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1291 (IV)start_shift, (IV)(check_at - strbeg),
1292 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1294 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1297 if (endpos == strend) {
1298 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1299 " Could not match STCLASS...\n") );
1302 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1303 " This position contradicts STCLASS...\n") );
1304 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1305 && !(prog->intflags & PREGf_IMPLICIT))
1308 /* Contradict one of substrings */
1309 if (prog->anchored_substr || prog->anchored_utf8) {
1310 if (prog->substrs->check_ix == 1) { /* check is float */
1311 /* Have both, check_string is floating */
1312 assert(rx_origin + start_shift <= check_at);
1313 if (rx_origin + start_shift != check_at) {
1314 /* not at latest position float substr could match:
1315 * Recheck anchored substring, but not floating.
1316 * The condition above is in bytes rather than
1317 * chars for efficiency. It's conservative, in
1318 * that it errs on the side of doing 'goto
1319 * do_other_substr'. In this case, at worst,
1320 * an extra anchored search may get done, but in
1321 * practice the extra fbm_instr() is likely to
1322 * get skipped anyway. */
1323 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1324 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1325 (long)(other_last - strbeg),
1326 (IV)(rx_origin - strbeg)
1328 goto do_other_substr;
1336 /* In the presence of ml_anch, we might be able to
1337 * find another \n without breaking the current float
1340 /* strictly speaking this should be HOP3c(..., 1, ...),
1341 * but since we goto a block of code that's going to
1342 * search for the next \n if any, its safe here */
1344 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1345 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1346 PL_colors[0], PL_colors[1],
1347 (long)(rx_origin - strbeg)) );
1348 goto postprocess_substr_matches;
1351 /* strictly speaking this can never be true; but might
1352 * be if we ever allow intuit without substrings */
1353 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1356 rx_origin = rx_max_float;
1359 /* at this point, any matching substrings have been
1360 * contradicted. Start again... */
1362 rx_origin = HOP3c(rx_origin, 1, strend);
1364 /* uses bytes rather than char calculations for efficiency.
1365 * It's conservative: it errs on the side of doing 'goto restart',
1366 * where there is code that does a proper char-based test */
1367 if (rx_origin + start_shift + end_shift > strend) {
1368 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1369 " Could not match STCLASS...\n") );
1372 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1373 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1374 (prog->substrs->check_ix ? "floating" : "anchored"),
1375 (long)(rx_origin + start_shift - strbeg),
1376 (IV)(rx_origin - strbeg)
1383 if (rx_origin != s) {
1384 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1385 " By STCLASS: moving %ld --> %ld\n",
1386 (long)(rx_origin - strbeg), (long)(s - strbeg))
1390 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1391 " Does not contradict STCLASS...\n");
1396 /* Decide whether using the substrings helped */
1398 if (rx_origin != strpos) {
1399 /* Fixed substring is found far enough so that the match
1400 cannot start at strpos. */
1402 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1403 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1406 /* The found rx_origin position does not prohibit matching at
1407 * strpos, so calling intuit didn't gain us anything. Decrement
1408 * the BmUSEFUL() count on the check substring, and if we reach
1410 if (!(prog->intflags & PREGf_NAUGHTY)
1412 prog->check_utf8 /* Could be deleted already */
1413 && --BmUSEFUL(prog->check_utf8) < 0
1414 && (prog->check_utf8 == prog->float_utf8)
1416 prog->check_substr /* Could be deleted already */
1417 && --BmUSEFUL(prog->check_substr) < 0
1418 && (prog->check_substr == prog->float_substr)
1421 /* If flags & SOMETHING - do not do it many times on the same match */
1422 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1423 /* XXX Does the destruction order has to change with utf8_target? */
1424 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1425 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1426 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1427 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1428 check = NULL; /* abort */
1429 /* XXXX This is a remnant of the old implementation. It
1430 looks wasteful, since now INTUIT can use many
1431 other heuristics. */
1432 prog->extflags &= ~RXf_USE_INTUIT;
1436 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1437 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1438 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1442 fail_finish: /* Substring not found */
1443 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1444 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1446 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1447 PL_colors[4], PL_colors[5]));
1452 #define DECL_TRIE_TYPE(scan) \
1453 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1454 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1455 trie_utf8l, trie_flu8 } \
1456 trie_type = ((scan->flags == EXACT) \
1457 ? (utf8_target ? trie_utf8 : trie_plain) \
1458 : (scan->flags == EXACTL) \
1459 ? (utf8_target ? trie_utf8l : trie_plain) \
1460 : (scan->flags == EXACTFA) \
1462 ? trie_utf8_exactfa_fold \
1463 : trie_latin_utf8_exactfa_fold) \
1464 : (scan->flags == EXACTFLU8 \
1468 : trie_latin_utf8_fold)))
1470 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1473 U8 flags = FOLD_FLAGS_FULL; \
1474 switch (trie_type) { \
1476 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1477 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1478 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1480 goto do_trie_utf8_fold; \
1481 case trie_utf8_exactfa_fold: \
1482 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1484 case trie_utf8_fold: \
1485 do_trie_utf8_fold: \
1486 if ( foldlen>0 ) { \
1487 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1492 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1493 len = UTF8SKIP(uc); \
1494 skiplen = UNISKIP( uvc ); \
1495 foldlen -= skiplen; \
1496 uscan = foldbuf + skiplen; \
1499 case trie_latin_utf8_exactfa_fold: \
1500 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1502 case trie_latin_utf8_fold: \
1503 if ( foldlen>0 ) { \
1504 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1510 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1511 skiplen = UNISKIP( uvc ); \
1512 foldlen -= skiplen; \
1513 uscan = foldbuf + skiplen; \
1517 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1518 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1519 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1523 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1530 charid = trie->charmap[ uvc ]; \
1534 if (widecharmap) { \
1535 SV** const svpp = hv_fetch(widecharmap, \
1536 (char*)&uvc, sizeof(UV), 0); \
1538 charid = (U16)SvIV(*svpp); \
1543 #define DUMP_EXEC_POS(li,s,doutf8) \
1544 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1547 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1551 && (ln == 1 || folder(s, pat_string, ln)) \
1552 && (reginfo->intuit || regtry(reginfo, &s)) )\
1558 #define REXEC_FBC_UTF8_SCAN(CODE) \
1560 while (s < strend) { \
1566 #define REXEC_FBC_SCAN(CODE) \
1568 while (s < strend) { \
1574 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1575 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1577 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1586 #define REXEC_FBC_CLASS_SCAN(COND) \
1587 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1589 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1598 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1599 if (utf8_target) { \
1600 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1603 REXEC_FBC_CLASS_SCAN(COND); \
1606 /* The three macros below are slightly different versions of the same logic.
1608 * The first is for /a and /aa when the target string is UTF-8. This can only
1609 * match ascii, but it must advance based on UTF-8. The other two handle the
1610 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1611 * for the boundary (or non-boundary) between a word and non-word character.
1612 * The utf8 and non-utf8 cases have the same logic, but the details must be
1613 * different. Find the "wordness" of the character just prior to this one, and
1614 * compare it with the wordness of this one. If they differ, we have a
1615 * boundary. At the beginning of the string, pretend that the previous
1616 * character was a new-line.
1618 * All these macros uncleanly have side-effects with each other and outside
1619 * variables. So far it's been too much trouble to clean-up
1621 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1622 * a word character or not.
1623 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1625 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1627 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1628 * are looking for a boundary or for a non-boundary. If we are looking for a
1629 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1630 * see if this tentative match actually works, and if so, to quit the loop
1631 * here. And vice-versa if we are looking for a non-boundary.
1633 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1634 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1635 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1636 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1637 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1638 * complement. But in that branch we complement tmp, meaning that at the
1639 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1640 * which means at the top of the loop in the next iteration, it is
1641 * TEST_NON_UTF8(s-1) */
1642 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1643 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1644 tmp = TEST_NON_UTF8(tmp); \
1645 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1646 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1648 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1655 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1656 * TEST_UTF8 is a macro that for the same input code points returns identically
1657 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1658 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1659 if (s == reginfo->strbeg) { \
1662 else { /* Back-up to the start of the previous character */ \
1663 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1664 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1665 0, UTF8_ALLOW_DEFAULT); \
1667 tmp = TEST_UV(tmp); \
1668 LOAD_UTF8_CHARCLASS_ALNUM(); \
1669 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1670 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1679 /* Like the above two macros. UTF8_CODE is the complete code for handling
1680 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1682 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1683 if (utf8_target) { \
1686 else { /* Not utf8 */ \
1687 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1688 tmp = TEST_NON_UTF8(tmp); \
1689 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1690 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1699 /* Here, things have been set up by the previous code so that tmp is the \
1700 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1701 * utf8ness of the target). We also have to check if this matches against \
1702 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1703 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1705 if (tmp == ! TEST_NON_UTF8('\n')) { \
1712 /* This is the macro to use when we want to see if something that looks like it
1713 * could match, actually does, and if so exits the loop */
1714 #define REXEC_FBC_TRYIT \
1715 if ((reginfo->intuit || regtry(reginfo, &s))) \
1718 /* The only difference between the BOUND and NBOUND cases is that
1719 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1720 * NBOUND. This is accomplished by passing it as either the if or else clause,
1721 * with the other one being empty (PLACEHOLDER is defined as empty).
1723 * The TEST_FOO parameters are for operating on different forms of input, but
1724 * all should be ones that return identically for the same underlying code
1726 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1728 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1729 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1731 #define FBC_BOUND_A(TEST_NON_UTF8) \
1733 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1734 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1736 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1738 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1739 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1741 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1743 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1744 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1746 /* Takes a pointer to an inversion list, a pointer to its corresponding
1747 * inversion map, and a code point, and returns the code point's value
1748 * according to the two arrays. It assumes that all code points have a value.
1749 * This is used as the base macro for macros for particular properties */
1750 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1751 invmap[_invlist_search(invlist, cp)]
1753 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1754 * of a code point, returning the value for the first code point in the string.
1755 * And it takes the particular macro name that finds the desired value given a
1756 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1757 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1758 (__ASSERT_(pos < strend) \
1759 /* Note assumes is valid UTF-8 */ \
1760 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1762 /* Returns the GCB value for the input code point */
1763 #define getGCB_VAL_CP(cp) \
1764 _generic_GET_BREAK_VAL_CP( \
1766 Grapheme_Cluster_Break_invmap, \
1769 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1770 * bounded by pos and strend */
1771 #define getGCB_VAL_UTF8(pos, strend) \
1772 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1775 /* Returns the SB value for the input code point */
1776 #define getSB_VAL_CP(cp) \
1777 _generic_GET_BREAK_VAL_CP( \
1779 Sentence_Break_invmap, \
1782 /* Returns the SB value for the first code point in the UTF-8 encoded string
1783 * bounded by pos and strend */
1784 #define getSB_VAL_UTF8(pos, strend) \
1785 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1787 /* Returns the WB value for the input code point */
1788 #define getWB_VAL_CP(cp) \
1789 _generic_GET_BREAK_VAL_CP( \
1791 Word_Break_invmap, \
1794 /* Returns the WB value for the first code point in the UTF-8 encoded string
1795 * bounded by pos and strend */
1796 #define getWB_VAL_UTF8(pos, strend) \
1797 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1799 /* We know what class REx starts with. Try to find this position... */
1800 /* if reginfo->intuit, its a dryrun */
1801 /* annoyingly all the vars in this routine have different names from their counterparts
1802 in regmatch. /grrr */
1804 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1805 const char *strend, regmatch_info *reginfo)
1808 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1809 char *pat_string; /* The pattern's exactish string */
1810 char *pat_end; /* ptr to end char of pat_string */
1811 re_fold_t folder; /* Function for computing non-utf8 folds */
1812 const U8 *fold_array; /* array for folding ords < 256 */
1818 I32 tmp = 1; /* Scratch variable? */
1819 const bool utf8_target = reginfo->is_utf8_target;
1820 UV utf8_fold_flags = 0;
1821 const bool is_utf8_pat = reginfo->is_utf8_pat;
1822 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1823 with a result inverts that result, as 0^1 =
1825 _char_class_number classnum;
1827 RXi_GET_DECL(prog,progi);
1829 PERL_ARGS_ASSERT_FIND_BYCLASS;
1831 /* We know what class it must start with. */
1834 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1838 REXEC_FBC_UTF8_CLASS_SCAN(
1839 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1842 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1847 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
1854 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1855 assert(! is_utf8_pat);
1858 if (is_utf8_pat || utf8_target) {
1859 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1860 goto do_exactf_utf8;
1862 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1863 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1864 goto do_exactf_non_utf8; /* isn't dealt with by these */
1866 case EXACTF: /* This node only generated for non-utf8 patterns */
1867 assert(! is_utf8_pat);
1869 utf8_fold_flags = 0;
1870 goto do_exactf_utf8;
1872 fold_array = PL_fold;
1874 goto do_exactf_non_utf8;
1877 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1878 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1879 utf8_fold_flags = FOLDEQ_LOCALE;
1880 goto do_exactf_utf8;
1882 fold_array = PL_fold_locale;
1883 folder = foldEQ_locale;
1884 goto do_exactf_non_utf8;
1888 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1890 goto do_exactf_utf8;
1893 if (! utf8_target) { /* All code points in this node require
1894 UTF-8 to express. */
1897 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1898 | FOLDEQ_S2_FOLDS_SANE;
1899 goto do_exactf_utf8;
1902 if (is_utf8_pat || utf8_target) {
1903 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1904 goto do_exactf_utf8;
1907 /* Any 'ss' in the pattern should have been replaced by regcomp,
1908 * so we don't have to worry here about this single special case
1909 * in the Latin1 range */
1910 fold_array = PL_fold_latin1;
1911 folder = foldEQ_latin1;
1915 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1916 are no glitches with fold-length differences
1917 between the target string and pattern */
1919 /* The idea in the non-utf8 EXACTF* cases is to first find the
1920 * first character of the EXACTF* node and then, if necessary,
1921 * case-insensitively compare the full text of the node. c1 is the
1922 * first character. c2 is its fold. This logic will not work for
1923 * Unicode semantics and the german sharp ss, which hence should
1924 * not be compiled into a node that gets here. */
1925 pat_string = STRING(c);
1926 ln = STR_LEN(c); /* length to match in octets/bytes */
1928 /* We know that we have to match at least 'ln' bytes (which is the
1929 * same as characters, since not utf8). If we have to match 3
1930 * characters, and there are only 2 availabe, we know without
1931 * trying that it will fail; so don't start a match past the
1932 * required minimum number from the far end */
1933 e = HOP3c(strend, -((SSize_t)ln), s);
1935 if (reginfo->intuit && e < s) {
1936 e = s; /* Due to minlen logic of intuit() */
1940 c2 = fold_array[c1];
1941 if (c1 == c2) { /* If char and fold are the same */
1942 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1945 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1953 /* If one of the operands is in utf8, we can't use the simpler folding
1954 * above, due to the fact that many different characters can have the
1955 * same fold, or portion of a fold, or different- length fold */
1956 pat_string = STRING(c);
1957 ln = STR_LEN(c); /* length to match in octets/bytes */
1958 pat_end = pat_string + ln;
1959 lnc = is_utf8_pat /* length to match in characters */
1960 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1963 /* We have 'lnc' characters to match in the pattern, but because of
1964 * multi-character folding, each character in the target can match
1965 * up to 3 characters (Unicode guarantees it will never exceed
1966 * this) if it is utf8-encoded; and up to 2 if not (based on the
1967 * fact that the Latin 1 folds are already determined, and the
1968 * only multi-char fold in that range is the sharp-s folding to
1969 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1970 * string character. Adjust lnc accordingly, rounding up, so that
1971 * if we need to match at least 4+1/3 chars, that really is 5. */
1972 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1973 lnc = (lnc + expansion - 1) / expansion;
1975 /* As in the non-UTF8 case, if we have to match 3 characters, and
1976 * only 2 are left, it's guaranteed to fail, so don't start a
1977 * match that would require us to go beyond the end of the string
1979 e = HOP3c(strend, -((SSize_t)lnc), s);
1981 if (reginfo->intuit && e < s) {
1982 e = s; /* Due to minlen logic of intuit() */
1985 /* XXX Note that we could recalculate e to stop the loop earlier,
1986 * as the worst case expansion above will rarely be met, and as we
1987 * go along we would usually find that e moves further to the left.
1988 * This would happen only after we reached the point in the loop
1989 * where if there were no expansion we should fail. Unclear if
1990 * worth the expense */
1993 char *my_strend= (char *)strend;
1994 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1995 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1996 && (reginfo->intuit || regtry(reginfo, &s)) )
2000 s += (utf8_target) ? UTF8SKIP(s) : 1;
2006 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2007 if (FLAGS(c) != TRADITIONAL_BOUND) {
2008 if (! IN_UTF8_CTYPE_LOCALE) {
2009 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2010 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2015 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2019 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2020 if (FLAGS(c) != TRADITIONAL_BOUND) {
2021 if (! IN_UTF8_CTYPE_LOCALE) {
2022 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2023 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2028 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2031 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2033 assert(FLAGS(c) == TRADITIONAL_BOUND);
2035 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2038 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2040 assert(FLAGS(c) == TRADITIONAL_BOUND);
2042 FBC_BOUND_A(isWORDCHAR_A);
2045 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2047 assert(FLAGS(c) == TRADITIONAL_BOUND);
2049 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2052 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2054 assert(FLAGS(c) == TRADITIONAL_BOUND);
2056 FBC_NBOUND_A(isWORDCHAR_A);
2060 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2061 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2072 switch((bound_type) FLAGS(c)) {
2073 case TRADITIONAL_BOUND:
2074 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2077 if (s == reginfo->strbeg) { /* GCB always matches at begin and
2079 if (to_complement ^ cBOOL(reginfo->intuit
2080 || regtry(reginfo, &s)))
2084 s += (utf8_target) ? UTF8SKIP(s) : 1;
2088 GCB_enum before = getGCB_VAL_UTF8(
2090 (U8*)(reginfo->strbeg)),
2091 (U8*) reginfo->strend);
2092 while (s < strend) {
2093 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2094 (U8*) reginfo->strend);
2095 if (to_complement ^ isGCB(before, after)) {
2096 if (reginfo->intuit || regtry(reginfo, &s)) {
2104 else { /* Not utf8. Everything is a GCB except between CR and
2106 while (s < strend) {
2107 if (to_complement ^ (UCHARAT(s - 1) != '\r'
2108 || UCHARAT(s) != '\n'))
2110 if (reginfo->intuit || regtry(reginfo, &s)) {
2118 if (to_complement ^ cBOOL(reginfo->intuit || regtry(reginfo, &s))) {
2124 if (s == reginfo->strbeg) { /* SB always matches at beginning */
2126 ^ cBOOL(reginfo->intuit || regtry(reginfo, &s)))
2131 /* Didn't match. Go try at the next position */
2132 s += (utf8_target) ? UTF8SKIP(s) : 1;
2136 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2138 (U8*)(reginfo->strbeg)),
2139 (U8*) reginfo->strend);
2140 while (s < strend) {
2141 SB_enum after = getSB_VAL_UTF8((U8*) s,
2142 (U8*) reginfo->strend);
2143 if (to_complement ^ isSB(before,
2145 (U8*) reginfo->strbeg,
2147 (U8*) reginfo->strend,
2150 if (reginfo->intuit || regtry(reginfo, &s)) {
2158 else { /* Not utf8. */
2159 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2160 while (s < strend) {
2161 SB_enum after = getSB_VAL_CP((U8) *s);
2162 if (to_complement ^ isSB(before,
2164 (U8*) reginfo->strbeg,
2166 (U8*) reginfo->strend,
2169 if (reginfo->intuit || regtry(reginfo, &s)) {
2178 /* Here are at the final position in the target string. The SB
2179 * value is always true here, so matches, depending on other
2181 if (to_complement ^ cBOOL(reginfo->intuit
2182 || regtry(reginfo, &s)))
2190 if (s == reginfo->strbeg) {
2191 if (to_complement ^ cBOOL(reginfo->intuit
2192 || regtry(reginfo, &s)))
2196 s += (utf8_target) ? UTF8SKIP(s) : 1;
2200 /* We are at a boundary between char_sub_0 and char_sub_1.
2201 * We also keep track of the value for char_sub_-1 as we
2202 * loop through the line. Context may be needed to make a
2203 * determination, and if so, this can save having to
2205 WB_enum previous = WB_UNKNOWN;
2206 WB_enum before = getWB_VAL_UTF8(
2209 (U8*)(reginfo->strbeg)),
2210 (U8*) reginfo->strend);
2211 while (s < strend) {
2212 WB_enum after = getWB_VAL_UTF8((U8*) s,
2213 (U8*) reginfo->strend);
2214 if (to_complement ^ isWB(previous,
2217 (U8*) reginfo->strbeg,
2219 (U8*) reginfo->strend,
2222 if (reginfo->intuit || regtry(reginfo, &s)) {
2231 else { /* Not utf8. */
2232 WB_enum previous = WB_UNKNOWN;
2233 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2234 while (s < strend) {
2235 WB_enum after = getWB_VAL_CP((U8) *s);
2236 if (to_complement ^ isWB(previous,
2239 (U8*) reginfo->strbeg,
2241 (U8*) reginfo->strend,
2244 if (reginfo->intuit || regtry(reginfo, &s)) {
2254 if (to_complement ^ cBOOL(reginfo->intuit
2255 || regtry(reginfo, &s)))
2265 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2266 is_LNBREAK_latin1_safe(s, strend)
2270 /* The argument to all the POSIX node types is the class number to pass to
2271 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2278 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2279 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2280 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2295 /* The complement of something that matches only ASCII matches all
2296 * non-ASCII, plus everything in ASCII that isn't in the class. */
2297 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2298 || ! _generic_isCC_A(*s, FLAGS(c)));
2307 /* Don't need to worry about utf8, as it can match only a single
2308 * byte invariant character. */
2309 REXEC_FBC_CLASS_SCAN(
2310 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2318 if (! utf8_target) {
2319 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2325 classnum = (_char_class_number) FLAGS(c);
2326 if (classnum < _FIRST_NON_SWASH_CC) {
2327 while (s < strend) {
2329 /* We avoid loading in the swash as long as possible, but
2330 * should we have to, we jump to a separate loop. This
2331 * extra 'if' statement is what keeps this code from being
2332 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2333 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2334 goto found_above_latin1;
2336 if ((UTF8_IS_INVARIANT(*s)
2337 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2339 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2340 && to_complement ^ cBOOL(
2341 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2345 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2357 else switch (classnum) { /* These classes are implemented as
2359 case _CC_ENUM_SPACE:
2360 REXEC_FBC_UTF8_CLASS_SCAN(
2361 to_complement ^ cBOOL(isSPACE_utf8(s)));
2364 case _CC_ENUM_BLANK:
2365 REXEC_FBC_UTF8_CLASS_SCAN(
2366 to_complement ^ cBOOL(isBLANK_utf8(s)));
2369 case _CC_ENUM_XDIGIT:
2370 REXEC_FBC_UTF8_CLASS_SCAN(
2371 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2374 case _CC_ENUM_VERTSPACE:
2375 REXEC_FBC_UTF8_CLASS_SCAN(
2376 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2379 case _CC_ENUM_CNTRL:
2380 REXEC_FBC_UTF8_CLASS_SCAN(
2381 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2385 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2386 NOT_REACHED; /* NOTREACHED */
2391 found_above_latin1: /* Here we have to load a swash to get the result
2392 for the current code point */
2393 if (! PL_utf8_swash_ptrs[classnum]) {
2394 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2395 PL_utf8_swash_ptrs[classnum] =
2396 _core_swash_init("utf8",
2399 PL_XPosix_ptrs[classnum], &flags);
2402 /* This is a copy of the loop above for swash classes, though using the
2403 * FBC macro instead of being expanded out. Since we've loaded the
2404 * swash, we don't have to check for that each time through the loop */
2405 REXEC_FBC_UTF8_CLASS_SCAN(
2406 to_complement ^ cBOOL(_generic_utf8(
2409 swash_fetch(PL_utf8_swash_ptrs[classnum],
2417 /* what trie are we using right now */
2418 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2419 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2420 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2422 const char *last_start = strend - trie->minlen;
2424 const char *real_start = s;
2426 STRLEN maxlen = trie->maxlen;
2428 U8 **points; /* map of where we were in the input string
2429 when reading a given char. For ASCII this
2430 is unnecessary overhead as the relationship
2431 is always 1:1, but for Unicode, especially
2432 case folded Unicode this is not true. */
2433 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2437 GET_RE_DEBUG_FLAGS_DECL;
2439 /* We can't just allocate points here. We need to wrap it in
2440 * an SV so it gets freed properly if there is a croak while
2441 * running the match */
2444 sv_points=newSV(maxlen * sizeof(U8 *));
2445 SvCUR_set(sv_points,
2446 maxlen * sizeof(U8 *));
2447 SvPOK_on(sv_points);
2448 sv_2mortal(sv_points);
2449 points=(U8**)SvPV_nolen(sv_points );
2450 if ( trie_type != trie_utf8_fold
2451 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2454 bitmap=(U8*)trie->bitmap;
2456 bitmap=(U8*)ANYOF_BITMAP(c);
2458 /* this is the Aho-Corasick algorithm modified a touch
2459 to include special handling for long "unknown char" sequences.
2460 The basic idea being that we use AC as long as we are dealing
2461 with a possible matching char, when we encounter an unknown char
2462 (and we have not encountered an accepting state) we scan forward
2463 until we find a legal starting char.
2464 AC matching is basically that of trie matching, except that when
2465 we encounter a failing transition, we fall back to the current
2466 states "fail state", and try the current char again, a process
2467 we repeat until we reach the root state, state 1, or a legal
2468 transition. If we fail on the root state then we can either
2469 terminate if we have reached an accepting state previously, or
2470 restart the entire process from the beginning if we have not.
2473 while (s <= last_start) {
2474 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2482 U8 *uscan = (U8*)NULL;
2483 U8 *leftmost = NULL;
2485 U32 accepted_word= 0;
2489 while ( state && uc <= (U8*)strend ) {
2491 U32 word = aho->states[ state ].wordnum;
2495 DEBUG_TRIE_EXECUTE_r(
2496 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2497 dump_exec_pos( (char *)uc, c, strend, real_start,
2498 (char *)uc, utf8_target );
2499 PerlIO_printf( Perl_debug_log,
2500 " Scanning for legal start char...\n");
2504 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2508 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2514 if (uc >(U8*)last_start) break;
2518 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2519 if (!leftmost || lpos < leftmost) {
2520 DEBUG_r(accepted_word=word);
2526 points[pointpos++ % maxlen]= uc;
2527 if (foldlen || uc < (U8*)strend) {
2528 REXEC_TRIE_READ_CHAR(trie_type, trie,
2530 uscan, len, uvc, charid, foldlen,
2532 DEBUG_TRIE_EXECUTE_r({
2533 dump_exec_pos( (char *)uc, c, strend,
2534 real_start, s, utf8_target);
2535 PerlIO_printf(Perl_debug_log,
2536 " Charid:%3u CP:%4"UVxf" ",
2548 word = aho->states[ state ].wordnum;
2550 base = aho->states[ state ].trans.base;
2552 DEBUG_TRIE_EXECUTE_r({
2554 dump_exec_pos( (char *)uc, c, strend, real_start,
2556 PerlIO_printf( Perl_debug_log,
2557 "%sState: %4"UVxf", word=%"UVxf,
2558 failed ? " Fail transition to " : "",
2559 (UV)state, (UV)word);
2565 ( ((offset = base + charid
2566 - 1 - trie->uniquecharcount)) >= 0)
2567 && ((U32)offset < trie->lasttrans)
2568 && trie->trans[offset].check == state
2569 && (tmp=trie->trans[offset].next))
2571 DEBUG_TRIE_EXECUTE_r(
2572 PerlIO_printf( Perl_debug_log," - legal\n"));
2577 DEBUG_TRIE_EXECUTE_r(
2578 PerlIO_printf( Perl_debug_log," - fail\n"));
2580 state = aho->fail[state];
2584 /* we must be accepting here */
2585 DEBUG_TRIE_EXECUTE_r(
2586 PerlIO_printf( Perl_debug_log," - accepting\n"));
2595 if (!state) state = 1;
2598 if ( aho->states[ state ].wordnum ) {
2599 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2600 if (!leftmost || lpos < leftmost) {
2601 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2606 s = (char*)leftmost;
2607 DEBUG_TRIE_EXECUTE_r({
2609 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2610 (UV)accepted_word, (IV)(s - real_start)
2613 if (reginfo->intuit || regtry(reginfo, &s)) {
2619 DEBUG_TRIE_EXECUTE_r({
2620 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2623 DEBUG_TRIE_EXECUTE_r(
2624 PerlIO_printf( Perl_debug_log,"No match.\n"));
2633 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2640 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2641 * flags have same meanings as with regexec_flags() */
2644 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2651 struct regexp *const prog = ReANY(rx);
2653 if (flags & REXEC_COPY_STR) {
2657 PerlIO_printf(Perl_debug_log,
2658 "Copy on write: regexp capture, type %d\n",
2661 /* Create a new COW SV to share the match string and store
2662 * in saved_copy, unless the current COW SV in saved_copy
2663 * is valid and suitable for our purpose */
2664 if (( prog->saved_copy
2665 && SvIsCOW(prog->saved_copy)
2666 && SvPOKp(prog->saved_copy)
2669 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2671 /* just reuse saved_copy SV */
2672 if (RXp_MATCH_COPIED(prog)) {
2673 Safefree(prog->subbeg);
2674 RXp_MATCH_COPIED_off(prog);
2678 /* create new COW SV to share string */
2679 RX_MATCH_COPY_FREE(rx);
2680 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2682 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2683 assert (SvPOKp(prog->saved_copy));
2684 prog->sublen = strend - strbeg;
2685 prog->suboffset = 0;
2686 prog->subcoffset = 0;
2691 SSize_t max = strend - strbeg;
2694 if ( (flags & REXEC_COPY_SKIP_POST)
2695 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2696 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2697 ) { /* don't copy $' part of string */
2700 /* calculate the right-most part of the string covered
2701 * by a capture. Due to look-ahead, this may be to
2702 * the right of $&, so we have to scan all captures */
2703 while (n <= prog->lastparen) {
2704 if (prog->offs[n].end > max)
2705 max = prog->offs[n].end;
2709 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2710 ? prog->offs[0].start
2712 assert(max >= 0 && max <= strend - strbeg);
2715 if ( (flags & REXEC_COPY_SKIP_PRE)
2716 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2717 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2718 ) { /* don't copy $` part of string */
2721 /* calculate the left-most part of the string covered
2722 * by a capture. Due to look-behind, this may be to
2723 * the left of $&, so we have to scan all captures */
2724 while (min && n <= prog->lastparen) {
2725 if ( prog->offs[n].start != -1
2726 && prog->offs[n].start < min)
2728 min = prog->offs[n].start;
2732 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2733 && min > prog->offs[0].end
2735 min = prog->offs[0].end;
2739 assert(min >= 0 && min <= max && min <= strend - strbeg);
2742 if (RX_MATCH_COPIED(rx)) {
2743 if (sublen > prog->sublen)
2745 (char*)saferealloc(prog->subbeg, sublen+1);
2748 prog->subbeg = (char*)safemalloc(sublen+1);
2749 Copy(strbeg + min, prog->subbeg, sublen, char);
2750 prog->subbeg[sublen] = '\0';
2751 prog->suboffset = min;
2752 prog->sublen = sublen;
2753 RX_MATCH_COPIED_on(rx);
2755 prog->subcoffset = prog->suboffset;
2756 if (prog->suboffset && utf8_target) {
2757 /* Convert byte offset to chars.
2758 * XXX ideally should only compute this if @-/@+
2759 * has been seen, a la PL_sawampersand ??? */
2761 /* If there's a direct correspondence between the
2762 * string which we're matching and the original SV,
2763 * then we can use the utf8 len cache associated with
2764 * the SV. In particular, it means that under //g,
2765 * sv_pos_b2u() will use the previously cached
2766 * position to speed up working out the new length of
2767 * subcoffset, rather than counting from the start of
2768 * the string each time. This stops
2769 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2770 * from going quadratic */
2771 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2772 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2773 SV_GMAGIC|SV_CONST_RETURN);
2775 prog->subcoffset = utf8_length((U8*)strbeg,
2776 (U8*)(strbeg+prog->suboffset));
2780 RX_MATCH_COPY_FREE(rx);
2781 prog->subbeg = strbeg;
2782 prog->suboffset = 0;
2783 prog->subcoffset = 0;
2784 prog->sublen = strend - strbeg;
2792 - regexec_flags - match a regexp against a string
2795 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2796 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2797 /* stringarg: the point in the string at which to begin matching */
2798 /* strend: pointer to null at end of string */
2799 /* strbeg: real beginning of string */
2800 /* minend: end of match must be >= minend bytes after stringarg. */
2801 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2802 * itself is accessed via the pointers above */
2803 /* data: May be used for some additional optimizations.
2804 Currently unused. */
2805 /* flags: For optimizations. See REXEC_* in regexp.h */
2808 struct regexp *const prog = ReANY(rx);
2812 SSize_t minlen; /* must match at least this many chars */
2813 SSize_t dontbother = 0; /* how many characters not to try at end */
2814 const bool utf8_target = cBOOL(DO_UTF8(sv));
2816 RXi_GET_DECL(prog,progi);
2817 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2818 regmatch_info *const reginfo = ®info_buf;
2819 regexp_paren_pair *swap = NULL;
2821 GET_RE_DEBUG_FLAGS_DECL;
2823 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2824 PERL_UNUSED_ARG(data);
2826 /* Be paranoid... */
2828 Perl_croak(aTHX_ "NULL regexp parameter");
2832 debug_start_match(rx, utf8_target, stringarg, strend,
2836 startpos = stringarg;
2838 if (prog->intflags & PREGf_GPOS_SEEN) {
2841 /* set reginfo->ganch, the position where \G can match */
2844 (flags & REXEC_IGNOREPOS)
2845 ? stringarg /* use start pos rather than pos() */
2846 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2847 /* Defined pos(): */
2848 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2849 : strbeg; /* pos() not defined; use start of string */
2851 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2852 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2854 /* in the presence of \G, we may need to start looking earlier in
2855 * the string than the suggested start point of stringarg:
2856 * if prog->gofs is set, then that's a known, fixed minimum
2859 * /ab|c\G/: gofs = 1
2860 * or if the minimum offset isn't known, then we have to go back
2861 * to the start of the string, e.g. /w+\G/
2864 if (prog->intflags & PREGf_ANCH_GPOS) {
2865 startpos = reginfo->ganch - prog->gofs;
2867 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2869 DEBUG_r(PerlIO_printf(Perl_debug_log,
2870 "fail: ganch-gofs before earliest possible start\n"));
2874 else if (prog->gofs) {
2875 if (startpos - prog->gofs < strbeg)
2878 startpos -= prog->gofs;
2880 else if (prog->intflags & PREGf_GPOS_FLOAT)
2884 minlen = prog->minlen;
2885 if ((startpos + minlen) > strend || startpos < strbeg) {
2886 DEBUG_r(PerlIO_printf(Perl_debug_log,
2887 "Regex match can't succeed, so not even tried\n"));
2891 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2892 * which will call destuctors to reset PL_regmatch_state, free higher
2893 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2894 * regmatch_info_aux_eval */
2896 oldsave = PL_savestack_ix;
2900 if ((prog->extflags & RXf_USE_INTUIT)
2901 && !(flags & REXEC_CHECKED))
2903 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2908 if (prog->extflags & RXf_CHECK_ALL) {
2909 /* we can match based purely on the result of INTUIT.
2910 * Set up captures etc just for $& and $-[0]
2911 * (an intuit-only match wont have $1,$2,..) */
2912 assert(!prog->nparens);
2914 /* s/// doesn't like it if $& is earlier than where we asked it to
2915 * start searching (which can happen on something like /.\G/) */
2916 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2919 /* this should only be possible under \G */
2920 assert(prog->intflags & PREGf_GPOS_SEEN);
2921 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2922 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2926 /* match via INTUIT shouldn't have any captures.
2927 * Let @-, @+, $^N know */
2928 prog->lastparen = prog->lastcloseparen = 0;
2929 RX_MATCH_UTF8_set(rx, utf8_target);
2930 prog->offs[0].start = s - strbeg;
2931 prog->offs[0].end = utf8_target
2932 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2933 : s - strbeg + prog->minlenret;
2934 if ( !(flags & REXEC_NOT_FIRST) )
2935 S_reg_set_capture_string(aTHX_ rx,
2937 sv, flags, utf8_target);
2943 multiline = prog->extflags & RXf_PMf_MULTILINE;
2945 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2946 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2947 "String too short [regexec_flags]...\n"));
2951 /* Check validity of program. */
2952 if (UCHARAT(progi->program) != REG_MAGIC) {
2953 Perl_croak(aTHX_ "corrupted regexp program");
2956 RX_MATCH_TAINTED_off(rx);
2957 RX_MATCH_UTF8_set(rx, utf8_target);
2959 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2960 reginfo->intuit = 0;
2961 reginfo->is_utf8_target = cBOOL(utf8_target);
2962 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2963 reginfo->warned = FALSE;
2964 reginfo->strbeg = strbeg;
2966 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2967 reginfo->strend = strend;
2968 /* see how far we have to get to not match where we matched before */
2969 reginfo->till = stringarg + minend;
2971 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2972 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2973 S_cleanup_regmatch_info_aux has executed (registered by
2974 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2975 magic belonging to this SV.
2976 Not newSVsv, either, as it does not COW.
2978 reginfo->sv = newSV(0);
2979 SvSetSV_nosteal(reginfo->sv, sv);
2980 SAVEFREESV(reginfo->sv);
2983 /* reserve next 2 or 3 slots in PL_regmatch_state:
2984 * slot N+0: may currently be in use: skip it
2985 * slot N+1: use for regmatch_info_aux struct
2986 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2987 * slot N+3: ready for use by regmatch()
2991 regmatch_state *old_regmatch_state;
2992 regmatch_slab *old_regmatch_slab;
2993 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2995 /* on first ever match, allocate first slab */
2996 if (!PL_regmatch_slab) {
2997 Newx(PL_regmatch_slab, 1, regmatch_slab);
2998 PL_regmatch_slab->prev = NULL;
2999 PL_regmatch_slab->next = NULL;
3000 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3003 old_regmatch_state = PL_regmatch_state;
3004 old_regmatch_slab = PL_regmatch_slab;
3006 for (i=0; i <= max; i++) {
3008 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3010 reginfo->info_aux_eval =
3011 reginfo->info_aux->info_aux_eval =
3012 &(PL_regmatch_state->u.info_aux_eval);
3014 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3015 PL_regmatch_state = S_push_slab(aTHX);
3018 /* note initial PL_regmatch_state position; at end of match we'll
3019 * pop back to there and free any higher slabs */
3021 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3022 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3023 reginfo->info_aux->poscache = NULL;
3025 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3027 if ((prog->extflags & RXf_EVAL_SEEN))
3028 S_setup_eval_state(aTHX_ reginfo);
3030 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3033 /* If there is a "must appear" string, look for it. */
3035 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3036 /* We have to be careful. If the previous successful match
3037 was from this regex we don't want a subsequent partially
3038 successful match to clobber the old results.
3039 So when we detect this possibility we add a swap buffer
3040 to the re, and switch the buffer each match. If we fail,
3041 we switch it back; otherwise we leave it swapped.
3044 /* do we need a save destructor here for eval dies? */
3045 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3046 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3047 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3054 /* Simplest case: anchored match need be tried only once, or with
3055 * MBOL, only at the beginning of each line.
3057 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3058 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3059 * match at the start of the string then it won't match anywhere else
3060 * either; while with /.*.../, if it doesn't match at the beginning,
3061 * the earliest it could match is at the start of the next line */
3063 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3066 if (regtry(reginfo, &s))
3069 if (!(prog->intflags & PREGf_ANCH_MBOL))
3072 /* didn't match at start, try at other newline positions */
3075 dontbother = minlen - 1;
3076 end = HOP3c(strend, -dontbother, strbeg) - 1;
3078 /* skip to next newline */
3080 while (s <= end) { /* note it could be possible to match at the end of the string */
3081 /* NB: newlines are the same in unicode as they are in latin */
3084 if (prog->check_substr || prog->check_utf8) {
3085 /* note that with PREGf_IMPLICIT, intuit can only fail
3086 * or return the start position, so it's of limited utility.
3087 * Nevertheless, I made the decision that the potential for
3088 * quick fail was still worth it - DAPM */
3089 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3093 if (regtry(reginfo, &s))
3097 } /* end anchored search */
3099 if (prog->intflags & PREGf_ANCH_GPOS)
3101 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3102 assert(prog->intflags & PREGf_GPOS_SEEN);
3103 /* For anchored \G, the only position it can match from is
3104 * (ganch-gofs); we already set startpos to this above; if intuit
3105 * moved us on from there, we can't possibly succeed */
3106 assert(startpos == reginfo->ganch - prog->gofs);
3107 if (s == startpos && regtry(reginfo, &s))
3112 /* Messy cases: unanchored match. */
3113 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3114 /* we have /x+whatever/ */
3115 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3121 if (! prog->anchored_utf8) {
3122 to_utf8_substr(prog);
3124 ch = SvPVX_const(prog->anchored_utf8)[0];
3127 DEBUG_EXECUTE_r( did_match = 1 );
3128 if (regtry(reginfo, &s)) goto got_it;
3130 while (s < strend && *s == ch)
3137 if (! prog->anchored_substr) {
3138 if (! to_byte_substr(prog)) {
3139 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3142 ch = SvPVX_const(prog->anchored_substr)[0];
3145 DEBUG_EXECUTE_r( did_match = 1 );
3146 if (regtry(reginfo, &s)) goto got_it;
3148 while (s < strend && *s == ch)
3153 DEBUG_EXECUTE_r(if (!did_match)
3154 PerlIO_printf(Perl_debug_log,
3155 "Did not find anchored character...\n")
3158 else if (prog->anchored_substr != NULL
3159 || prog->anchored_utf8 != NULL
3160 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3161 && prog->float_max_offset < strend - s)) {
3166 char *last1; /* Last position checked before */
3170 if (prog->anchored_substr || prog->anchored_utf8) {
3172 if (! prog->anchored_utf8) {
3173 to_utf8_substr(prog);
3175 must = prog->anchored_utf8;
3178 if (! prog->anchored_substr) {
3179 if (! to_byte_substr(prog)) {
3180 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3183 must = prog->anchored_substr;
3185 back_max = back_min = prog->anchored_offset;
3188 if (! prog->float_utf8) {
3189 to_utf8_substr(prog);
3191 must = prog->float_utf8;
3194 if (! prog->float_substr) {
3195 if (! to_byte_substr(prog)) {
3196 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3199 must = prog->float_substr;
3201 back_max = prog->float_max_offset;
3202 back_min = prog->float_min_offset;
3208 last = HOP3c(strend, /* Cannot start after this */
3209 -(SSize_t)(CHR_SVLEN(must)
3210 - (SvTAIL(must) != 0) + back_min), strbeg);
3212 if (s > reginfo->strbeg)
3213 last1 = HOPc(s, -1);
3215 last1 = s - 1; /* bogus */
3217 /* XXXX check_substr already used to find "s", can optimize if
3218 check_substr==must. */
3220 strend = HOPc(strend, -dontbother);
3221 while ( (s <= last) &&
3222 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3223 (unsigned char*)strend, must,
3224 multiline ? FBMrf_MULTILINE : 0)) ) {
3225 DEBUG_EXECUTE_r( did_match = 1 );
3226 if (HOPc(s, -back_max) > last1) {
3227 last1 = HOPc(s, -back_min);
3228 s = HOPc(s, -back_max);
3231 char * const t = (last1 >= reginfo->strbeg)
3232 ? HOPc(last1, 1) : last1 + 1;
3234 last1 = HOPc(s, -back_min);
3238 while (s <= last1) {
3239 if (regtry(reginfo, &s))
3242 s++; /* to break out of outer loop */
3249 while (s <= last1) {
3250 if (regtry(reginfo, &s))
3256 DEBUG_EXECUTE_r(if (!did_match) {
3257 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3258 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3259 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3260 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3261 ? "anchored" : "floating"),
3262 quoted, RE_SV_TAIL(must));
3266 else if ( (c = progi->regstclass) ) {
3268 const OPCODE op = OP(progi->regstclass);
3269 /* don't bother with what can't match */
3270 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
3271 strend = HOPc(strend, -(minlen - 1));
3274 SV * const prop = sv_newmortal();
3275 regprop(prog, prop, c, reginfo, NULL);
3277 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3279 PerlIO_printf(Perl_debug_log,
3280 "Matching stclass %.*s against %s (%d bytes)\n",
3281 (int)SvCUR(prop), SvPVX_const(prop),
3282 quoted, (int)(strend - s));
3285 if (find_byclass(prog, c, s, strend, reginfo))
3287 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3291 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3299 if (! prog->float_utf8) {
3300 to_utf8_substr(prog);
3302 float_real = prog->float_utf8;
3305 if (! prog->float_substr) {
3306 if (! to_byte_substr(prog)) {
3307 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3310 float_real = prog->float_substr;
3313 little = SvPV_const(float_real, len);
3314 if (SvTAIL(float_real)) {
3315 /* This means that float_real contains an artificial \n on
3316 * the end due to the presence of something like this:
3317 * /foo$/ where we can match both "foo" and "foo\n" at the
3318 * end of the string. So we have to compare the end of the
3319 * string first against the float_real without the \n and
3320 * then against the full float_real with the string. We
3321 * have to watch out for cases where the string might be
3322 * smaller than the float_real or the float_real without
3324 char *checkpos= strend - len;
3326 PerlIO_printf(Perl_debug_log,
3327 "%sChecking for float_real.%s\n",
3328 PL_colors[4], PL_colors[5]));
3329 if (checkpos + 1 < strbeg) {
3330 /* can't match, even if we remove the trailing \n
3331 * string is too short to match */
3333 PerlIO_printf(Perl_debug_log,
3334 "%sString shorter than required trailing substring, cannot match.%s\n",
3335 PL_colors[4], PL_colors[5]));
3337 } else if (memEQ(checkpos + 1, little, len - 1)) {
3338 /* can match, the end of the string matches without the
3340 last = checkpos + 1;
3341 } else if (checkpos < strbeg) {
3342 /* cant match, string is too short when the "\n" is
3345 PerlIO_printf(Perl_debug_log,
3346 "%sString does not contain required trailing substring, cannot match.%s\n",
3347 PL_colors[4], PL_colors[5]));
3349 } else if (!multiline) {
3350 /* non multiline match, so compare with the "\n" at the
3351 * end of the string */
3352 if (memEQ(checkpos, little, len)) {
3356 PerlIO_printf(Perl_debug_log,
3357 "%sString does not contain required trailing substring, cannot match.%s\n",
3358 PL_colors[4], PL_colors[5]));
3362 /* multiline match, so we have to search for a place
3363 * where the full string is located */
3369 last = rninstr(s, strend, little, little + len);
3371 last = strend; /* matching "$" */
3374 /* at one point this block contained a comment which was
3375 * probably incorrect, which said that this was a "should not
3376 * happen" case. Even if it was true when it was written I am
3377 * pretty sure it is not anymore, so I have removed the comment
3378 * and replaced it with this one. Yves */
3380 PerlIO_printf(Perl_debug_log,
3381 "%sString does not contain required substring, cannot match.%s\n",
3382 PL_colors[4], PL_colors[5]
3386 dontbother = strend - last + prog->float_min_offset;
3388 if (minlen && (dontbother < minlen))
3389 dontbother = minlen - 1;
3390 strend -= dontbother; /* this one's always in bytes! */
3391 /* We don't know much -- general case. */
3394 if (regtry(reginfo, &s))
3403 if (regtry(reginfo, &s))
3405 } while (s++ < strend);
3413 /* s/// doesn't like it if $& is earlier than where we asked it to
3414 * start searching (which can happen on something like /.\G/) */
3415 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3416 && (prog->offs[0].start < stringarg - strbeg))
3418 /* this should only be possible under \G */
3419 assert(prog->intflags & PREGf_GPOS_SEEN);
3420 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3421 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3427 PerlIO_printf(Perl_debug_log,
3428 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3435 /* clean up; this will trigger destructors that will free all slabs
3436 * above the current one, and cleanup the regmatch_info_aux
3437 * and regmatch_info_aux_eval sructs */
3439 LEAVE_SCOPE(oldsave);
3441 if (RXp_PAREN_NAMES(prog))
3442 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3444 /* make sure $`, $&, $', and $digit will work later */
3445 if ( !(flags & REXEC_NOT_FIRST) )
3446 S_reg_set_capture_string(aTHX_ rx,
3447 strbeg, reginfo->strend,
3448 sv, flags, utf8_target);
3453 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3454 PL_colors[4], PL_colors[5]));
3456 /* clean up; this will trigger destructors that will free all slabs
3457 * above the current one, and cleanup the regmatch_info_aux
3458 * and regmatch_info_aux_eval sructs */
3460 LEAVE_SCOPE(oldsave);
3463 /* we failed :-( roll it back */
3464 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3465 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3470 Safefree(prog->offs);
3477 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3478 * Do inc before dec, in case old and new rex are the same */
3479 #define SET_reg_curpm(Re2) \
3480 if (reginfo->info_aux_eval) { \
3481 (void)ReREFCNT_inc(Re2); \
3482 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3483 PM_SETRE((PL_reg_curpm), (Re2)); \
3488 - regtry - try match at specific point
3490 STATIC I32 /* 0 failure, 1 success */
3491 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3494 REGEXP *const rx = reginfo->prog;
3495 regexp *const prog = ReANY(rx);
3497 RXi_GET_DECL(prog,progi);
3498 GET_RE_DEBUG_FLAGS_DECL;
3500 PERL_ARGS_ASSERT_REGTRY;
3502 reginfo->cutpoint=NULL;
3504 prog->offs[0].start = *startposp - reginfo->strbeg;
3505 prog->lastparen = 0;
3506 prog->lastcloseparen = 0;
3508 /* XXXX What this code is doing here?!!! There should be no need
3509 to do this again and again, prog->lastparen should take care of
3512 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3513 * Actually, the code in regcppop() (which Ilya may be meaning by
3514 * prog->lastparen), is not needed at all by the test suite
3515 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3516 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3517 * Meanwhile, this code *is* needed for the
3518 * above-mentioned test suite tests to succeed. The common theme
3519 * on those tests seems to be returning null fields from matches.
3520 * --jhi updated by dapm */
3522 if (prog->nparens) {
3523 regexp_paren_pair *pp = prog->offs;
3525 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3533 result = regmatch(reginfo, *startposp, progi->program + 1);
3535 prog->offs[0].end = result;
3538 if (reginfo->cutpoint)
3539 *startposp= reginfo->cutpoint;
3540 REGCP_UNWIND(lastcp);
3545 #define sayYES goto yes
3546 #define sayNO goto no
3547 #define sayNO_SILENT goto no_silent
3549 /* we dont use STMT_START/END here because it leads to
3550 "unreachable code" warnings, which are bogus, but distracting. */
3551 #define CACHEsayNO \
3552 if (ST.cache_mask) \
3553 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3556 /* this is used to determine how far from the left messages like
3557 'failed...' are printed. It should be set such that messages
3558 are inline with the regop output that created them.
3560 #define REPORT_CODE_OFF 32
3563 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3564 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3565 #define CHRTEST_NOT_A_CP_1 -999
3566 #define CHRTEST_NOT_A_CP_2 -998
3568 /* grab a new slab and return the first slot in it */
3570 STATIC regmatch_state *
3573 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3576 regmatch_slab *s = PL_regmatch_slab->next;
3578 Newx(s, 1, regmatch_slab);
3579 s->prev = PL_regmatch_slab;
3581 PL_regmatch_slab->next = s;
3583 PL_regmatch_slab = s;
3584 return SLAB_FIRST(s);
3588 /* push a new state then goto it */
3590 #define PUSH_STATE_GOTO(state, node, input) \
3591 pushinput = input; \
3593 st->resume_state = state; \
3596 /* push a new state with success backtracking, then goto it */
3598 #define PUSH_YES_STATE_GOTO(state, node, input) \
3599 pushinput = input; \
3601 st->resume_state = state; \
3602 goto push_yes_state;
3609 regmatch() - main matching routine
3611 This is basically one big switch statement in a loop. We execute an op,
3612 set 'next' to point the next op, and continue. If we come to a point which
3613 we may need to backtrack to on failure such as (A|B|C), we push a
3614 backtrack state onto the backtrack stack. On failure, we pop the top
3615 state, and re-enter the loop at the state indicated. If there are no more
3616 states to pop, we return failure.
3618 Sometimes we also need to backtrack on success; for example /A+/, where
3619 after successfully matching one A, we need to go back and try to
3620 match another one; similarly for lookahead assertions: if the assertion
3621 completes successfully, we backtrack to the state just before the assertion
3622 and then carry on. In these cases, the pushed state is marked as
3623 'backtrack on success too'. This marking is in fact done by a chain of
3624 pointers, each pointing to the previous 'yes' state. On success, we pop to
3625 the nearest yes state, discarding any intermediate failure-only states.
3626 Sometimes a yes state is pushed just to force some cleanup code to be
3627 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3628 it to free the inner regex.
3630 Note that failure backtracking rewinds the cursor position, while
3631 success backtracking leaves it alone.
3633 A pattern is complete when the END op is executed, while a subpattern
3634 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3635 ops trigger the "pop to last yes state if any, otherwise return true"
3638 A common convention in this function is to use A and B to refer to the two
3639 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3640 the subpattern to be matched possibly multiple times, while B is the entire
3641 rest of the pattern. Variable and state names reflect this convention.
3643 The states in the main switch are the union of ops and failure/success of
3644 substates associated with with that op. For example, IFMATCH is the op
3645 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3646 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3647 successfully matched A and IFMATCH_A_fail is a state saying that we have
3648 just failed to match A. Resume states always come in pairs. The backtrack
3649 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3650 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3651 on success or failure.
3653 The struct that holds a backtracking state is actually a big union, with
3654 one variant for each major type of op. The variable st points to the
3655 top-most backtrack struct. To make the code clearer, within each
3656 block of code we #define ST to alias the relevant union.
3658 Here's a concrete example of a (vastly oversimplified) IFMATCH
3664 #define ST st->u.ifmatch
3666 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3667 ST.foo = ...; // some state we wish to save
3669 // push a yes backtrack state with a resume value of
3670 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3672 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3675 case IFMATCH_A: // we have successfully executed A; now continue with B
3677 bar = ST.foo; // do something with the preserved value
3680 case IFMATCH_A_fail: // A failed, so the assertion failed
3681 ...; // do some housekeeping, then ...
3682 sayNO; // propagate the failure
3689 For any old-timers reading this who are familiar with the old recursive
3690 approach, the code above is equivalent to:
3692 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3701 ...; // do some housekeeping, then ...
3702 sayNO; // propagate the failure
3705 The topmost backtrack state, pointed to by st, is usually free. If you
3706 want to claim it, populate any ST.foo fields in it with values you wish to
3707 save, then do one of
3709 PUSH_STATE_GOTO(resume_state, node, newinput);
3710 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3712 which sets that backtrack state's resume value to 'resume_state', pushes a
3713 new free entry to the top of the backtrack stack, then goes to 'node'.
3714 On backtracking, the free slot is popped, and the saved state becomes the
3715 new free state. An ST.foo field in this new top state can be temporarily
3716 accessed to retrieve values, but once the main loop is re-entered, it
3717 becomes available for reuse.
3719 Note that the depth of the backtrack stack constantly increases during the
3720 left-to-right execution of the pattern, rather than going up and down with
3721 the pattern nesting. For example the stack is at its maximum at Z at the
3722 end of the pattern, rather than at X in the following:
3724 /(((X)+)+)+....(Y)+....Z/
3726 The only exceptions to this are lookahead/behind assertions and the cut,
3727 (?>A), which pop all the backtrack states associated with A before
3730 Backtrack state structs are allocated in slabs of about 4K in size.
3731 PL_regmatch_state and st always point to the currently active state,
3732 and PL_regmatch_slab points to the slab currently containing
3733 PL_regmatch_state. The first time regmatch() is called, the first slab is
3734 allocated, and is never freed until interpreter destruction. When the slab
3735 is full, a new one is allocated and chained to the end. At exit from
3736 regmatch(), slabs allocated since entry are freed.
3741 #define DEBUG_STATE_pp(pp) \
3743 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3744 PerlIO_printf(Perl_debug_log, \
3745 " %*s"pp" %s%s%s%s%s\n", \
3747 PL_reg_name[st->resume_state], \
3748 ((st==yes_state||st==mark_state) ? "[" : ""), \
3749 ((st==yes_state) ? "Y" : ""), \
3750 ((st==mark_state) ? "M" : ""), \
3751 ((st==yes_state||st==mark_state) ? "]" : "") \
3756 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3761 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3762 const char *start, const char *end, const char *blurb)
3764 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3766 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3771 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3772 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3774 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3775 start, end - start, 60);
3777 PerlIO_printf(Perl_debug_log,
3778 "%s%s REx%s %s against %s\n",
3779 PL_colors[4], blurb, PL_colors[5], s0, s1);
3781 if (utf8_target||utf8_pat)
3782 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3783 utf8_pat ? "pattern" : "",
3784 utf8_pat && utf8_target ? " and " : "",
3785 utf8_target ? "string" : ""
3791 S_dump_exec_pos(pTHX_ const char *locinput,
3792 const regnode *scan,
3793 const char *loc_regeol,
3794 const char *loc_bostr,
3795 const char *loc_reg_starttry,
3796 const bool utf8_target)
3798 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3799 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3800 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3801 /* The part of the string before starttry has one color
3802 (pref0_len chars), between starttry and current
3803 position another one (pref_len - pref0_len chars),
3804 after the current position the third one.
3805 We assume that pref0_len <= pref_len, otherwise we
3806 decrease pref0_len. */
3807 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3808 ? (5 + taill) - l : locinput - loc_bostr;
3811 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3813 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3815 pref0_len = pref_len - (locinput - loc_reg_starttry);
3816 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3817 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3818 ? (5 + taill) - pref_len : loc_regeol - locinput);
3819 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3823 if (pref0_len > pref_len)
3824 pref0_len = pref_len;
3826 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3828 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3829 (locinput - pref_len),pref0_len, 60, 4, 5);
3831 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3832 (locinput - pref_len + pref0_len),
3833 pref_len - pref0_len, 60, 2, 3);
3835 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3836 locinput, loc_regeol - locinput, 10, 0, 1);
3838 const STRLEN tlen=len0+len1+len2;
3839 PerlIO_printf(Perl_debug_log,
3840 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3841 (IV)(locinput - loc_bostr),
3844 (docolor ? "" : "> <"),
3846 (int)(tlen > 19 ? 0 : 19 - tlen),
3853 /* reg_check_named_buff_matched()
3854 * Checks to see if a named buffer has matched. The data array of
3855 * buffer numbers corresponding to the buffer is expected to reside
3856 * in the regexp->data->data array in the slot stored in the ARG() of
3857 * node involved. Note that this routine doesn't actually care about the
3858 * name, that information is not preserved from compilation to execution.
3859 * Returns the index of the leftmost defined buffer with the given name
3860 * or 0 if non of the buffers matched.
3863 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3866 RXi_GET_DECL(rex,rexi);
3867 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3868 I32 *nums=(I32*)SvPVX(sv_dat);
3870 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3872 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3873 if ((I32)rex->lastparen >= nums[n] &&
3874 rex->offs[nums[n]].end != -1)
3884 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3885 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3887 /* This function determines if there are one or two characters that match
3888 * the first character of the passed-in EXACTish node <text_node>, and if
3889 * so, returns them in the passed-in pointers.
3891 * If it determines that no possible character in the target string can
3892 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3893 * the first character in <text_node> requires UTF-8 to represent, and the
3894 * target string isn't in UTF-8.)
3896 * If there are more than two characters that could match the beginning of
3897 * <text_node>, or if more context is required to determine a match or not,
3898 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3900 * The motiviation behind this function is to allow the caller to set up
3901 * tight loops for matching. If <text_node> is of type EXACT, there is
3902 * only one possible character that can match its first character, and so
3903 * the situation is quite simple. But things get much more complicated if
3904 * folding is involved. It may be that the first character of an EXACTFish
3905 * node doesn't participate in any possible fold, e.g., punctuation, so it
3906 * can be matched only by itself. The vast majority of characters that are
3907 * in folds match just two things, their lower and upper-case equivalents.
3908 * But not all are like that; some have multiple possible matches, or match
3909 * sequences of more than one character. This function sorts all that out.
3911 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3912 * loop of trying to match A*, we know we can't exit where the thing
3913 * following it isn't a B. And something can't be a B unless it is the
3914 * beginning of B. By putting a quick test for that beginning in a tight
3915 * loop, we can rule out things that can't possibly be B without having to
3916 * break out of the loop, thus avoiding work. Similarly, if A is a single
3917 * character, we can make a tight loop matching A*, using the outputs of
3920 * If the target string to match isn't in UTF-8, and there aren't
3921 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3922 * the one or two possible octets (which are characters in this situation)
3923 * that can match. In all cases, if there is only one character that can
3924 * match, *<c1p> and *<c2p> will be identical.
3926 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3927 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3928 * can match the beginning of <text_node>. They should be declared with at
3929 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3930 * undefined what these contain.) If one or both of the buffers are
3931 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3932 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3933 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3934 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3935 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
3937 const bool utf8_target = reginfo->is_utf8_target;
3939 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
3940 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
3941 bool use_chrtest_void = FALSE;
3942 const bool is_utf8_pat = reginfo->is_utf8_pat;
3944 /* Used when we have both utf8 input and utf8 output, to avoid converting
3945 * to/from code points */
3946 bool utf8_has_been_setup = FALSE;
3950 U8 *pat = (U8*)STRING(text_node);
3951 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
3953 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
3955 /* In an exact node, only one thing can be matched, that first
3956 * character. If both the pat and the target are UTF-8, we can just
3957 * copy the input to the output, avoiding finding the code point of
3962 else if (utf8_target) {
3963 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3964 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3965 utf8_has_been_setup = TRUE;
3968 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
3971 else { /* an EXACTFish node */
3972 U8 *pat_end = pat + STR_LEN(text_node);
3974 /* An EXACTFL node has at least some characters unfolded, because what
3975 * they match is not known until now. So, now is the time to fold
3976 * the first few of them, as many as are needed to determine 'c1' and
3977 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3978 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3979 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3980 * need to fold as many characters as a single character can fold to,
3981 * so that later we can check if the first ones are such a multi-char
3982 * fold. But, in such a pattern only locale-problematic characters
3983 * aren't folded, so we can skip this completely if the first character
3984 * in the node isn't one of the tricky ones */
3985 if (OP(text_node) == EXACTFL) {
3987 if (! is_utf8_pat) {
3988 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3990 folded[0] = folded[1] = 's';
3992 pat_end = folded + 2;
3995 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4000 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4002 *(d++) = (U8) toFOLD_LC(*s);
4007 _to_utf8_fold_flags(s,
4010 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4021 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4022 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4024 /* Multi-character folds require more context to sort out. Also
4025 * PL_utf8_foldclosures used below doesn't handle them, so have to
4026 * be handled outside this routine */
4027 use_chrtest_void = TRUE;
4029 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4030 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4032 /* Load the folds hash, if not already done */
4034 if (! PL_utf8_foldclosures) {
4035 _load_PL_utf8_foldclosures();
4038 /* The fold closures data structure is a hash with the keys
4039 * being the UTF-8 of every character that is folded to, like
4040 * 'k', and the values each an array of all code points that
4041 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4042 * Multi-character folds are not included */
4043 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4048 /* Not found in the hash, therefore there are no folds
4049 * containing it, so there is only a single character that
4053 else { /* Does participate in folds */
4054 AV* list = (AV*) *listp;
4055 if (av_tindex(list) != 1) {
4057 /* If there aren't exactly two folds to this, it is
4058 * outside the scope of this function */
4059 use_chrtest_void = TRUE;
4061 else { /* There are two. Get them */
4062 SV** c_p = av_fetch(list, 0, FALSE);
4064 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4068 c_p = av_fetch(list, 1, FALSE);
4070 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4074 /* Folds that cross the 255/256 boundary are forbidden
4075 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4076 * one is ASCIII. Since the pattern character is above
4077 * 255, and its only other match is below 256, the only
4078 * legal match will be to itself. We have thrown away
4079 * the original, so have to compute which is the one
4081 if ((c1 < 256) != (c2 < 256)) {
4082 if ((OP(text_node) == EXACTFL
4083 && ! IN_UTF8_CTYPE_LOCALE)
4084 || ((OP(text_node) == EXACTFA
4085 || OP(text_node) == EXACTFA_NO_TRIE)
4086 && (isASCII(c1) || isASCII(c2))))
4099 else /* Here, c1 is <= 255 */
4101 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4102 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4103 && ((OP(text_node) != EXACTFA
4104 && OP(text_node) != EXACTFA_NO_TRIE)
4107 /* Here, there could be something above Latin1 in the target
4108 * which folds to this character in the pattern. All such
4109 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4110 * than two characters involved in their folds, so are outside
4111 * the scope of this function */
4112 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4113 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4116 use_chrtest_void = TRUE;
4119 else { /* Here nothing above Latin1 can fold to the pattern
4121 switch (OP(text_node)) {
4123 case EXACTFL: /* /l rules */
4124 c2 = PL_fold_locale[c1];
4127 case EXACTF: /* This node only generated for non-utf8
4129 assert(! is_utf8_pat);
4130 if (! utf8_target) { /* /d rules */
4135 /* /u rules for all these. This happens to work for
4136 * EXACTFA as nothing in Latin1 folds to ASCII */
4137 case EXACTFA_NO_TRIE: /* This node only generated for
4138 non-utf8 patterns */
4139 assert(! is_utf8_pat);
4144 c2 = PL_fold_latin1[c1];
4148 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4149 NOT_REACHED; /* NOTREACHED */
4155 /* Here have figured things out. Set up the returns */
4156 if (use_chrtest_void) {
4157 *c2p = *c1p = CHRTEST_VOID;
4159 else if (utf8_target) {
4160 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4161 uvchr_to_utf8(c1_utf8, c1);
4162 uvchr_to_utf8(c2_utf8, c2);
4165 /* Invariants are stored in both the utf8 and byte outputs; Use
4166 * negative numbers otherwise for the byte ones. Make sure that the
4167 * byte ones are the same iff the utf8 ones are the same */
4168 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4169 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4172 ? CHRTEST_NOT_A_CP_1
4173 : CHRTEST_NOT_A_CP_2;
4175 else if (c1 > 255) {
4176 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4181 *c1p = *c2p = c2; /* c2 is the only representable value */
4183 else { /* c1 is representable; see about c2 */
4185 *c2p = (c2 < 256) ? c2 : c1;
4191 /* This creates a single number by combining two, with 'before' being like the
4192 * 10's digit, but this isn't necessarily base 10; it is base however many
4193 * elements of the enum there are */
4194 #define GCBcase(before, after) ((GCB_ENUM_COUNT * before) + after)
4197 S_isGCB(const GCB_enum before, const GCB_enum after)
4199 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4200 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4202 switch (GCBcase(before, after)) {
4204 /* Break at the start and end of text.
4208 Break before and after controls except between CR and LF
4209 GB4. ( Control | CR | LF ) ÷
4210 GB5. ÷ ( Control | CR | LF )
4212 Otherwise, break everywhere.
4217 /* Do not break between a CR and LF.
4219 case GCBcase(GCB_CR, GCB_LF):
4222 /* Do not break Hangul syllable sequences.
4223 GB6. L × ( L | V | LV | LVT ) */
4224 case GCBcase(GCB_L, GCB_L):
4225 case GCBcase(GCB_L, GCB_V):
4226 case GCBcase(GCB_L, GCB_LV):
4227 case GCBcase(GCB_L, GCB_LVT):
4230 /* GB7. ( LV | V ) × ( V | T ) */
4231 case GCBcase(GCB_LV, GCB_V):
4232 case GCBcase(GCB_LV, GCB_T):
4233 case GCBcase(GCB_V, GCB_V):
4234 case GCBcase(GCB_V, GCB_T):
4237 /* GB8. ( LVT | T) × T */
4238 case GCBcase(GCB_LVT, GCB_T):
4239 case GCBcase(GCB_T, GCB_T):
4242 /* Do not break between regional indicator symbols.
4243 GB8a. Regional_Indicator × Regional_Indicator */
4244 case GCBcase(GCB_Regional_Indicator, GCB_Regional_Indicator):
4247 /* Do not break before extending characters.
4249 case GCBcase(GCB_Other, GCB_Extend):
4250 case GCBcase(GCB_Extend, GCB_Extend):
4251 case GCBcase(GCB_L, GCB_Extend):
4252 case GCBcase(GCB_LV, GCB_Extend):
4253 case GCBcase(GCB_LVT, GCB_Extend):
4254 case GCBcase(GCB_Prepend, GCB_Extend):
4255 case GCBcase(GCB_Regional_Indicator, GCB_Extend):
4256 case GCBcase(GCB_SpacingMark, GCB_Extend):
4257 case GCBcase(GCB_T, GCB_Extend):
4258 case GCBcase(GCB_V, GCB_Extend):
4261 /* Do not break before SpacingMarks, or after Prepend characters.
4262 GB9a. × SpacingMark */
4263 case GCBcase(GCB_Other, GCB_SpacingMark):
4264 case GCBcase(GCB_Extend, GCB_SpacingMark):
4265 case GCBcase(GCB_L, GCB_SpacingMark):
4266 case GCBcase(GCB_LV, GCB_SpacingMark):
4267 case GCBcase(GCB_LVT, GCB_SpacingMark):
4268 case GCBcase(GCB_Prepend, GCB_SpacingMark):
4269 case GCBcase(GCB_Regional_Indicator, GCB_SpacingMark):
4270 case GCBcase(GCB_SpacingMark, GCB_SpacingMark):
4271 case GCBcase(GCB_T, GCB_SpacingMark):
4272 case GCBcase(GCB_V, GCB_SpacingMark):
4275 /* GB9b. Prepend × */
4276 case GCBcase(GCB_Prepend, GCB_Other):
4277 case GCBcase(GCB_Prepend, GCB_L):
4278 case GCBcase(GCB_Prepend, GCB_LV):
4279 case GCBcase(GCB_Prepend, GCB_LVT):
4280 case GCBcase(GCB_Prepend, GCB_Prepend):
4281 case GCBcase(GCB_Prepend, GCB_Regional_Indicator):
4282 case GCBcase(GCB_Prepend, GCB_T):
4283 case GCBcase(GCB_Prepend, GCB_V):
4287 NOT_REACHED; /* NOTREACHED */
4290 #define SBcase(before, after) ((SB_ENUM_COUNT * before) + after)
4293 S_isSB(pTHX_ SB_enum before,
4295 const U8 * const strbeg,
4296 const U8 * const curpos,
4297 const U8 * const strend,
4298 const bool utf8_target)
4300 /* returns a boolean indicating if there is a Sentence Boundary Break
4301 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4303 U8 * lpos = (U8 *) curpos;
4307 PERL_ARGS_ASSERT_ISSB;
4309 /* Break at the start and end of text.
4312 if (before == SB_EDGE || after == SB_EDGE) {
4316 /* SB 3: Do not break within CRLF. */
4317 if (before == SB_CR && after == SB_LF) {
4321 /* Break after paragraph separators. (though why CR and LF are considered
4322 * so is beyond me (khw)
4323 SB4. Sep | CR | LF ÷ */
4324 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4328 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4329 * (See Section 6.2, Replacing Ignore Rules.)
4330 SB5. X (Extend | Format)* → X */
4331 if (after == SB_Extend || after == SB_Format) {
4335 if (before == SB_Extend || before == SB_Format) {
4336 before = backup_one_SB(strbeg, &lpos, utf8_target);
4339 /* Do not break after ambiguous terminators like period, if they are
4340 * immediately followed by a number or lowercase letter, if they are
4341 * between uppercase letters, if the first following letter (optionally
4342 * after certain punctuation) is lowercase, or if they are followed by
4343 * "continuation" punctuation such as comma, colon, or semicolon. For
4344 * example, a period may be an abbreviation or numeric period, and thus may
4345 * not mark the end of a sentence.
4347 * SB6. ATerm × Numeric */
4348 if (before == SB_ATerm && after == SB_Numeric) {
4352 /* SB7. Upper ATerm × Upper */
4353 if (before == SB_ATerm && after == SB_Upper) {
4355 if (SB_Upper == backup_one_SB(strbeg, &temp_pos, utf8_target)) {
4360 /* SB8a. (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4361 * SB10. (STerm | ATerm) Close* Sp* × ( Sp | Sep | CR | LF ) */
4364 while (backup == SB_Sp) {
4365 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4367 while (backup == SB_Close) {
4368 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4370 if ((backup == SB_STerm || backup == SB_ATerm)
4371 && ( after == SB_SContinue
4372 || after == SB_STerm
4373 || after == SB_ATerm
4382 /* SB8. ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR | LF |
4383 * STerm | ATerm) )* Lower */
4384 if (backup == SB_ATerm) {
4385 U8 * rpos = (U8 *) curpos;
4386 SB_enum later = after;
4388 while ( later != SB_OLetter
4389 && later != SB_Upper
4390 && later != SB_Lower
4394 && later != SB_STerm
4395 && later != SB_ATerm
4396 && later != SB_EDGE)
4398 later = advance_one_SB(&rpos, strend, utf8_target);
4400 if (later == SB_Lower) {
4405 /* Break after sentence terminators, but include closing punctuation,
4406 * trailing spaces, and a paragraph separator (if present). [See note
4408 * SB9. ( STerm | ATerm ) Close* × ( Close | Sp | Sep | CR | LF ) */
4411 while (backup == SB_Close) {
4412 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4414 if ((backup == SB_STerm || backup == SB_ATerm)
4415 && ( after == SB_Close
4425 /* SB11. ( STerm | ATerm ) Close* Sp* ( Sep | CR | LF )? ÷ */
4427 backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4428 if ( backup == SB_Sep
4437 while (backup == SB_Sp) {
4438 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4440 while (backup == SB_Close) {
4441 backup = backup_one_SB(strbeg, &lpos, utf8_target);
4443 if (backup == SB_STerm || backup == SB_ATerm) {
4447 /* Otherwise, do not break.
4454 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4458 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4460 if (*curpos >= strend) {
4466 *curpos += UTF8SKIP(*curpos);
4467 if (*curpos >= strend) {
4470 sb = getSB_VAL_UTF8(*curpos, strend);
4471 } while (sb == SB_Extend || sb == SB_Format);
4476 if (*curpos >= strend) {
4479 sb = getSB_VAL_CP(**curpos);
4480 } while (sb == SB_Extend || sb == SB_Format);
4487 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4491 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4493 if (*curpos < strbeg) {
4498 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4499 if (! prev_char_pos) {
4503 /* Back up over Extend and Format. curpos is always just to the right
4504 * of the characater whose value we are getting */
4506 U8 * prev_prev_char_pos;
4507 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4510 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4511 *curpos = prev_char_pos;
4512 prev_char_pos = prev_prev_char_pos;
4515 *curpos = (U8 *) strbeg;
4518 } while (sb == SB_Extend || sb == SB_Format);
4522 if (*curpos - 2 < strbeg) {
4523 *curpos = (U8 *) strbeg;
4527 sb = getSB_VAL_CP(*(*curpos - 1));
4528 } while (sb == SB_Extend || sb == SB_Format);
4534 #define WBcase(before, after) ((WB_ENUM_COUNT * before) + after)
4537 S_isWB(pTHX_ WB_enum previous,
4540 const U8 * const strbeg,
4541 const U8 * const curpos,
4542 const U8 * const strend,
4543 const bool utf8_target)
4545 /* Return a boolean as to if the boundary between 'before' and 'after' is
4546 * a Unicode word break, using their published algorithm. Context may be
4547 * needed to make this determination. If the value for the character
4548 * before 'before' is known, it is passed as 'previous'; otherwise that
4549 * should be set to WB_UNKNOWN. The other input parameters give the
4550 * boundaries and current position in the matching of the string. That
4551 * is, 'curpos' marks the position where the character whose wb value is
4552 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
4554 U8 * before_pos = (U8 *) curpos;
4555 U8 * after_pos = (U8 *) curpos;
4557 PERL_ARGS_ASSERT_ISWB;
4559 /* WB1 and WB2: Break at the start and end of text. */
4560 if (before == WB_EDGE || after == WB_EDGE) {
4564 /* WB 3: Do not break within CRLF. */
4565 if (before == WB_CR && after == WB_LF) {
4569 /* WB 3a and WB 3b: Otherwise break before and after Newlines (including CR
4571 if ( before == WB_CR || before == WB_LF || before == WB_Newline
4572 || after == WB_CR || after == WB_LF || after == WB_Newline)
4577 /* Ignore Format and Extend characters, except when they appear at the
4578 * beginning of a region of text.
4579 * WB4. X (Extend | Format)* → X. */
4581 if (after == WB_Extend || after == WB_Format) {
4585 if (before == WB_Extend || before == WB_Format) {
4586 before = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4589 switch (WBcase(before, after)) {
4590 /* Otherwise, break everywhere (including around ideographs).
4595 /* Do not break between most letters.
4596 WB5. (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) */
4597 case WBcase(WB_ALetter, WB_ALetter):
4598 case WBcase(WB_ALetter, WB_Hebrew_Letter):
4599 case WBcase(WB_Hebrew_Letter, WB_ALetter):
4600 case WBcase(WB_Hebrew_Letter, WB_Hebrew_Letter):
4603 /* Do not break letters across certain punctuation.
4604 WB6. (ALetter | Hebrew_Letter)
4605 × (MidLetter | MidNumLet | Single_Quote) (ALetter
4607 case WBcase(WB_ALetter, WB_MidLetter):
4608 case WBcase(WB_ALetter, WB_MidNumLet):
4609 case WBcase(WB_ALetter, WB_Single_Quote):
4610 case WBcase(WB_Hebrew_Letter, WB_MidLetter):
4611 case WBcase(WB_Hebrew_Letter, WB_MidNumLet):
4612 /*case WBcase(WB_Hebrew_Letter, WB_Single_Quote):*/
4613 after = advance_one_WB(&after_pos, strend, utf8_target);
4614 return after != WB_ALetter && after != WB_Hebrew_Letter;
4616 /* WB7. (ALetter | Hebrew_Letter) (MidLetter | MidNumLet |
4617 * Single_Quote) × (ALetter | Hebrew_Letter) */
4618 case WBcase(WB_MidLetter, WB_ALetter):
4619 case WBcase(WB_MidLetter, WB_Hebrew_Letter):
4620 case WBcase(WB_MidNumLet, WB_ALetter):
4621 case WBcase(WB_MidNumLet, WB_Hebrew_Letter):
4622 case WBcase(WB_Single_Quote, WB_ALetter):
4623 case WBcase(WB_Single_Quote, WB_Hebrew_Letter):
4625 = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4626 return before != WB_ALetter && before != WB_Hebrew_Letter;
4628 /* WB7a. Hebrew_Letter × Single_Quote */
4629 case WBcase(WB_Hebrew_Letter, WB_Single_Quote):
4632 /* WB7b. Hebrew_Letter × Double_Quote Hebrew_Letter */
4633 case WBcase(WB_Hebrew_Letter, WB_Double_Quote):
4634 return advance_one_WB(&after_pos, strend, utf8_target)
4635 != WB_Hebrew_Letter;
4637 /* WB7c. Hebrew_Letter Double_Quote × Hebrew_Letter */
4638 case WBcase(WB_Double_Quote, WB_Hebrew_Letter):
4639 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4640 != WB_Hebrew_Letter;
4642 /* Do not break within sequences of digits, or digits adjacent to
4643 * letters (“3a”, or “A3”).
4644 WB8. Numeric × Numeric */
4645 case WBcase(WB_Numeric, WB_Numeric):
4648 /* WB9. (ALetter | Hebrew_Letter) × Numeric */
4649 case WBcase(WB_ALetter, WB_Numeric):
4650 case WBcase(WB_Hebrew_Letter, WB_Numeric):
4653 /* WB10. Numeric × (ALetter | Hebrew_Letter) */
4654 case WBcase(WB_Numeric, WB_ALetter):
4655 case WBcase(WB_Numeric, WB_Hebrew_Letter):
4658 /* Do not break within sequences, such as “3.2” or “3,456.789”.
4659 WB11. Numeric (MidNum | MidNumLet | Single_Quote) × Numeric
4661 case WBcase(WB_MidNum, WB_Numeric):
4662 case WBcase(WB_MidNumLet, WB_Numeric):
4663 case WBcase(WB_Single_Quote, WB_Numeric):
4664 return backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4667 /* WB12. Numeric × (MidNum | MidNumLet | Single_Quote) Numeric
4669 case WBcase(WB_Numeric, WB_MidNum):
4670 case WBcase(WB_Numeric, WB_MidNumLet):
4671 case WBcase(WB_Numeric, WB_Single_Quote):
4672 return advance_one_WB(&after_pos, strend, utf8_target)
4675 /* Do not break between Katakana.
4676 WB13. Katakana × Katakana */
4677 case WBcase(WB_Katakana, WB_Katakana):
4680 /* Do not break from extenders.
4681 WB13a. (ALetter | Hebrew_Letter | Numeric | Katakana |
4682 ExtendNumLet) × ExtendNumLet */
4683 case WBcase(WB_ALetter, WB_ExtendNumLet):
4684 case WBcase(WB_Hebrew_Letter, WB_ExtendNumLet):
4685 case WBcase(WB_Numeric, WB_ExtendNumLet):
4686 case WBcase(WB_Katakana, WB_ExtendNumLet):
4687 case WBcase(WB_ExtendNumLet, WB_ExtendNumLet):
4690 /* WB13b. ExtendNumLet × (ALetter | Hebrew_Letter | Numeric
4692 case WBcase(WB_ExtendNumLet, WB_ALetter):
4693 case WBcase(WB_ExtendNumLet, WB_Hebrew_Letter):
4694 case WBcase(WB_ExtendNumLet, WB_Numeric):
4695 case WBcase(WB_ExtendNumLet, WB_Katakana):
4698 /* Do not break between regional indicator symbols.
4699 WB13c. Regional_Indicator × Regional_Indicator */
4700 case WBcase(WB_Regional_Indicator, WB_Regional_Indicator):
4705 NOT_REACHED; /* NOTREACHED */
4709 S_advance_one_WB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4713 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
4715 if (*curpos >= strend) {
4721 /* Advance over Extend and Format */
4723 *curpos += UTF8SKIP(*curpos);
4724 if (*curpos >= strend) {
4727 wb = getWB_VAL_UTF8(*curpos, strend);
4728 } while (wb == WB_Extend || wb == WB_Format);
4733 if (*curpos >= strend) {
4736 wb = getWB_VAL_CP(**curpos);
4737 } while (wb == WB_Extend || wb == WB_Format);
4744 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4748 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
4750 /* If we know what the previous character's break value is, don't have
4752 if (*previous != WB_UNKNOWN) {
4754 *previous = WB_UNKNOWN;
4755 /* XXX Note that doesn't change curpos, and maybe should */
4757 /* But we always back up over these two types */
4758 if (wb != WB_Extend && wb != WB_Format) {
4763 if (*curpos < strbeg) {
4768 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4769 if (! prev_char_pos) {
4773 /* Back up over Extend and Format. curpos is always just to the right
4774 * of the characater whose value we are getting */
4776 U8 * prev_prev_char_pos;
4777 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
4781 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4782 *curpos = prev_char_pos;
4783 prev_char_pos = prev_prev_char_pos;
4786 *curpos = (U8 *) strbeg;
4789 } while (wb == WB_Extend || wb == WB_Format);
4793 if (*curpos - 2 < strbeg) {
4794 *curpos = (U8 *) strbeg;
4798 wb = getWB_VAL_CP(*(*curpos - 1));
4799 } while (wb == WB_Extend || wb == WB_Format);
4805 /* returns -1 on failure, $+[0] on success */
4807 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
4809 #if PERL_VERSION < 9 && !defined(PERL_CORE)
4813 const bool utf8_target = reginfo->is_utf8_target;
4814 const U32 uniflags = UTF8_ALLOW_DEFAULT;
4815 REGEXP *rex_sv = reginfo->prog;
4816 regexp *rex = ReANY(rex_sv);
4817 RXi_GET_DECL(rex,rexi);
4818 /* the current state. This is a cached copy of PL_regmatch_state */
4820 /* cache heavy used fields of st in registers */
4823 U32 n = 0; /* general value; init to avoid compiler warning */
4824 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
4825 char *locinput = startpos;
4826 char *pushinput; /* where to continue after a PUSH */
4827 I32 nextchr; /* is always set to UCHARAT(locinput) */
4829 bool result = 0; /* return value of S_regmatch */
4830 int depth = 0; /* depth of backtrack stack */
4831 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
4832 const U32 max_nochange_depth =
4833 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
4834 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
4835 regmatch_state *yes_state = NULL; /* state to pop to on success of
4837 /* mark_state piggy backs on the yes_state logic so that when we unwind
4838 the stack on success we can update the mark_state as we go */
4839 regmatch_state *mark_state = NULL; /* last mark state we have seen */
4840 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
4841 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
4843 bool no_final = 0; /* prevent failure from backtracking? */
4844 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
4845 char *startpoint = locinput;
4846 SV *popmark = NULL; /* are we looking for a mark? */
4847 SV *sv_commit = NULL; /* last mark name seen in failure */
4848 SV *sv_yes_mark = NULL; /* last mark name we have seen
4849 during a successful match */
4850 U32 lastopen = 0; /* last open we saw */
4851 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
4852 SV* const oreplsv = GvSVn(PL_replgv);
4853 /* these three flags are set by various ops to signal information to
4854 * the very next op. They have a useful lifetime of exactly one loop
4855 * iteration, and are not preserved or restored by state pushes/pops
4857 bool sw = 0; /* the condition value in (?(cond)a|b) */
4858 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
4859 int logical = 0; /* the following EVAL is:
4863 or the following IFMATCH/UNLESSM is:
4864 false: plain (?=foo)
4865 true: used as a condition: (?(?=foo))
4867 PAD* last_pad = NULL;
4869 I32 gimme = G_SCALAR;
4870 CV *caller_cv = NULL; /* who called us */
4871 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
4872 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
4873 U32 maxopenparen = 0; /* max '(' index seen so far */
4874 int to_complement; /* Invert the result? */
4875 _char_class_number classnum;
4876 bool is_utf8_pat = reginfo->is_utf8_pat;
4881 GET_RE_DEBUG_FLAGS_DECL;
4884 /* protect against undef(*^R) */
4885 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
4887 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
4888 multicall_oldcatch = 0;
4889 multicall_cv = NULL;
4891 PERL_UNUSED_VAR(multicall_cop);
4892 PERL_UNUSED_VAR(newsp);
4895 PERL_ARGS_ASSERT_REGMATCH;
4897 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
4898 PerlIO_printf(Perl_debug_log,"regmatch start\n");
4901 st = PL_regmatch_state;
4903 /* Note that nextchr is a byte even in UTF */
4906 while (scan != NULL) {
4909 SV * const prop = sv_newmortal();
4910 regnode *rnext=regnext(scan);
4911 DUMP_EXEC_POS( locinput, scan, utf8_target );
4912 regprop(rex, prop, scan, reginfo, NULL);
4914 PerlIO_printf(Perl_debug_log,
4915 "%3"IVdf":%*s%s(%"IVdf")\n",
4916 (IV)(scan - rexi->program), depth*2, "",
4918 (PL_regkind[OP(scan)] == END || !rnext) ?
4919 0 : (IV)(rnext - rexi->program));
4922 next = scan + NEXT_OFF(scan);
4925 state_num = OP(scan);
4927 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
4932 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
4934 switch (state_num) {
4935 case SBOL: /* /^../ and /\A../ */
4936 if (locinput == reginfo->strbeg)
4940 case MBOL: /* /^../m */
4941 if (locinput == reginfo->strbeg ||
4942 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
4949 if (locinput == reginfo->ganch)
4953 case KEEPS: /* \K */
4954 /* update the startpoint */
4955 st->u.keeper.val = rex->offs[0].start;
4956 rex->offs[0].start = locinput - reginfo->strbeg;
4957 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
4959 NOT_REACHED; /* NOTREACHED */
4961 case KEEPS_next_fail:
4962 /* rollback the start point change */
4963 rex->offs[0].start = st->u.keeper.val;
4966 NOT_REACHED; /* NOTREACHED */
4968 case MEOL: /* /..$/m */
4969 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4973 case SEOL: /* /..$/ */
4974 if (!NEXTCHR_IS_EOS && nextchr != '\n')
4976 if (reginfo->strend - locinput > 1)
4981 if (!NEXTCHR_IS_EOS)
4985 case SANY: /* /./s */
4988 goto increment_locinput;
4996 case REG_ANY: /* /./ */
4997 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
4999 goto increment_locinput;
5003 #define ST st->u.trie
5004 case TRIEC: /* (ab|cd) with known charclass */
5005 /* In this case the charclass data is available inline so
5006 we can fail fast without a lot of extra overhead.
5008 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5010 PerlIO_printf(Perl_debug_log,
5011 "%*s %sfailed to match trie start class...%s\n",
5012 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5016 NOT_REACHED; /* NOTREACHED */
5019 case TRIE: /* (ab|cd) */
5020 /* the basic plan of execution of the trie is:
5021 * At the beginning, run though all the states, and
5022 * find the longest-matching word. Also remember the position
5023 * of the shortest matching word. For example, this pattern:
5026 * when matched against the string "abcde", will generate
5027 * accept states for all words except 3, with the longest
5028 * matching word being 4, and the shortest being 2 (with
5029 * the position being after char 1 of the string).
5031 * Then for each matching word, in word order (i.e. 1,2,4,5),
5032 * we run the remainder of the pattern; on each try setting
5033 * the current position to the character following the word,
5034 * returning to try the next word on failure.
5036 * We avoid having to build a list of words at runtime by
5037 * using a compile-time structure, wordinfo[].prev, which
5038 * gives, for each word, the previous accepting word (if any).
5039 * In the case above it would contain the mappings 1->2, 2->0,
5040 * 3->0, 4->5, 5->1. We can use this table to generate, from
5041 * the longest word (4 above), a list of all words, by
5042 * following the list of prev pointers; this gives us the
5043 * unordered list 4,5,1,2. Then given the current word we have
5044 * just tried, we can go through the list and find the
5045 * next-biggest word to try (so if we just failed on word 2,
5046 * the next in the list is 4).
5048 * Since at runtime we don't record the matching position in
5049 * the string for each word, we have to work that out for
5050 * each word we're about to process. The wordinfo table holds
5051 * the character length of each word; given that we recorded
5052 * at the start: the position of the shortest word and its
5053 * length in chars, we just need to move the pointer the
5054 * difference between the two char lengths. Depending on
5055 * Unicode status and folding, that's cheap or expensive.
5057 * This algorithm is optimised for the case where are only a
5058 * small number of accept states, i.e. 0,1, or maybe 2.
5059 * With lots of accepts states, and having to try all of them,
5060 * it becomes quadratic on number of accept states to find all
5065 /* what type of TRIE am I? (utf8 makes this contextual) */
5066 DECL_TRIE_TYPE(scan);
5068 /* what trie are we using right now */
5069 reg_trie_data * const trie
5070 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5071 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5072 U32 state = trie->startstate;
5074 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5075 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5077 && UTF8_IS_ABOVE_LATIN1(nextchr)
5078 && scan->flags == EXACTL)
5080 /* We only output for EXACTL, as we let the folder
5081 * output this message for EXACTFLU8 to avoid
5083 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5088 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5090 if (trie->states[ state ].wordnum) {
5092 PerlIO_printf(Perl_debug_log,
5093 "%*s %smatched empty string...%s\n",
5094 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5100 PerlIO_printf(Perl_debug_log,
5101 "%*s %sfailed to match trie start class...%s\n",
5102 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5109 U8 *uc = ( U8* )locinput;
5113 U8 *uscan = (U8*)NULL;
5114 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5115 U32 charcount = 0; /* how many input chars we have matched */
5116 U32 accepted = 0; /* have we seen any accepting states? */
5118 ST.jump = trie->jump;
5121 ST.longfold = FALSE; /* char longer if folded => it's harder */
5124 /* fully traverse the TRIE; note the position of the
5125 shortest accept state and the wordnum of the longest
5128 while ( state && uc <= (U8*)(reginfo->strend) ) {
5129 U32 base = trie->states[ state ].trans.base;
5133 wordnum = trie->states[ state ].wordnum;
5135 if (wordnum) { /* it's an accept state */
5138 /* record first match position */
5140 ST.firstpos = (U8*)locinput;
5145 ST.firstchars = charcount;
5148 if (!ST.nextword || wordnum < ST.nextword)
5149 ST.nextword = wordnum;
5150 ST.topword = wordnum;
5153 DEBUG_TRIE_EXECUTE_r({
5154 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5155 PerlIO_printf( Perl_debug_log,
5156 "%*s %sState: %4"UVxf" Accepted: %c ",
5157 2+depth * 2, "", PL_colors[4],
5158 (UV)state, (accepted ? 'Y' : 'N'));
5161 /* read a char and goto next state */
5162 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5164 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5165 uscan, len, uvc, charid, foldlen,
5172 base + charid - 1 - trie->uniquecharcount)) >= 0)
5174 && ((U32)offset < trie->lasttrans)
5175 && trie->trans[offset].check == state)
5177 state = trie->trans[offset].next;
5188 DEBUG_TRIE_EXECUTE_r(
5189 PerlIO_printf( Perl_debug_log,
5190 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5191 charid, uvc, (UV)state, PL_colors[5] );
5197 /* calculate total number of accept states */
5202 w = trie->wordinfo[w].prev;
5205 ST.accepted = accepted;
5209 PerlIO_printf( Perl_debug_log,
5210 "%*s %sgot %"IVdf" possible matches%s\n",
5211 REPORT_CODE_OFF + depth * 2, "",
5212 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5214 goto trie_first_try; /* jump into the fail handler */
5217 NOT_REACHED; /* NOTREACHED */
5219 case TRIE_next_fail: /* we failed - try next alternative */
5223 REGCP_UNWIND(ST.cp);
5224 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5226 if (!--ST.accepted) {
5228 PerlIO_printf( Perl_debug_log,
5229 "%*s %sTRIE failed...%s\n",
5230 REPORT_CODE_OFF+depth*2, "",
5237 /* Find next-highest word to process. Note that this code
5238 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5241 U16 const nextword = ST.nextword;
5242 reg_trie_wordinfo * const wordinfo
5243 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5244 for (word=ST.topword; word; word=wordinfo[word].prev) {
5245 if (word > nextword && (!min || word < min))
5258 ST.lastparen = rex->lastparen;
5259 ST.lastcloseparen = rex->lastcloseparen;
5263 /* find start char of end of current word */
5265 U32 chars; /* how many chars to skip */
5266 reg_trie_data * const trie
5267 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5269 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5271 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5276 /* the hard option - fold each char in turn and find
5277 * its folded length (which may be different */
5278 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5286 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5294 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5299 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5315 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5316 ? ST.jump[ST.nextword]
5320 PerlIO_printf( Perl_debug_log,
5321 "%*s %sTRIE matched word #%d, continuing%s\n",
5322 REPORT_CODE_OFF+depth*2, "",
5329 if (ST.accepted > 1 || has_cutgroup) {
5330 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5332 NOT_REACHED; /* NOTREACHED */
5334 /* only one choice left - just continue */
5336 AV *const trie_words
5337 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5338 SV ** const tmp = trie_words
5339 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5340 SV *sv= tmp ? sv_newmortal() : NULL;
5342 PerlIO_printf( Perl_debug_log,
5343 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
5344 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5346 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5347 PL_colors[0], PL_colors[1],
5348 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5350 : "not compiled under -Dr",
5354 locinput = (char*)uc;
5355 continue; /* execute rest of RE */
5360 case EXACTL: /* /abc/l */
5361 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5363 /* Complete checking would involve going through every character
5364 * matched by the string to see if any is above latin1. But the
5365 * comparision otherwise might very well be a fast assembly
5366 * language routine, and I (khw) don't think slowing things down
5367 * just to check for this warning is worth it. So this just checks
5368 * the first character */
5369 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5370 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5373 case EXACT: { /* /abc/ */
5374 char *s = STRING(scan);
5376 if (utf8_target != is_utf8_pat) {
5377 /* The target and the pattern have differing utf8ness. */
5379 const char * const e = s + ln;
5382 /* The target is utf8, the pattern is not utf8.
5383 * Above-Latin1 code points can't match the pattern;
5384 * invariants match exactly, and the other Latin1 ones need
5385 * to be downgraded to a single byte in order to do the
5386 * comparison. (If we could be confident that the target
5387 * is not malformed, this could be refactored to have fewer
5388 * tests by just assuming that if the first bytes match, it
5389 * is an invariant, but there are tests in the test suite
5390 * dealing with (??{...}) which violate this) */
5392 if (l >= reginfo->strend
5393 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5397 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5404 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5414 /* The target is not utf8, the pattern is utf8. */
5416 if (l >= reginfo->strend
5417 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5421 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5428 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5440 /* The target and the pattern have the same utf8ness. */
5441 /* Inline the first character, for speed. */
5442 if (reginfo->strend - locinput < ln
5443 || UCHARAT(s) != nextchr
5444 || (ln > 1 && memNE(s, locinput, ln)))
5453 case EXACTFL: { /* /abc/il */
5455 const U8 * fold_array;
5457 U32 fold_utf8_flags;
5459 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5460 folder = foldEQ_locale;
5461 fold_array = PL_fold_locale;
5462 fold_utf8_flags = FOLDEQ_LOCALE;
5465 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5466 is effectively /u; hence to match, target
5468 if (! utf8_target) {
5471 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5472 | FOLDEQ_S1_FOLDS_SANE;
5473 folder = foldEQ_latin1;
5474 fold_array = PL_fold_latin1;
5477 case EXACTFU_SS: /* /\x{df}/iu */
5478 case EXACTFU: /* /abc/iu */
5479 folder = foldEQ_latin1;
5480 fold_array = PL_fold_latin1;
5481 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5484 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5486 assert(! is_utf8_pat);
5488 case EXACTFA: /* /abc/iaa */
5489 folder = foldEQ_latin1;
5490 fold_array = PL_fold_latin1;
5491 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5494 case EXACTF: /* /abc/i This node only generated for
5495 non-utf8 patterns */
5496 assert(! is_utf8_pat);
5498 fold_array = PL_fold;
5499 fold_utf8_flags = 0;
5507 || state_num == EXACTFU_SS
5508 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5510 /* Either target or the pattern are utf8, or has the issue where
5511 * the fold lengths may differ. */
5512 const char * const l = locinput;
5513 char *e = reginfo->strend;
5515 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
5516 l, &e, 0, utf8_target, fold_utf8_flags))
5524 /* Neither the target nor the pattern are utf8 */
5525 if (UCHARAT(s) != nextchr
5527 && UCHARAT(s) != fold_array[nextchr])
5531 if (reginfo->strend - locinput < ln)
5533 if (ln > 1 && ! folder(s, locinput, ln))
5539 case NBOUNDL: /* /\B/l */
5543 case BOUNDL: /* /\b/l */
5544 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5546 if (FLAGS(scan) != TRADITIONAL_BOUND) {
5547 if (! IN_UTF8_CTYPE_LOCALE) {
5548 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5549 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5555 if (locinput == reginfo->strbeg)
5556 ln = isWORDCHAR_LC('\n');
5558 ln = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5559 (U8*)(reginfo->strbeg)));
5561 n = (NEXTCHR_IS_EOS)
5562 ? isWORDCHAR_LC('\n')
5563 : isWORDCHAR_LC_utf8((U8*)locinput);
5565 else { /* Here the string isn't utf8 */
5566 ln = (locinput == reginfo->strbeg)
5567 ? isWORDCHAR_LC('\n')
5568 : isWORDCHAR_LC(UCHARAT(locinput - 1));
5569 n = (NEXTCHR_IS_EOS)
5570 ? isWORDCHAR_LC('\n')
5571 : isWORDCHAR_LC(nextchr);
5573 if (to_complement ^ (ln == n)) {
5578 case NBOUND: /* /\B/ */
5582 case BOUND: /* /\b/ */
5586 goto bound_ascii_match_only;
5588 case NBOUNDA: /* /\B/a */
5592 case BOUNDA: /* /\b/a */
5594 bound_ascii_match_only:
5595 /* Here the string isn't utf8, or is utf8 and only ascii characters
5596 * are to match \w. In the latter case looking at the byte just
5597 * prior to the current one may be just the final byte of a
5598 * multi-byte character. This is ok. There are two cases:
5599 * 1) it is a single byte character, and then the test is doing
5600 * just what it's supposed to.
5601 * 2) it is a multi-byte character, in which case the final byte is
5602 * never mistakable for ASCII, and so the test will say it is
5603 * not a word character, which is the correct answer. */
5604 ln = (locinput == reginfo->strbeg)
5605 ? isWORDCHAR_A('\n')
5606 : isWORDCHAR_A(UCHARAT(locinput - 1));
5607 n = (NEXTCHR_IS_EOS)
5608 ? isWORDCHAR_A('\n')
5609 : isWORDCHAR_A(nextchr);
5610 if (to_complement ^ (ln == n)) {
5615 case NBOUNDU: /* /\B/u */
5619 case BOUNDU: /* /\b/u */
5625 switch((bound_type) FLAGS(scan)) {
5626 case TRADITIONAL_BOUND:
5627 ln = (locinput == reginfo->strbeg)
5628 ? 0 /* isWORDCHAR_L1('\n') */
5629 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5630 (U8*)(reginfo->strbeg)));
5631 n = (NEXTCHR_IS_EOS)
5632 ? 0 /* isWORDCHAR_L1('\n') */
5633 : isWORDCHAR_utf8((U8*)locinput);
5634 match = cBOOL(ln != n);
5637 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5638 match = TRUE; /* GCB always matches at begin and
5642 /* Find the gcb values of previous and current
5643 * chars, then see if is a break point */
5644 match = isGCB(getGCB_VAL_UTF8(
5645 reghop3((U8*)locinput,
5647 (U8*)(reginfo->strbeg)),
5648 (U8*) reginfo->strend),
5649 getGCB_VAL_UTF8((U8*) locinput,
5650 (U8*) reginfo->strend));
5654 case SB_BOUND: /* Always matches at begin and end */
5655 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5659 match = isSB(getSB_VAL_UTF8(
5660 reghop3((U8*)locinput,
5662 (U8*)(reginfo->strbeg)),
5663 (U8*) reginfo->strend),
5664 getSB_VAL_UTF8((U8*) locinput,
5665 (U8*) reginfo->strend),
5666 (U8*) reginfo->strbeg,
5668 (U8*) reginfo->strend,
5674 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5678 match = isWB(WB_UNKNOWN,
5680 reghop3((U8*)locinput,
5682 (U8*)(reginfo->strbeg)),
5683 (U8*) reginfo->strend),
5684 getWB_VAL_UTF8((U8*) locinput,
5685 (U8*) reginfo->strend),
5686 (U8*) reginfo->strbeg,
5688 (U8*) reginfo->strend,
5694 else { /* Not utf8 target */
5695 switch((bound_type) FLAGS(scan)) {
5696 case TRADITIONAL_BOUND:
5697 ln = (locinput == reginfo->strbeg)
5698 ? 0 /* isWORDCHAR_L1('\n') */
5699 : isWORDCHAR_L1(UCHARAT(locinput - 1));
5700 n = (NEXTCHR_IS_EOS)
5701 ? 0 /* isWORDCHAR_L1('\n') */
5702 : isWORDCHAR_L1(nextchr);
5703 match = cBOOL(ln != n);
5707 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5708 match = TRUE; /* GCB always matches at begin and
5711 else { /* Only CR-LF combo isn't a GCB in 0-255
5713 match = UCHARAT(locinput - 1) != '\r'
5714 || UCHARAT(locinput) != '\n';
5718 case SB_BOUND: /* Always matches at begin and end */
5719 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5723 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
5724 getSB_VAL_CP(UCHARAT(locinput)),
5725 (U8*) reginfo->strbeg,
5727 (U8*) reginfo->strend,
5733 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5737 match = isWB(WB_UNKNOWN,
5738 getWB_VAL_CP(UCHARAT(locinput -1)),
5739 getWB_VAL_CP(UCHARAT(locinput)),
5740 (U8*) reginfo->strbeg,
5742 (U8*) reginfo->strend,
5749 if (to_complement ^ ! match) {
5754 case ANYOFL: /* /[abc]/l */
5755 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5757 case ANYOF: /* /[abc]/ */
5761 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
5764 locinput += UTF8SKIP(locinput);
5767 if (!REGINCLASS(rex, scan, (U8*)locinput))
5773 /* The argument (FLAGS) to all the POSIX node types is the class number
5776 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
5780 case POSIXL: /* \w or [:punct:] etc. under /l */
5781 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5785 /* Use isFOO_lc() for characters within Latin1. (Note that
5786 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5787 * wouldn't be invariant) */
5788 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5789 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
5793 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5794 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
5795 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
5796 *(locinput + 1))))))
5801 else { /* Here, must be an above Latin-1 code point */
5802 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5803 goto utf8_posix_above_latin1;
5806 /* Here, must be utf8 */
5807 locinput += UTF8SKIP(locinput);
5810 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
5814 case POSIXD: /* \w or [:punct:] etc. under /d */
5820 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
5822 if (NEXTCHR_IS_EOS) {
5826 /* All UTF-8 variants match */
5827 if (! UTF8_IS_INVARIANT(nextchr)) {
5828 goto increment_locinput;
5834 case POSIXA: /* \w or [:punct:] etc. under /a */
5837 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
5838 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
5839 * character is a single byte */
5842 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
5848 /* Here we are either not in utf8, or we matched a utf8-invariant,
5849 * so the next char is the next byte */
5853 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
5857 case POSIXU: /* \w or [:punct:] etc. under /u */
5859 if (NEXTCHR_IS_EOS) {
5863 /* Use _generic_isCC() for characters within Latin1. (Note that
5864 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
5865 * wouldn't be invariant) */
5866 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
5867 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
5874 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
5875 if (! (to_complement
5876 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
5884 else { /* Handle above Latin-1 code points */
5885 utf8_posix_above_latin1:
5886 classnum = (_char_class_number) FLAGS(scan);
5887 if (classnum < _FIRST_NON_SWASH_CC) {
5889 /* Here, uses a swash to find such code points. Load if if
5890 * not done already */
5891 if (! PL_utf8_swash_ptrs[classnum]) {
5892 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
5893 PL_utf8_swash_ptrs[classnum]
5894 = _core_swash_init("utf8",
5897 PL_XPosix_ptrs[classnum], &flags);
5899 if (! (to_complement
5900 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
5901 (U8 *) locinput, TRUE))))
5906 else { /* Here, uses macros to find above Latin-1 code points */
5908 case _CC_ENUM_SPACE:
5909 if (! (to_complement
5910 ^ cBOOL(is_XPERLSPACE_high(locinput))))
5915 case _CC_ENUM_BLANK:
5916 if (! (to_complement
5917 ^ cBOOL(is_HORIZWS_high(locinput))))
5922 case _CC_ENUM_XDIGIT:
5923 if (! (to_complement
5924 ^ cBOOL(is_XDIGIT_high(locinput))))
5929 case _CC_ENUM_VERTSPACE:
5930 if (! (to_complement
5931 ^ cBOOL(is_VERTWS_high(locinput))))
5936 default: /* The rest, e.g. [:cntrl:], can't match
5938 if (! to_complement) {
5944 locinput += UTF8SKIP(locinput);
5948 case CLUMP: /* Match \X: logical Unicode character. This is defined as
5949 a Unicode extended Grapheme Cluster */
5952 if (! utf8_target) {
5954 /* Match either CR LF or '.', as all the other possibilities
5956 locinput++; /* Match the . or CR */
5957 if (nextchr == '\r' /* And if it was CR, and the next is LF,
5959 && locinput < reginfo->strend
5960 && UCHARAT(locinput) == '\n')
5967 /* Get the gcb type for the current character */
5968 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
5969 (U8*) reginfo->strend);
5971 /* Then scan through the input until we get to the first
5972 * character whose type is supposed to be a gcb with the
5973 * current character. (There is always a break at the
5975 locinput += UTF8SKIP(locinput);
5976 while (locinput < reginfo->strend) {
5977 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
5978 (U8*) reginfo->strend);
5979 if (isGCB(prev_gcb, cur_gcb)) {
5984 locinput += UTF8SKIP(locinput);
5991 case NREFFL: /* /\g{name}/il */
5992 { /* The capture buffer cases. The ones beginning with N for the
5993 named buffers just convert to the equivalent numbered and
5994 pretend they were called as the corresponding numbered buffer
5996 /* don't initialize these in the declaration, it makes C++
6001 const U8 *fold_array;
6004 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6005 folder = foldEQ_locale;
6006 fold_array = PL_fold_locale;
6008 utf8_fold_flags = FOLDEQ_LOCALE;
6011 case NREFFA: /* /\g{name}/iaa */
6012 folder = foldEQ_latin1;
6013 fold_array = PL_fold_latin1;
6015 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6018 case NREFFU: /* /\g{name}/iu */
6019 folder = foldEQ_latin1;
6020 fold_array = PL_fold_latin1;
6022 utf8_fold_flags = 0;
6025 case NREFF: /* /\g{name}/i */
6027 fold_array = PL_fold;
6029 utf8_fold_flags = 0;
6032 case NREF: /* /\g{name}/ */
6036 utf8_fold_flags = 0;
6039 /* For the named back references, find the corresponding buffer
6041 n = reg_check_named_buff_matched(rex,scan);
6046 goto do_nref_ref_common;
6048 case REFFL: /* /\1/il */
6049 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6050 folder = foldEQ_locale;
6051 fold_array = PL_fold_locale;
6052 utf8_fold_flags = FOLDEQ_LOCALE;
6055 case REFFA: /* /\1/iaa */
6056 folder = foldEQ_latin1;
6057 fold_array = PL_fold_latin1;
6058 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6061 case REFFU: /* /\1/iu */
6062 folder = foldEQ_latin1;
6063 fold_array = PL_fold_latin1;
6064 utf8_fold_flags = 0;
6067 case REFF: /* /\1/i */
6069 fold_array = PL_fold;
6070 utf8_fold_flags = 0;
6073 case REF: /* /\1/ */
6076 utf8_fold_flags = 0;
6080 n = ARG(scan); /* which paren pair */
6083 ln = rex->offs[n].start;
6084 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6085 if (rex->lastparen < n || ln == -1)
6086 sayNO; /* Do not match unless seen CLOSEn. */
6087 if (ln == rex->offs[n].end)
6090 s = reginfo->strbeg + ln;
6091 if (type != REF /* REF can do byte comparison */
6092 && (utf8_target || type == REFFU || type == REFFL))
6094 char * limit = reginfo->strend;
6096 /* This call case insensitively compares the entire buffer
6097 * at s, with the current input starting at locinput, but
6098 * not going off the end given by reginfo->strend, and
6099 * returns in <limit> upon success, how much of the
6100 * current input was matched */
6101 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6102 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6110 /* Not utf8: Inline the first character, for speed. */
6111 if (!NEXTCHR_IS_EOS &&
6112 UCHARAT(s) != nextchr &&
6114 UCHARAT(s) != fold_array[nextchr]))
6116 ln = rex->offs[n].end - ln;
6117 if (locinput + ln > reginfo->strend)
6119 if (ln > 1 && (type == REF
6120 ? memNE(s, locinput, ln)
6121 : ! folder(s, locinput, ln)))
6127 case NOTHING: /* null op; e.g. the 'nothing' following
6128 * the '*' in m{(a+|b)*}' */
6130 case TAIL: /* placeholder while compiling (A|B|C) */
6134 #define ST st->u.eval
6139 regexp_internal *rei;
6140 regnode *startpoint;
6142 case GOSTART: /* (?R) */
6143 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6144 if (cur_eval && cur_eval->locinput==locinput) {
6145 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
6146 Perl_croak(aTHX_ "Infinite recursion in regex");
6147 if ( ++nochange_depth > max_nochange_depth )
6149 "Pattern subroutine nesting without pos change"
6150 " exceeded limit in regex");
6157 if (OP(scan)==GOSUB) {
6158 startpoint = scan + ARG2L(scan);
6159 ST.close_paren = ARG(scan);
6161 startpoint = rei->program+1;
6165 /* Save all the positions seen so far. */
6166 ST.cp = regcppush(rex, 0, maxopenparen);
6167 REGCP_SET(ST.lastcp);
6169 /* and then jump to the code we share with EVAL */
6170 goto eval_recurse_doit;
6173 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6174 if (cur_eval && cur_eval->locinput==locinput) {
6175 if ( ++nochange_depth > max_nochange_depth )
6176 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6181 /* execute the code in the {...} */
6185 OP * const oop = PL_op;
6186 COP * const ocurcop = PL_curcop;
6190 /* save *all* paren positions */
6191 regcppush(rex, 0, maxopenparen);
6192 REGCP_SET(runops_cp);
6195 caller_cv = find_runcv(NULL);
6199 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6201 (REGEXP*)(rexi->data->data[n])
6204 nop = (OP*)rexi->data->data[n+1];
6206 else if (rexi->data->what[n] == 'l') { /* literal code */
6208 nop = (OP*)rexi->data->data[n];
6209 assert(CvDEPTH(newcv));
6212 /* literal with own CV */
6213 assert(rexi->data->what[n] == 'L');
6214 newcv = rex->qr_anoncv;
6215 nop = (OP*)rexi->data->data[n];
6218 /* normally if we're about to execute code from the same
6219 * CV that we used previously, we just use the existing
6220 * CX stack entry. However, its possible that in the
6221 * meantime we may have backtracked, popped from the save
6222 * stack, and undone the SAVECOMPPAD(s) associated with
6223 * PUSH_MULTICALL; in which case PL_comppad no longer
6224 * points to newcv's pad. */
6225 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6227 U8 flags = (CXp_SUB_RE |
6228 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6229 if (last_pushed_cv) {
6230 CHANGE_MULTICALL_FLAGS(newcv, flags);
6233 PUSH_MULTICALL_FLAGS(newcv, flags);
6235 last_pushed_cv = newcv;
6238 /* these assignments are just to silence compiler
6240 multicall_cop = NULL;
6243 last_pad = PL_comppad;
6245 /* the initial nextstate you would normally execute
6246 * at the start of an eval (which would cause error
6247 * messages to come from the eval), may be optimised
6248 * away from the execution path in the regex code blocks;
6249 * so manually set PL_curcop to it initially */
6251 OP *o = cUNOPx(nop)->op_first;
6252 assert(o->op_type == OP_NULL);
6253 if (o->op_targ == OP_SCOPE) {
6254 o = cUNOPo->op_first;
6257 assert(o->op_targ == OP_LEAVE);
6258 o = cUNOPo->op_first;
6259 assert(o->op_type == OP_ENTER);
6263 if (o->op_type != OP_STUB) {
6264 assert( o->op_type == OP_NEXTSTATE
6265 || o->op_type == OP_DBSTATE
6266 || (o->op_type == OP_NULL
6267 && ( o->op_targ == OP_NEXTSTATE
6268 || o->op_targ == OP_DBSTATE
6272 PL_curcop = (COP*)o;
6277 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
6278 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6280 rex->offs[0].end = locinput - reginfo->strbeg;
6281 if (reginfo->info_aux_eval->pos_magic)
6282 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6283 reginfo->sv, reginfo->strbeg,
6284 locinput - reginfo->strbeg);
6287 SV *sv_mrk = get_sv("REGMARK", 1);
6288 sv_setsv(sv_mrk, sv_yes_mark);
6291 /* we don't use MULTICALL here as we want to call the
6292 * first op of the block of interest, rather than the
6293 * first op of the sub */
6294 before = (IV)(SP-PL_stack_base);
6296 CALLRUNOPS(aTHX); /* Scalar context. */
6298 if ((IV)(SP-PL_stack_base) == before)
6299 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6305 /* before restoring everything, evaluate the returned
6306 * value, so that 'uninit' warnings don't use the wrong
6307 * PL_op or pad. Also need to process any magic vars
6308 * (e.g. $1) *before* parentheses are restored */
6313 if (logical == 0) /* (?{})/ */
6314 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6315 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6316 sw = cBOOL(SvTRUE(ret));
6319 else { /* /(??{}) */
6320 /* if its overloaded, let the regex compiler handle
6321 * it; otherwise extract regex, or stringify */
6322 if (SvGMAGICAL(ret))
6323 ret = sv_mortalcopy(ret);
6324 if (!SvAMAGIC(ret)) {
6328 if (SvTYPE(sv) == SVt_REGEXP)
6329 re_sv = (REGEXP*) sv;
6330 else if (SvSMAGICAL(ret)) {
6331 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6333 re_sv = (REGEXP *) mg->mg_obj;
6336 /* force any undef warnings here */
6337 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6338 ret = sv_mortalcopy(ret);
6339 (void) SvPV_force_nolen(ret);
6345 /* *** Note that at this point we don't restore
6346 * PL_comppad, (or pop the CxSUB) on the assumption it may
6347 * be used again soon. This is safe as long as nothing
6348 * in the regexp code uses the pad ! */
6350 PL_curcop = ocurcop;
6351 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6352 PL_curpm = PL_reg_curpm;
6358 /* only /(??{})/ from now on */
6361 /* extract RE object from returned value; compiling if
6365 re_sv = reg_temp_copy(NULL, re_sv);
6370 if (SvUTF8(ret) && IN_BYTES) {
6371 /* In use 'bytes': make a copy of the octet
6372 * sequence, but without the flag on */
6374 const char *const p = SvPV(ret, len);
6375 ret = newSVpvn_flags(p, len, SVs_TEMP);
6377 if (rex->intflags & PREGf_USE_RE_EVAL)
6378 pm_flags |= PMf_USE_RE_EVAL;
6380 /* if we got here, it should be an engine which
6381 * supports compiling code blocks and stuff */
6382 assert(rex->engine && rex->engine->op_comp);
6383 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6384 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6385 rex->engine, NULL, NULL,
6386 /* copy /msixn etc to inner pattern */
6391 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6392 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6393 /* This isn't a first class regexp. Instead, it's
6394 caching a regexp onto an existing, Perl visible
6396 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6402 RXp_MATCH_COPIED_off(re);
6403 re->subbeg = rex->subbeg;
6404 re->sublen = rex->sublen;
6405 re->suboffset = rex->suboffset;
6406 re->subcoffset = rex->subcoffset;
6408 re->lastcloseparen = 0;
6411 debug_start_match(re_sv, utf8_target, locinput,
6412 reginfo->strend, "Matching embedded");
6414 startpoint = rei->program + 1;
6415 ST.close_paren = 0; /* only used for GOSUB */
6416 /* Save all the seen positions so far. */
6417 ST.cp = regcppush(rex, 0, maxopenparen);
6418 REGCP_SET(ST.lastcp);
6419 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6421 /* run the pattern returned from (??{...}) */
6423 eval_recurse_doit: /* Share code with GOSUB below this line
6424 * At this point we expect the stack context to be
6425 * set up correctly */
6427 /* invalidate the S-L poscache. We're now executing a
6428 * different set of WHILEM ops (and their associated
6429 * indexes) against the same string, so the bits in the
6430 * cache are meaningless. Setting maxiter to zero forces
6431 * the cache to be invalidated and zeroed before reuse.
6432 * XXX This is too dramatic a measure. Ideally we should
6433 * save the old cache and restore when running the outer
6435 reginfo->poscache_maxiter = 0;
6437 /* the new regexp might have a different is_utf8_pat than we do */
6438 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6440 ST.prev_rex = rex_sv;
6441 ST.prev_curlyx = cur_curlyx;
6443 SET_reg_curpm(rex_sv);
6448 ST.prev_eval = cur_eval;
6450 /* now continue from first node in postoned RE */
6451 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
6453 NOT_REACHED; /* NOTREACHED */
6456 case EVAL_AB: /* cleanup after a successful (??{A})B */
6457 /* note: this is called twice; first after popping B, then A */
6458 rex_sv = ST.prev_rex;
6459 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6460 SET_reg_curpm(rex_sv);
6461 rex = ReANY(rex_sv);
6462 rexi = RXi_GET(rex);
6464 /* preserve $^R across LEAVE's. See Bug 121070. */
6465 SV *save_sv= GvSV(PL_replgv);
6466 SvREFCNT_inc(save_sv);
6467 regcpblow(ST.cp); /* LEAVE in disguise */
6468 sv_setsv(GvSV(PL_replgv), save_sv);
6469 SvREFCNT_dec(save_sv);
6471 cur_eval = ST.prev_eval;
6472 cur_curlyx = ST.prev_curlyx;
6474 /* Invalidate cache. See "invalidate" comment above. */
6475 reginfo->poscache_maxiter = 0;
6476 if ( nochange_depth )
6481 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
6482 /* note: this is called twice; first after popping B, then A */
6483 rex_sv = ST.prev_rex;
6484 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6485 SET_reg_curpm(rex_sv);
6486 rex = ReANY(rex_sv);
6487 rexi = RXi_GET(rex);
6489 REGCP_UNWIND(ST.lastcp);
6490 regcppop(rex, &maxopenparen);
6491 cur_eval = ST.prev_eval;
6492 cur_curlyx = ST.prev_curlyx;
6493 /* Invalidate cache. See "invalidate" comment above. */
6494 reginfo->poscache_maxiter = 0;
6495 if ( nochange_depth )
6501 n = ARG(scan); /* which paren pair */
6502 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
6503 if (n > maxopenparen)
6505 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
6506 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
6510 (IV)rex->offs[n].start_tmp,
6516 /* XXX really need to log other places start/end are set too */
6517 #define CLOSE_CAPTURE \
6518 rex->offs[n].start = rex->offs[n].start_tmp; \
6519 rex->offs[n].end = locinput - reginfo->strbeg; \
6520 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
6521 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
6523 PTR2UV(rex->offs), \
6525 (IV)rex->offs[n].start, \
6526 (IV)rex->offs[n].end \
6530 n = ARG(scan); /* which paren pair */
6532 if (n > rex->lastparen)
6534 rex->lastcloseparen = n;
6535 if (cur_eval && cur_eval->u.eval.close_paren == n) {
6540 case ACCEPT: /* (*ACCEPT) */
6544 cursor && OP(cursor)!=END;
6545 cursor=regnext(cursor))
6547 if ( OP(cursor)==CLOSE ){
6549 if ( n <= lastopen ) {
6551 if (n > rex->lastparen)
6553 rex->lastcloseparen = n;
6554 if ( n == ARG(scan) || (cur_eval &&
6555 cur_eval->u.eval.close_paren == n))
6564 case GROUPP: /* (?(1)) */
6565 n = ARG(scan); /* which paren pair */
6566 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
6569 case NGROUPP: /* (?(<name>)) */
6570 /* reg_check_named_buff_matched returns 0 for no match */
6571 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
6574 case INSUBP: /* (?(R)) */
6576 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
6579 case DEFINEP: /* (?(DEFINE)) */
6583 case IFTHEN: /* (?(cond)A|B) */
6584 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6586 next = NEXTOPER(NEXTOPER(scan));
6588 next = scan + ARG(scan);
6589 if (OP(next) == IFTHEN) /* Fake one. */
6590 next = NEXTOPER(NEXTOPER(next));
6594 case LOGICAL: /* modifier for EVAL and IFMATCH */
6595 logical = scan->flags;
6598 /*******************************************************************
6600 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
6601 pattern, where A and B are subpatterns. (For simple A, CURLYM or
6602 STAR/PLUS/CURLY/CURLYN are used instead.)
6604 A*B is compiled as <CURLYX><A><WHILEM><B>
6606 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
6607 state, which contains the current count, initialised to -1. It also sets
6608 cur_curlyx to point to this state, with any previous value saved in the
6611 CURLYX then jumps straight to the WHILEM op, rather than executing A,
6612 since the pattern may possibly match zero times (i.e. it's a while {} loop
6613 rather than a do {} while loop).
6615 Each entry to WHILEM represents a successful match of A. The count in the
6616 CURLYX block is incremented, another WHILEM state is pushed, and execution
6617 passes to A or B depending on greediness and the current count.
6619 For example, if matching against the string a1a2a3b (where the aN are
6620 substrings that match /A/), then the match progresses as follows: (the
6621 pushed states are interspersed with the bits of strings matched so far):
6624 <CURLYX cnt=0><WHILEM>
6625 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
6626 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
6627 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
6628 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
6630 (Contrast this with something like CURLYM, which maintains only a single
6634 a1 <CURLYM cnt=1> a2
6635 a1 a2 <CURLYM cnt=2> a3
6636 a1 a2 a3 <CURLYM cnt=3> b
6639 Each WHILEM state block marks a point to backtrack to upon partial failure
6640 of A or B, and also contains some minor state data related to that
6641 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
6642 overall state, such as the count, and pointers to the A and B ops.
6644 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
6645 must always point to the *current* CURLYX block, the rules are:
6647 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
6648 and set cur_curlyx to point the new block.
6650 When popping the CURLYX block after a successful or unsuccessful match,
6651 restore the previous cur_curlyx.
6653 When WHILEM is about to execute B, save the current cur_curlyx, and set it
6654 to the outer one saved in the CURLYX block.
6656 When popping the WHILEM block after a successful or unsuccessful B match,
6657 restore the previous cur_curlyx.
6659 Here's an example for the pattern (AI* BI)*BO
6660 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
6663 curlyx backtrack stack
6664 ------ ---------------
6666 CO <CO prev=NULL> <WO>
6667 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6668 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6669 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
6671 At this point the pattern succeeds, and we work back down the stack to
6672 clean up, restoring as we go:
6674 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
6675 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
6676 CO <CO prev=NULL> <WO>
6679 *******************************************************************/
6681 #define ST st->u.curlyx
6683 case CURLYX: /* start of /A*B/ (for complex A) */
6685 /* No need to save/restore up to this paren */
6686 I32 parenfloor = scan->flags;
6688 assert(next); /* keep Coverity happy */
6689 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
6692 /* XXXX Probably it is better to teach regpush to support
6693 parenfloor > maxopenparen ... */
6694 if (parenfloor > (I32)rex->lastparen)
6695 parenfloor = rex->lastparen; /* Pessimization... */
6697 ST.prev_curlyx= cur_curlyx;
6699 ST.cp = PL_savestack_ix;
6701 /* these fields contain the state of the current curly.
6702 * they are accessed by subsequent WHILEMs */
6703 ST.parenfloor = parenfloor;
6708 ST.count = -1; /* this will be updated by WHILEM */
6709 ST.lastloc = NULL; /* this will be updated by WHILEM */
6711 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
6713 NOT_REACHED; /* NOTREACHED */
6716 case CURLYX_end: /* just finished matching all of A*B */
6717 cur_curlyx = ST.prev_curlyx;
6720 NOT_REACHED; /* NOTREACHED */
6722 case CURLYX_end_fail: /* just failed to match all of A*B */
6724 cur_curlyx = ST.prev_curlyx;
6727 NOT_REACHED; /* NOTREACHED */
6731 #define ST st->u.whilem
6733 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
6735 /* see the discussion above about CURLYX/WHILEM */
6740 assert(cur_curlyx); /* keep Coverity happy */
6742 min = ARG1(cur_curlyx->u.curlyx.me);
6743 max = ARG2(cur_curlyx->u.curlyx.me);
6744 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
6745 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
6746 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
6747 ST.cache_offset = 0;
6751 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6752 "%*s whilem: matched %ld out of %d..%d\n",
6753 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
6756 /* First just match a string of min A's. */
6759 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6761 cur_curlyx->u.curlyx.lastloc = locinput;
6762 REGCP_SET(ST.lastcp);
6764 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
6766 NOT_REACHED; /* NOTREACHED */
6769 /* If degenerate A matches "", assume A done. */
6771 if (locinput == cur_curlyx->u.curlyx.lastloc) {
6772 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6773 "%*s whilem: empty match detected, trying continuation...\n",
6774 REPORT_CODE_OFF+depth*2, "")
6776 goto do_whilem_B_max;
6779 /* super-linear cache processing.
6781 * The idea here is that for certain types of CURLYX/WHILEM -
6782 * principally those whose upper bound is infinity (and
6783 * excluding regexes that have things like \1 and other very
6784 * non-regular expresssiony things), then if a pattern like
6785 * /....A*.../ fails and we backtrack to the WHILEM, then we
6786 * make a note that this particular WHILEM op was at string
6787 * position 47 (say) when the rest of pattern failed. Then, if
6788 * we ever find ourselves back at that WHILEM, and at string
6789 * position 47 again, we can just fail immediately rather than
6790 * running the rest of the pattern again.
6792 * This is very handy when patterns start to go
6793 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
6794 * with a combinatorial explosion of backtracking.
6796 * The cache is implemented as a bit array, with one bit per
6797 * string byte position per WHILEM op (up to 16) - so its
6798 * between 0.25 and 2x the string size.
6800 * To avoid allocating a poscache buffer every time, we do an
6801 * initially countdown; only after we have executed a WHILEM
6802 * op (string-length x #WHILEMs) times do we allocate the
6805 * The top 4 bits of scan->flags byte say how many different
6806 * relevant CURLLYX/WHILEM op pairs there are, while the
6807 * bottom 4-bits is the identifying index number of this
6813 if (!reginfo->poscache_maxiter) {
6814 /* start the countdown: Postpone detection until we
6815 * know the match is not *that* much linear. */
6816 reginfo->poscache_maxiter
6817 = (reginfo->strend - reginfo->strbeg + 1)
6819 /* possible overflow for long strings and many CURLYX's */
6820 if (reginfo->poscache_maxiter < 0)
6821 reginfo->poscache_maxiter = I32_MAX;
6822 reginfo->poscache_iter = reginfo->poscache_maxiter;
6825 if (reginfo->poscache_iter-- == 0) {
6826 /* initialise cache */
6827 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
6828 regmatch_info_aux *const aux = reginfo->info_aux;
6829 if (aux->poscache) {
6830 if ((SSize_t)reginfo->poscache_size < size) {
6831 Renew(aux->poscache, size, char);
6832 reginfo->poscache_size = size;
6834 Zero(aux->poscache, size, char);
6837 reginfo->poscache_size = size;
6838 Newxz(aux->poscache, size, char);
6840 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6841 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
6842 PL_colors[4], PL_colors[5])
6846 if (reginfo->poscache_iter < 0) {
6847 /* have we already failed at this position? */
6848 SSize_t offset, mask;
6850 reginfo->poscache_iter = -1; /* stop eventual underflow */
6851 offset = (scan->flags & 0xf) - 1
6852 + (locinput - reginfo->strbeg)
6854 mask = 1 << (offset % 8);
6856 if (reginfo->info_aux->poscache[offset] & mask) {
6857 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
6858 "%*s whilem: (cache) already tried at this position...\n",
6859 REPORT_CODE_OFF+depth*2, "")
6861 sayNO; /* cache records failure */
6863 ST.cache_offset = offset;
6864 ST.cache_mask = mask;
6868 /* Prefer B over A for minimal matching. */
6870 if (cur_curlyx->u.curlyx.minmod) {
6871 ST.save_curlyx = cur_curlyx;
6872 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6873 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
6875 REGCP_SET(ST.lastcp);
6876 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
6879 NOT_REACHED; /* NOTREACHED */
6882 /* Prefer A over B for maximal matching. */
6884 if (n < max) { /* More greed allowed? */
6885 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6887 cur_curlyx->u.curlyx.lastloc = locinput;
6888 REGCP_SET(ST.lastcp);
6889 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
6891 NOT_REACHED; /* NOTREACHED */
6893 goto do_whilem_B_max;
6896 NOT_REACHED; /* NOTREACHED */
6898 case WHILEM_B_min: /* just matched B in a minimal match */
6899 case WHILEM_B_max: /* just matched B in a maximal match */
6900 cur_curlyx = ST.save_curlyx;
6903 NOT_REACHED; /* NOTREACHED */
6905 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
6906 cur_curlyx = ST.save_curlyx;
6907 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6908 cur_curlyx->u.curlyx.count--;
6911 NOT_REACHED; /* NOTREACHED */
6913 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
6915 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
6916 REGCP_UNWIND(ST.lastcp);
6917 regcppop(rex, &maxopenparen);
6918 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
6919 cur_curlyx->u.curlyx.count--;
6922 NOT_REACHED; /* NOTREACHED */
6924 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
6925 REGCP_UNWIND(ST.lastcp);
6926 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
6927 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6928 "%*s whilem: failed, trying continuation...\n",
6929 REPORT_CODE_OFF+depth*2, "")
6932 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6933 && ckWARN(WARN_REGEXP)
6934 && !reginfo->warned)
6936 reginfo->warned = TRUE;
6937 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6938 "Complex regular subexpression recursion limit (%d) "
6944 ST.save_curlyx = cur_curlyx;
6945 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
6946 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
6949 NOT_REACHED; /* NOTREACHED */
6951 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
6952 cur_curlyx = ST.save_curlyx;
6953 REGCP_UNWIND(ST.lastcp);
6954 regcppop(rex, &maxopenparen);
6956 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
6957 /* Maximum greed exceeded */
6958 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6959 && ckWARN(WARN_REGEXP)
6960 && !reginfo->warned)
6962 reginfo->warned = TRUE;
6963 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
6964 "Complex regular subexpression recursion "
6965 "limit (%d) exceeded",
6968 cur_curlyx->u.curlyx.count--;
6972 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6973 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
6975 /* Try grabbing another A and see if it helps. */
6976 cur_curlyx->u.curlyx.lastloc = locinput;
6977 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6979 REGCP_SET(ST.lastcp);
6980 PUSH_STATE_GOTO(WHILEM_A_min,
6981 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6984 NOT_REACHED; /* NOTREACHED */
6987 #define ST st->u.branch
6989 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
6990 next = scan + ARG(scan);
6993 scan = NEXTOPER(scan);
6996 case BRANCH: /* /(...|A|...)/ */
6997 scan = NEXTOPER(scan); /* scan now points to inner node */
6998 ST.lastparen = rex->lastparen;
6999 ST.lastcloseparen = rex->lastcloseparen;
7000 ST.next_branch = next;
7003 /* Now go into the branch */
7005 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7007 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7010 NOT_REACHED; /* NOTREACHED */
7012 case CUTGROUP: /* /(*THEN)/ */
7013 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
7014 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7015 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7017 NOT_REACHED; /* NOTREACHED */
7019 case CUTGROUP_next_fail:
7022 if (st->u.mark.mark_name)
7023 sv_commit = st->u.mark.mark_name;
7026 NOT_REACHED; /* NOTREACHED */
7031 NOT_REACHED; /* NOTREACHED */
7033 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7038 REGCP_UNWIND(ST.cp);
7039 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7040 scan = ST.next_branch;
7041 /* no more branches? */
7042 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7044 PerlIO_printf( Perl_debug_log,
7045 "%*s %sBRANCH failed...%s\n",
7046 REPORT_CODE_OFF+depth*2, "",
7052 continue; /* execute next BRANCH[J] op */
7055 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7060 #define ST st->u.curlym
7062 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7064 /* This is an optimisation of CURLYX that enables us to push
7065 * only a single backtracking state, no matter how many matches
7066 * there are in {m,n}. It relies on the pattern being constant
7067 * length, with no parens to influence future backrefs
7071 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7073 ST.lastparen = rex->lastparen;
7074 ST.lastcloseparen = rex->lastcloseparen;
7076 /* if paren positive, emulate an OPEN/CLOSE around A */
7078 U32 paren = ST.me->flags;
7079 if (paren > maxopenparen)
7080 maxopenparen = paren;
7081 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7089 ST.c1 = CHRTEST_UNINIT;
7092 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7095 curlym_do_A: /* execute the A in /A{m,n}B/ */
7096 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7098 NOT_REACHED; /* NOTREACHED */
7100 case CURLYM_A: /* we've just matched an A */
7102 /* after first match, determine A's length: u.curlym.alen */
7103 if (ST.count == 1) {
7104 if (reginfo->is_utf8_target) {
7105 char *s = st->locinput;
7106 while (s < locinput) {
7112 ST.alen = locinput - st->locinput;
7115 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7118 PerlIO_printf(Perl_debug_log,
7119 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7120 (int)(REPORT_CODE_OFF+(depth*2)), "",
7121 (IV) ST.count, (IV)ST.alen)
7124 if (cur_eval && cur_eval->u.eval.close_paren &&
7125 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7129 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7130 if ( max == REG_INFTY || ST.count < max )
7131 goto curlym_do_A; /* try to match another A */
7133 goto curlym_do_B; /* try to match B */
7135 case CURLYM_A_fail: /* just failed to match an A */
7136 REGCP_UNWIND(ST.cp);
7138 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7139 || (cur_eval && cur_eval->u.eval.close_paren &&
7140 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7143 curlym_do_B: /* execute the B in /A{m,n}B/ */
7144 if (ST.c1 == CHRTEST_UNINIT) {
7145 /* calculate c1 and c2 for possible match of 1st char
7146 * following curly */
7147 ST.c1 = ST.c2 = CHRTEST_VOID;
7149 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7150 regnode *text_node = ST.B;
7151 if (! HAS_TEXT(text_node))
7152 FIND_NEXT_IMPT(text_node);
7155 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7157 But the former is redundant in light of the latter.
7159 if this changes back then the macro for
7160 IS_TEXT and friends need to change.
7162 if (PL_regkind[OP(text_node)] == EXACT) {
7163 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7164 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7174 PerlIO_printf(Perl_debug_log,
7175 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
7176 (int)(REPORT_CODE_OFF+(depth*2)),
7179 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7180 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7181 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7182 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7184 /* simulate B failing */
7186 PerlIO_printf(Perl_debug_log,
7187 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7188 (int)(REPORT_CODE_OFF+(depth*2)),"",
7189 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7190 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7191 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7193 state_num = CURLYM_B_fail;
7194 goto reenter_switch;
7197 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7198 /* simulate B failing */
7200 PerlIO_printf(Perl_debug_log,
7201 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7202 (int)(REPORT_CODE_OFF+(depth*2)),"",
7203 (int) nextchr, ST.c1, ST.c2)
7205 state_num = CURLYM_B_fail;
7206 goto reenter_switch;
7211 /* emulate CLOSE: mark current A as captured */
7212 I32 paren = ST.me->flags;
7214 rex->offs[paren].start
7215 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7216 rex->offs[paren].end = locinput - reginfo->strbeg;
7217 if ((U32)paren > rex->lastparen)
7218 rex->lastparen = paren;
7219 rex->lastcloseparen = paren;
7222 rex->offs[paren].end = -1;
7223 if (cur_eval && cur_eval->u.eval.close_paren &&
7224 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7233 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7235 NOT_REACHED; /* NOTREACHED */
7237 case CURLYM_B_fail: /* just failed to match a B */
7238 REGCP_UNWIND(ST.cp);
7239 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7241 I32 max = ARG2(ST.me);
7242 if (max != REG_INFTY && ST.count == max)
7244 goto curlym_do_A; /* try to match a further A */
7246 /* backtrack one A */
7247 if (ST.count == ARG1(ST.me) /* min */)
7250 SET_locinput(HOPc(locinput, -ST.alen));
7251 goto curlym_do_B; /* try to match B */
7254 #define ST st->u.curly
7256 #define CURLY_SETPAREN(paren, success) \
7259 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7260 rex->offs[paren].end = locinput - reginfo->strbeg; \
7261 if (paren > rex->lastparen) \
7262 rex->lastparen = paren; \
7263 rex->lastcloseparen = paren; \
7266 rex->offs[paren].end = -1; \
7267 rex->lastparen = ST.lastparen; \
7268 rex->lastcloseparen = ST.lastcloseparen; \
7272 case STAR: /* /A*B/ where A is width 1 char */
7276 scan = NEXTOPER(scan);
7279 case PLUS: /* /A+B/ where A is width 1 char */
7283 scan = NEXTOPER(scan);
7286 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7287 ST.paren = scan->flags; /* Which paren to set */
7288 ST.lastparen = rex->lastparen;
7289 ST.lastcloseparen = rex->lastcloseparen;
7290 if (ST.paren > maxopenparen)
7291 maxopenparen = ST.paren;
7292 ST.min = ARG1(scan); /* min to match */
7293 ST.max = ARG2(scan); /* max to match */
7294 if (cur_eval && cur_eval->u.eval.close_paren &&
7295 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7299 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7302 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7304 ST.min = ARG1(scan); /* min to match */
7305 ST.max = ARG2(scan); /* max to match */
7306 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7309 * Lookahead to avoid useless match attempts
7310 * when we know what character comes next.
7312 * Used to only do .*x and .*?x, but now it allows
7313 * for )'s, ('s and (?{ ... })'s to be in the way
7314 * of the quantifier and the EXACT-like node. -- japhy
7317 assert(ST.min <= ST.max);
7318 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7319 ST.c1 = ST.c2 = CHRTEST_VOID;
7322 regnode *text_node = next;
7324 if (! HAS_TEXT(text_node))
7325 FIND_NEXT_IMPT(text_node);
7327 if (! HAS_TEXT(text_node))
7328 ST.c1 = ST.c2 = CHRTEST_VOID;
7330 if ( PL_regkind[OP(text_node)] != EXACT ) {
7331 ST.c1 = ST.c2 = CHRTEST_VOID;
7335 /* Currently we only get here when
7337 PL_rekind[OP(text_node)] == EXACT
7339 if this changes back then the macro for IS_TEXT and
7340 friends need to change. */
7341 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7342 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7354 char *li = locinput;
7357 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7363 if (ST.c1 == CHRTEST_VOID)
7364 goto curly_try_B_min;
7366 ST.oldloc = locinput;
7368 /* set ST.maxpos to the furthest point along the
7369 * string that could possibly match */
7370 if (ST.max == REG_INFTY) {
7371 ST.maxpos = reginfo->strend - 1;
7373 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7376 else if (utf8_target) {
7377 int m = ST.max - ST.min;
7378 for (ST.maxpos = locinput;
7379 m >0 && ST.maxpos < reginfo->strend; m--)
7380 ST.maxpos += UTF8SKIP(ST.maxpos);
7383 ST.maxpos = locinput + ST.max - ST.min;
7384 if (ST.maxpos >= reginfo->strend)
7385 ST.maxpos = reginfo->strend - 1;
7387 goto curly_try_B_min_known;
7391 /* avoid taking address of locinput, so it can remain
7393 char *li = locinput;
7394 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7395 if (ST.count < ST.min)
7398 if ((ST.count > ST.min)
7399 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7401 /* A{m,n} must come at the end of the string, there's
7402 * no point in backing off ... */
7404 /* ...except that $ and \Z can match before *and* after
7405 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7406 We may back off by one in this case. */
7407 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7411 goto curly_try_B_max;
7414 NOT_REACHED; /* NOTREACHED */
7416 case CURLY_B_min_known_fail:
7417 /* failed to find B in a non-greedy match where c1,c2 valid */
7419 REGCP_UNWIND(ST.cp);
7421 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7423 /* Couldn't or didn't -- move forward. */
7424 ST.oldloc = locinput;
7426 locinput += UTF8SKIP(locinput);
7430 curly_try_B_min_known:
7431 /* find the next place where 'B' could work, then call B */
7435 n = (ST.oldloc == locinput) ? 0 : 1;
7436 if (ST.c1 == ST.c2) {
7437 /* set n to utf8_distance(oldloc, locinput) */
7438 while (locinput <= ST.maxpos
7439 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7441 locinput += UTF8SKIP(locinput);
7446 /* set n to utf8_distance(oldloc, locinput) */
7447 while (locinput <= ST.maxpos
7448 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7449 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7451 locinput += UTF8SKIP(locinput);
7456 else { /* Not utf8_target */
7457 if (ST.c1 == ST.c2) {
7458 while (locinput <= ST.maxpos &&
7459 UCHARAT(locinput) != ST.c1)
7463 while (locinput <= ST.maxpos
7464 && UCHARAT(locinput) != ST.c1
7465 && UCHARAT(locinput) != ST.c2)
7468 n = locinput - ST.oldloc;
7470 if (locinput > ST.maxpos)
7473 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7474 * at b; check that everything between oldloc and
7475 * locinput matches */
7476 char *li = ST.oldloc;
7478 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7480 assert(n == REG_INFTY || locinput == li);
7482 CURLY_SETPAREN(ST.paren, ST.count);
7483 if (cur_eval && cur_eval->u.eval.close_paren &&
7484 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7487 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7490 NOT_REACHED; /* NOTREACHED */
7492 case CURLY_B_min_fail:
7493 /* failed to find B in a non-greedy match where c1,c2 invalid */
7495 REGCP_UNWIND(ST.cp);
7497 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7499 /* failed -- move forward one */
7501 char *li = locinput;
7502 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7509 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7510 ST.count > 0)) /* count overflow ? */
7513 CURLY_SETPAREN(ST.paren, ST.count);
7514 if (cur_eval && cur_eval->u.eval.close_paren &&
7515 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7518 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7523 NOT_REACHED; /* NOTREACHED */
7526 /* a successful greedy match: now try to match B */
7527 if (cur_eval && cur_eval->u.eval.close_paren &&
7528 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7532 bool could_match = locinput < reginfo->strend;
7534 /* If it could work, try it. */
7535 if (ST.c1 != CHRTEST_VOID && could_match) {
7536 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7538 could_match = memEQ(locinput,
7543 UTF8SKIP(locinput));
7546 could_match = UCHARAT(locinput) == ST.c1
7547 || UCHARAT(locinput) == ST.c2;
7550 if (ST.c1 == CHRTEST_VOID || could_match) {
7551 CURLY_SETPAREN(ST.paren, ST.count);
7552 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7554 NOT_REACHED; /* NOTREACHED */
7559 case CURLY_B_max_fail:
7560 /* failed to find B in a greedy match */
7562 REGCP_UNWIND(ST.cp);
7564 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7567 if (--ST.count < ST.min)
7569 locinput = HOPc(locinput, -1);
7570 goto curly_try_B_max;
7574 case END: /* last op of main pattern */
7577 /* we've just finished A in /(??{A})B/; now continue with B */
7579 st->u.eval.prev_rex = rex_sv; /* inner */
7581 /* Save *all* the positions. */
7582 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7583 rex_sv = cur_eval->u.eval.prev_rex;
7584 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7585 SET_reg_curpm(rex_sv);
7586 rex = ReANY(rex_sv);
7587 rexi = RXi_GET(rex);
7588 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7590 REGCP_SET(st->u.eval.lastcp);
7592 /* Restore parens of the outer rex without popping the
7594 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7597 st->u.eval.prev_eval = cur_eval;
7598 cur_eval = cur_eval->u.eval.prev_eval;
7600 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
7601 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7602 if ( nochange_depth )
7605 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7606 locinput); /* match B */
7609 if (locinput < reginfo->till) {
7610 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7611 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7613 (long)(locinput - startpos),
7614 (long)(reginfo->till - startpos),
7617 sayNO_SILENT; /* Cannot match: too short. */
7619 sayYES; /* Success! */
7621 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7623 PerlIO_printf(Perl_debug_log,
7624 "%*s %ssubpattern success...%s\n",
7625 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7626 sayYES; /* Success! */
7629 #define ST st->u.ifmatch
7634 case SUSPEND: /* (?>A) */
7636 newstart = locinput;
7639 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
7641 goto ifmatch_trivial_fail_test;
7643 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
7645 ifmatch_trivial_fail_test:
7647 char * const s = HOPBACKc(locinput, scan->flags);
7652 sw = 1 - cBOOL(ST.wanted);
7656 next = scan + ARG(scan);
7664 newstart = locinput;
7668 ST.logical = logical;
7669 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
7671 /* execute body of (?...A) */
7672 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
7674 NOT_REACHED; /* NOTREACHED */
7677 case IFMATCH_A_fail: /* body of (?...A) failed */
7678 ST.wanted = !ST.wanted;
7681 case IFMATCH_A: /* body of (?...A) succeeded */
7683 sw = cBOOL(ST.wanted);
7685 else if (!ST.wanted)
7688 if (OP(ST.me) != SUSPEND) {
7689 /* restore old position except for (?>...) */
7690 locinput = st->locinput;
7692 scan = ST.me + ARG(ST.me);
7695 continue; /* execute B */
7699 case LONGJMP: /* alternative with many branches compiles to
7700 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
7701 next = scan + ARG(scan);
7706 case COMMIT: /* (*COMMIT) */
7707 reginfo->cutpoint = reginfo->strend;
7710 case PRUNE: /* (*PRUNE) */
7712 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7713 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
7715 NOT_REACHED; /* NOTREACHED */
7717 case COMMIT_next_fail:
7721 case OPFAIL: /* (*FAIL) */
7724 NOT_REACHED; /* NOTREACHED */
7726 #define ST st->u.mark
7727 case MARKPOINT: /* (*MARK:foo) */
7728 ST.prev_mark = mark_state;
7729 ST.mark_name = sv_commit = sv_yes_mark
7730 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7732 ST.mark_loc = locinput;
7733 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
7735 NOT_REACHED; /* NOTREACHED */
7737 case MARKPOINT_next:
7738 mark_state = ST.prev_mark;
7741 NOT_REACHED; /* NOTREACHED */
7743 case MARKPOINT_next_fail:
7744 if (popmark && sv_eq(ST.mark_name,popmark))
7746 if (ST.mark_loc > startpoint)
7747 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7748 popmark = NULL; /* we found our mark */
7749 sv_commit = ST.mark_name;
7752 PerlIO_printf(Perl_debug_log,
7753 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
7754 REPORT_CODE_OFF+depth*2, "",
7755 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
7758 mark_state = ST.prev_mark;
7759 sv_yes_mark = mark_state ?
7760 mark_state->u.mark.mark_name : NULL;
7763 NOT_REACHED; /* NOTREACHED */
7765 case SKIP: /* (*SKIP) */
7767 /* (*SKIP) : if we fail we cut here*/
7768 ST.mark_name = NULL;
7769 ST.mark_loc = locinput;
7770 PUSH_STATE_GOTO(SKIP_next,next, locinput);
7772 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
7773 otherwise do nothing. Meaning we need to scan
7775 regmatch_state *cur = mark_state;
7776 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7779 if ( sv_eq( cur->u.mark.mark_name,
7782 ST.mark_name = find;
7783 PUSH_STATE_GOTO( SKIP_next, next, locinput);
7785 cur = cur->u.mark.prev_mark;
7788 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
7791 case SKIP_next_fail:
7793 /* (*CUT:NAME) - Set up to search for the name as we
7794 collapse the stack*/
7795 popmark = ST.mark_name;
7797 /* (*CUT) - No name, we cut here.*/
7798 if (ST.mark_loc > startpoint)
7799 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
7800 /* but we set sv_commit to latest mark_name if there
7801 is one so they can test to see how things lead to this
7804 sv_commit=mark_state->u.mark.mark_name;
7809 NOT_REACHED; /* NOTREACHED */
7812 case LNBREAK: /* \R */
7813 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
7820 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
7821 PTR2UV(scan), OP(scan));
7822 Perl_croak(aTHX_ "regexp memory corruption");
7824 /* this is a point to jump to in order to increment
7825 * locinput by one character */
7827 assert(!NEXTCHR_IS_EOS);
7829 locinput += PL_utf8skip[nextchr];
7830 /* locinput is allowed to go 1 char off the end, but not 2+ */
7831 if (locinput > reginfo->strend)
7840 /* switch break jumps here */
7841 scan = next; /* prepare to execute the next op and ... */
7842 continue; /* ... jump back to the top, reusing st */
7846 /* push a state that backtracks on success */
7847 st->u.yes.prev_yes_state = yes_state;
7851 /* push a new regex state, then continue at scan */
7853 regmatch_state *newst;
7856 regmatch_state *cur = st;
7857 regmatch_state *curyes = yes_state;
7859 regmatch_slab *slab = PL_regmatch_slab;
7860 for (;curd > -1;cur--,curd--) {
7861 if (cur < SLAB_FIRST(slab)) {
7863 cur = SLAB_LAST(slab);
7865 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
7866 REPORT_CODE_OFF + 2 + depth * 2,"",
7867 curd, PL_reg_name[cur->resume_state],
7868 (curyes == cur) ? "yes" : ""
7871 curyes = cur->u.yes.prev_yes_state;
7874 DEBUG_STATE_pp("push")
7877 st->locinput = locinput;
7879 if (newst > SLAB_LAST(PL_regmatch_slab))
7880 newst = S_push_slab(aTHX);
7881 PL_regmatch_state = newst;
7883 locinput = pushinput;
7891 * We get here only if there's trouble -- normally "case END" is
7892 * the terminating point.
7894 Perl_croak(aTHX_ "corrupted regexp pointers");
7897 NOT_REACHED; /* NOTREACHED */
7901 /* we have successfully completed a subexpression, but we must now
7902 * pop to the state marked by yes_state and continue from there */
7903 assert(st != yes_state);
7905 while (st != yes_state) {
7907 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7908 PL_regmatch_slab = PL_regmatch_slab->prev;
7909 st = SLAB_LAST(PL_regmatch_slab);
7913 DEBUG_STATE_pp("pop (no final)");
7915 DEBUG_STATE_pp("pop (yes)");
7921 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
7922 || yes_state > SLAB_LAST(PL_regmatch_slab))
7924 /* not in this slab, pop slab */
7925 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
7926 PL_regmatch_slab = PL_regmatch_slab->prev;
7927 st = SLAB_LAST(PL_regmatch_slab);
7929 depth -= (st - yes_state);
7932 yes_state = st->u.yes.prev_yes_state;
7933 PL_regmatch_state = st;
7936 locinput= st->locinput;
7937 state_num = st->resume_state + no_final;
7938 goto reenter_switch;
7941 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
7942 PL_colors[4], PL_colors[5]));
7944 if (reginfo->info_aux_eval) {
7945 /* each successfully executed (?{...}) block does the equivalent of
7946 * local $^R = do {...}
7947 * When popping the save stack, all these locals would be undone;
7948 * bypass this by setting the outermost saved $^R to the latest
7950 /* I dont know if this is needed or works properly now.
7951 * see code related to PL_replgv elsewhere in this file.
7954 if (oreplsv != GvSV(PL_replgv))
7955 sv_setsv(oreplsv, GvSV(PL_replgv));
7962 PerlIO_printf(Perl_debug_log,
7963 "%*s %sfailed...%s\n",
7964 REPORT_CODE_OFF+depth*2, "",
7965 PL_colors[4], PL_colors[5])
7977 /* there's a previous state to backtrack to */
7979 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7980 PL_regmatch_slab = PL_regmatch_slab->prev;
7981 st = SLAB_LAST(PL_regmatch_slab);
7983 PL_regmatch_state = st;
7984 locinput= st->locinput;
7986 DEBUG_STATE_pp("pop");
7988 if (yes_state == st)
7989 yes_state = st->u.yes.prev_yes_state;
7991 state_num = st->resume_state + 1; /* failure = success + 1 */
7992 goto reenter_switch;
7997 if (rex->intflags & PREGf_VERBARG_SEEN) {
7998 SV *sv_err = get_sv("REGERROR", 1);
7999 SV *sv_mrk = get_sv("REGMARK", 1);
8001 sv_commit = &PL_sv_no;
8003 sv_yes_mark = &PL_sv_yes;
8006 sv_commit = &PL_sv_yes;
8007 sv_yes_mark = &PL_sv_no;
8011 sv_setsv(sv_err, sv_commit);
8012 sv_setsv(sv_mrk, sv_yes_mark);
8016 if (last_pushed_cv) {
8019 PERL_UNUSED_VAR(SP);
8022 assert(!result || locinput - reginfo->strbeg >= 0);
8023 return result ? locinput - reginfo->strbeg : -1;
8027 - regrepeat - repeatedly match something simple, report how many
8029 * What 'simple' means is a node which can be the operand of a quantifier like
8032 * startposp - pointer a pointer to the start position. This is updated
8033 * to point to the byte following the highest successful
8035 * p - the regnode to be repeatedly matched against.
8036 * reginfo - struct holding match state, such as strend
8037 * max - maximum number of things to match.
8038 * depth - (for debugging) backtracking depth.
8041 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8042 regmatch_info *const reginfo, I32 max, int depth)
8044 char *scan; /* Pointer to current position in target string */
8046 char *loceol = reginfo->strend; /* local version */
8047 I32 hardcount = 0; /* How many matches so far */
8048 bool utf8_target = reginfo->is_utf8_target;
8049 unsigned int to_complement = 0; /* Invert the result? */
8051 _char_class_number classnum;
8053 PERL_UNUSED_ARG(depth);
8056 PERL_ARGS_ASSERT_REGREPEAT;
8059 if (max == REG_INFTY)
8061 else if (! utf8_target && loceol - scan > max)
8062 loceol = scan + max;
8064 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8065 * to the maximum of how far we should go in it (leaving it set to the real
8066 * end, if the maximum permissible would take us beyond that). This allows
8067 * us to make the loop exit condition that we haven't gone past <loceol> to
8068 * also mean that we haven't exceeded the max permissible count, saving a
8069 * test each time through the loop. But it assumes that the OP matches a
8070 * single byte, which is true for most of the OPs below when applied to a
8071 * non-UTF-8 target. Those relatively few OPs that don't have this
8072 * characteristic will have to compensate.
8074 * There is no adjustment for UTF-8 targets, as the number of bytes per
8075 * character varies. OPs will have to test both that the count is less
8076 * than the max permissible (using <hardcount> to keep track), and that we
8077 * are still within the bounds of the string (using <loceol>. A few OPs
8078 * match a single byte no matter what the encoding. They can omit the max
8079 * test if, for the UTF-8 case, they do the adjustment that was skipped
8082 * Thus, the code above sets things up for the common case; and exceptional
8083 * cases need extra work; the common case is to make sure <scan> doesn't
8084 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8085 * count doesn't exceed the maximum permissible */
8090 while (scan < loceol && hardcount < max && *scan != '\n') {
8091 scan += UTF8SKIP(scan);
8095 while (scan < loceol && *scan != '\n')
8101 while (scan < loceol && hardcount < max) {
8102 scan += UTF8SKIP(scan);
8109 case CANY: /* Move <scan> forward <max> bytes, unless goes off end */
8110 if (utf8_target && loceol - scan > max) {
8112 /* <loceol> hadn't been adjusted in the UTF-8 case */
8120 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8121 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8122 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8126 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8130 /* Can use a simple loop if the pattern char to match on is invariant
8131 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8132 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8133 * true iff it doesn't matter if the argument is in UTF-8 or not */
8134 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8135 if (utf8_target && loceol - scan > max) {
8136 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8137 * since here, to match at all, 1 char == 1 byte */
8138 loceol = scan + max;
8140 while (scan < loceol && UCHARAT(scan) == c) {
8144 else if (reginfo->is_utf8_pat) {
8146 STRLEN scan_char_len;
8148 /* When both target and pattern are UTF-8, we have to do
8150 while (hardcount < max
8152 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8153 && memEQ(scan, STRING(p), scan_char_len))
8155 scan += scan_char_len;
8159 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8161 /* Target isn't utf8; convert the character in the UTF-8
8162 * pattern to non-UTF8, and do a simple loop */
8163 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8164 while (scan < loceol && UCHARAT(scan) == c) {
8167 } /* else pattern char is above Latin1, can't possibly match the
8172 /* Here, the string must be utf8; pattern isn't, and <c> is
8173 * different in utf8 than not, so can't compare them directly.
8174 * Outside the loop, find the two utf8 bytes that represent c, and
8175 * then look for those in sequence in the utf8 string */
8176 U8 high = UTF8_TWO_BYTE_HI(c);
8177 U8 low = UTF8_TWO_BYTE_LO(c);
8179 while (hardcount < max
8180 && scan + 1 < loceol
8181 && UCHARAT(scan) == high
8182 && UCHARAT(scan + 1) == low)
8190 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8191 assert(! reginfo->is_utf8_pat);
8194 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8198 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8199 utf8_flags = FOLDEQ_LOCALE;
8202 case EXACTF: /* This node only generated for non-utf8 patterns */
8203 assert(! reginfo->is_utf8_pat);
8208 if (! utf8_target) {
8211 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8212 | FOLDEQ_S2_FOLDS_SANE;
8217 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8221 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8223 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8225 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8228 if (c1 == CHRTEST_VOID) {
8229 /* Use full Unicode fold matching */
8230 char *tmpeol = reginfo->strend;
8231 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8232 while (hardcount < max
8233 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8234 STRING(p), NULL, pat_len,
8235 reginfo->is_utf8_pat, utf8_flags))
8238 tmpeol = reginfo->strend;
8242 else if (utf8_target) {
8244 while (scan < loceol
8246 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8248 scan += UTF8SKIP(scan);
8253 while (scan < loceol
8255 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8256 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8258 scan += UTF8SKIP(scan);
8263 else if (c1 == c2) {
8264 while (scan < loceol && UCHARAT(scan) == c1) {
8269 while (scan < loceol &&
8270 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8279 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8283 while (hardcount < max
8285 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8287 scan += UTF8SKIP(scan);
8291 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
8296 /* The argument (FLAGS) to all the POSIX node types is the class number */
8303 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8304 if (! utf8_target) {
8305 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8311 while (hardcount < max && scan < loceol
8312 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8315 scan += UTF8SKIP(scan);
8328 if (utf8_target && loceol - scan > max) {
8330 /* We didn't adjust <loceol> at the beginning of this routine
8331 * because is UTF-8, but it is actually ok to do so, since here, to
8332 * match, 1 char == 1 byte. */
8333 loceol = scan + max;
8335 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8348 if (! utf8_target) {
8349 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8355 /* The complement of something that matches only ASCII matches all
8356 * non-ASCII, plus everything in ASCII that isn't in the class. */
8357 while (hardcount < max && scan < loceol
8358 && (! isASCII_utf8(scan)
8359 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8361 scan += UTF8SKIP(scan);
8372 if (! utf8_target) {
8373 while (scan < loceol && to_complement
8374 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8381 classnum = (_char_class_number) FLAGS(p);
8382 if (classnum < _FIRST_NON_SWASH_CC) {
8384 /* Here, a swash is needed for above-Latin1 code points.
8385 * Process as many Latin1 code points using the built-in rules.
8386 * Go to another loop to finish processing upon encountering
8387 * the first Latin1 code point. We could do that in this loop
8388 * as well, but the other way saves having to test if the swash
8389 * has been loaded every time through the loop: extra space to
8391 while (hardcount < max && scan < loceol) {
8392 if (UTF8_IS_INVARIANT(*scan)) {
8393 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8400 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8401 if (! (to_complement
8402 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
8411 goto found_above_latin1;
8418 /* For these character classes, the knowledge of how to handle
8419 * every code point is compiled in to Perl via a macro. This
8420 * code is written for making the loops as tight as possible.
8421 * It could be refactored to save space instead */
8423 case _CC_ENUM_SPACE:
8424 while (hardcount < max
8426 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8428 scan += UTF8SKIP(scan);
8432 case _CC_ENUM_BLANK:
8433 while (hardcount < max
8435 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8437 scan += UTF8SKIP(scan);
8441 case _CC_ENUM_XDIGIT:
8442 while (hardcount < max
8444 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8446 scan += UTF8SKIP(scan);
8450 case _CC_ENUM_VERTSPACE:
8451 while (hardcount < max
8453 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8455 scan += UTF8SKIP(scan);
8459 case _CC_ENUM_CNTRL:
8460 while (hardcount < max
8462 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8464 scan += UTF8SKIP(scan);
8469 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8475 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
8477 /* Load the swash if not already present */
8478 if (! PL_utf8_swash_ptrs[classnum]) {
8479 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8480 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8484 PL_XPosix_ptrs[classnum], &flags);
8487 while (hardcount < max && scan < loceol
8488 && to_complement ^ cBOOL(_generic_utf8(
8491 swash_fetch(PL_utf8_swash_ptrs[classnum],
8495 scan += UTF8SKIP(scan);
8502 while (hardcount < max && scan < loceol &&
8503 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8508 /* LNBREAK can match one or two latin chars, which is ok, but we
8509 * have to use hardcount in this situation, and throw away the
8510 * adjustment to <loceol> done before the switch statement */
8511 loceol = reginfo->strend;
8512 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8521 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8535 /* These are all 0 width, so match right here or not at all. */
8539 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8541 NOT_REACHED; /* NOTREACHED */
8548 c = scan - *startposp;
8552 GET_RE_DEBUG_FLAGS_DECL;
8554 SV * const prop = sv_newmortal();
8555 regprop(prog, prop, p, reginfo, NULL);
8556 PerlIO_printf(Perl_debug_log,
8557 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
8558 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8566 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8568 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
8569 create a copy so that changes the caller makes won't change the shared one.
8570 If <altsvp> is non-null, will return NULL in it, for back-compat.
8573 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8575 PERL_ARGS_ASSERT_REGCLASS_SWASH;
8581 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8584 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8587 - reginclass - determine if a character falls into a character class
8589 n is the ANYOF-type regnode
8590 p is the target string
8591 p_end points to one byte beyond the end of the target string
8592 utf8_target tells whether p is in UTF-8.
8594 Returns true if matched; false otherwise.
8596 Note that this can be a synthetic start class, a combination of various
8597 nodes, so things you think might be mutually exclusive, such as locale,
8598 aren't. It can match both locale and non-locale
8603 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8606 const char flags = ANYOF_FLAGS(n);
8610 PERL_ARGS_ASSERT_REGINCLASS;
8612 /* If c is not already the code point, get it. Note that
8613 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8614 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8616 c = utf8n_to_uvchr(p, p_end - p, &c_len,
8617 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8618 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8619 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8620 * UTF8_ALLOW_FFFF */
8621 if (c_len == (STRLEN)-1)
8622 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8623 if (c > 255 && OP(n) == ANYOFL && ! is_ANYOF_SYNTHETIC(n)) {
8624 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8628 /* If this character is potentially in the bitmap, check it */
8629 if (c < NUM_ANYOF_CODE_POINTS) {
8630 if (ANYOF_BITMAP_TEST(n, c))
8632 else if ((flags & ANYOF_MATCHES_ALL_NON_UTF8_NON_ASCII)
8638 else if (flags & ANYOF_LOCALE_FLAGS) {
8639 if ((flags & ANYOF_LOC_FOLD)
8641 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
8645 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
8649 /* The data structure is arranged so bits 0, 2, 4, ... are set
8650 * if the class includes the Posix character class given by
8651 * bit/2; and 1, 3, 5, ... are set if the class includes the
8652 * complemented Posix class given by int(bit/2). So we loop
8653 * through the bits, each time changing whether we complement
8654 * the result or not. Suppose for the sake of illustration
8655 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
8656 * is set, it means there is a match for this ANYOF node if the
8657 * character is in the class given by the expression (0 / 2 = 0
8658 * = \w). If it is in that class, isFOO_lc() will return 1,
8659 * and since 'to_complement' is 0, the result will stay TRUE,
8660 * and we exit the loop. Suppose instead that bit 0 is 0, but
8661 * bit 1 is 1. That means there is a match if the character
8662 * matches \W. We won't bother to call isFOO_lc() on bit 0,
8663 * but will on bit 1. On the second iteration 'to_complement'
8664 * will be 1, so the exclusive or will reverse things, so we
8665 * are testing for \W. On the third iteration, 'to_complement'
8666 * will be 0, and we would be testing for \s; the fourth
8667 * iteration would test for \S, etc.
8669 * Note that this code assumes that all the classes are closed
8670 * under folding. For example, if a character matches \w, then
8671 * its fold does too; and vice versa. This should be true for
8672 * any well-behaved locale for all the currently defined Posix
8673 * classes, except for :lower: and :upper:, which are handled
8674 * by the pseudo-class :cased: which matches if either of the
8675 * other two does. To get rid of this assumption, an outer
8676 * loop could be used below to iterate over both the source
8677 * character, and its fold (if different) */
8680 int to_complement = 0;
8682 while (count < ANYOF_MAX) {
8683 if (ANYOF_POSIXL_TEST(n, count)
8684 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
8697 /* If the bitmap didn't (or couldn't) match, and something outside the
8698 * bitmap could match, try that. */
8700 if (c >= NUM_ANYOF_CODE_POINTS
8701 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
8703 match = TRUE; /* Everything above the bitmap matches */
8705 else if ((flags & ANYOF_HAS_NONBITMAP_NON_UTF8_MATCHES)
8706 || (utf8_target && (flags & ANYOF_HAS_UTF8_NONBITMAP_MATCHES))
8707 || ((flags & ANYOF_LOC_FOLD)
8708 && IN_UTF8_CTYPE_LOCALE
8709 && ARG(n) != ANYOF_ONLY_HAS_BITMAP))
8711 SV* only_utf8_locale = NULL;
8712 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
8713 &only_utf8_locale, NULL);
8719 } else { /* Convert to utf8 */
8720 utf8_p = utf8_buffer;
8721 append_utf8_from_native_byte(*p, &utf8_p);
8722 utf8_p = utf8_buffer;
8725 if (swash_fetch(sw, utf8_p, TRUE)) {
8729 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
8730 match = _invlist_contains_cp(only_utf8_locale, c);
8734 if (UNICODE_IS_SUPER(c)
8735 && (flags & ANYOF_WARN_SUPER)
8736 && ckWARN_d(WARN_NON_UNICODE))
8738 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
8739 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
8743 #if ANYOF_INVERT != 1
8744 /* Depending on compiler optimization cBOOL takes time, so if don't have to
8746 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
8749 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
8750 return (flags & ANYOF_INVERT) ^ match;
8754 S_reghop3(U8 *s, SSize_t off, const U8* lim)
8756 /* return the position 'off' UTF-8 characters away from 's', forward if
8757 * 'off' >= 0, backwards if negative. But don't go outside of position
8758 * 'lim', which better be < s if off < 0 */
8760 PERL_ARGS_ASSERT_REGHOP3;
8763 while (off-- && s < lim) {
8764 /* XXX could check well-formedness here */
8769 while (off++ && s > lim) {
8771 if (UTF8_IS_CONTINUED(*s)) {
8772 while (s > lim && UTF8_IS_CONTINUATION(*s))
8775 /* XXX could check well-formedness here */
8782 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
8784 PERL_ARGS_ASSERT_REGHOP4;
8787 while (off-- && s < rlim) {
8788 /* XXX could check well-formedness here */
8793 while (off++ && s > llim) {
8795 if (UTF8_IS_CONTINUED(*s)) {
8796 while (s > llim && UTF8_IS_CONTINUATION(*s))
8799 /* XXX could check well-formedness here */
8805 /* like reghop3, but returns NULL on overrun, rather than returning last
8809 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
8811 PERL_ARGS_ASSERT_REGHOPMAYBE3;
8814 while (off-- && s < lim) {
8815 /* XXX could check well-formedness here */
8822 while (off++ && s > lim) {
8824 if (UTF8_IS_CONTINUED(*s)) {
8825 while (s > lim && UTF8_IS_CONTINUATION(*s))
8828 /* XXX could check well-formedness here */
8837 /* when executing a regex that may have (?{}), extra stuff needs setting
8838 up that will be visible to the called code, even before the current
8839 match has finished. In particular:
8841 * $_ is localised to the SV currently being matched;
8842 * pos($_) is created if necessary, ready to be updated on each call-out
8844 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
8845 isn't set until the current pattern is successfully finished), so that
8846 $1 etc of the match-so-far can be seen;
8847 * save the old values of subbeg etc of the current regex, and set then
8848 to the current string (again, this is normally only done at the end
8853 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
8856 regexp *const rex = ReANY(reginfo->prog);
8857 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
8859 eval_state->rex = rex;
8862 /* Make $_ available to executed code. */
8863 if (reginfo->sv != DEFSV) {
8865 DEFSV_set(reginfo->sv);
8868 if (!(mg = mg_find_mglob(reginfo->sv))) {
8869 /* prepare for quick setting of pos */
8870 mg = sv_magicext_mglob(reginfo->sv);
8873 eval_state->pos_magic = mg;
8874 eval_state->pos = mg->mg_len;
8875 eval_state->pos_flags = mg->mg_flags;
8878 eval_state->pos_magic = NULL;
8880 if (!PL_reg_curpm) {
8881 /* PL_reg_curpm is a fake PMOP that we can attach the current
8882 * regex to and point PL_curpm at, so that $1 et al are visible
8883 * within a /(?{})/. It's just allocated once per interpreter the
8884 * first time its needed */
8885 Newxz(PL_reg_curpm, 1, PMOP);
8888 SV* const repointer = &PL_sv_undef;
8889 /* this regexp is also owned by the new PL_reg_curpm, which
8890 will try to free it. */
8891 av_push(PL_regex_padav, repointer);
8892 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
8893 PL_regex_pad = AvARRAY(PL_regex_padav);
8897 SET_reg_curpm(reginfo->prog);
8898 eval_state->curpm = PL_curpm;
8899 PL_curpm = PL_reg_curpm;
8900 if (RXp_MATCH_COPIED(rex)) {
8901 /* Here is a serious problem: we cannot rewrite subbeg,
8902 since it may be needed if this match fails. Thus
8903 $` inside (?{}) could fail... */
8904 eval_state->subbeg = rex->subbeg;
8905 eval_state->sublen = rex->sublen;
8906 eval_state->suboffset = rex->suboffset;
8907 eval_state->subcoffset = rex->subcoffset;
8909 eval_state->saved_copy = rex->saved_copy;
8911 RXp_MATCH_COPIED_off(rex);
8914 eval_state->subbeg = NULL;
8915 rex->subbeg = (char *)reginfo->strbeg;
8917 rex->subcoffset = 0;
8918 rex->sublen = reginfo->strend - reginfo->strbeg;
8922 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
8925 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
8927 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
8928 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
8931 Safefree(aux->poscache);
8935 /* undo the effects of S_setup_eval_state() */
8937 if (eval_state->subbeg) {
8938 regexp * const rex = eval_state->rex;
8939 rex->subbeg = eval_state->subbeg;
8940 rex->sublen = eval_state->sublen;
8941 rex->suboffset = eval_state->suboffset;
8942 rex->subcoffset = eval_state->subcoffset;
8944 rex->saved_copy = eval_state->saved_copy;
8946 RXp_MATCH_COPIED_on(rex);
8948 if (eval_state->pos_magic)
8950 eval_state->pos_magic->mg_len = eval_state->pos;
8951 eval_state->pos_magic->mg_flags =
8952 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
8953 | (eval_state->pos_flags & MGf_BYTES);
8956 PL_curpm = eval_state->curpm;
8959 PL_regmatch_state = aux->old_regmatch_state;
8960 PL_regmatch_slab = aux->old_regmatch_slab;
8962 /* free all slabs above current one - this must be the last action
8963 * of this function, as aux and eval_state are allocated within
8964 * slabs and may be freed here */
8966 s = PL_regmatch_slab->next;
8968 PL_regmatch_slab->next = NULL;
8970 regmatch_slab * const osl = s;
8979 S_to_utf8_substr(pTHX_ regexp *prog)
8981 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8982 * on the converted value */
8986 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8989 if (prog->substrs->data[i].substr
8990 && !prog->substrs->data[i].utf8_substr) {
8991 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8992 prog->substrs->data[i].utf8_substr = sv;
8993 sv_utf8_upgrade(sv);
8994 if (SvVALID(prog->substrs->data[i].substr)) {
8995 if (SvTAIL(prog->substrs->data[i].substr)) {
8996 /* Trim the trailing \n that fbm_compile added last
8998 SvCUR_set(sv, SvCUR(sv) - 1);
8999 /* Whilst this makes the SV technically "invalid" (as its
9000 buffer is no longer followed by "\0") when fbm_compile()
9001 adds the "\n" back, a "\0" is restored. */
9002 fbm_compile(sv, FBMcf_TAIL);
9006 if (prog->substrs->data[i].substr == prog->check_substr)
9007 prog->check_utf8 = sv;
9013 S_to_byte_substr(pTHX_ regexp *prog)
9015 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9016 * on the converted value; returns FALSE if can't be converted. */
9020 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9023 if (prog->substrs->data[i].utf8_substr
9024 && !prog->substrs->data[i].substr) {
9025 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9026 if (! sv_utf8_downgrade(sv, TRUE)) {
9029 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9030 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9031 /* Trim the trailing \n that fbm_compile added last
9033 SvCUR_set(sv, SvCUR(sv) - 1);
9034 fbm_compile(sv, FBMcf_TAIL);
9038 prog->substrs->data[i].substr = sv;
9039 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9040 prog->check_substr = sv;
9048 * ex: set ts=8 sts=4 sw=4 et: