5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
89 static const char utf8_locale_required[] =
90 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
93 /* At least one required character in the target string is expressible only in
95 static const char* const non_utf8_target_but_utf8_required
96 = "Can't match, because target string needs to be in UTF-8\n";
99 /* Returns a boolean as to whether the input unsigned number is a power of 2
100 * (2**0, 2**1, etc). In other words if it has just a single bit set.
101 * If not, subtracting 1 would leave the uppermost bit set, so the & would
103 #define isPOWER_OF_2(n) ((n & (n-1)) == 0)
105 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
106 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
110 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
113 #define STATIC static
116 /* Valid only if 'c', the character being looke-up, is an invariant under
117 * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
118 * everything matchable is straight forward in the bitmap */
119 #define REGINCLASS(prog,p,c,u) (ANYOF_FLAGS(p) \
120 ? reginclass(prog,p,c,c+1,u) \
121 : ANYOF_BITMAP_TEST(p,*(c)))
127 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
129 #define HOPc(pos,off) \
130 (char *)(reginfo->is_utf8_target \
131 ? reghop3((U8*)pos, off, \
132 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
135 /* like HOPMAYBE3 but backwards. lim must be +ve. Returns NULL on overshoot */
136 #define HOPBACK3(pos, off, lim) \
137 (reginfo->is_utf8_target \
138 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(lim)) \
139 : (pos - off >= lim) \
143 #define HOPBACKc(pos, off) ((char*)HOPBACK3(pos, off, reginfo->strbeg))
145 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
146 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
148 /* lim must be +ve. Returns NULL on overshoot */
149 #define HOPMAYBE3(pos,off,lim) \
150 (reginfo->is_utf8_target \
151 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
152 : ((U8*)pos + off <= lim) \
156 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
157 * off must be >=0; args should be vars rather than expressions */
158 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
159 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
160 : (U8*)((pos + off) > lim ? lim : (pos + off)))
161 #define HOP3clim(pos,off,lim) ((char*)HOP3lim(pos,off,lim))
163 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
164 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
166 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
168 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
169 #define NEXTCHR_IS_EOS (nextchr < 0)
171 #define SET_nextchr \
172 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
174 #define SET_locinput(p) \
179 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
181 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
182 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
183 1, 0, invlist, &flags); \
188 /* If in debug mode, we test that a known character properly matches */
190 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
193 utf8_char_in_property) \
194 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
195 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
197 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
200 utf8_char_in_property) \
201 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
204 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
205 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
207 PL_XPosix_ptrs[_CC_WORDCHAR], \
208 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
210 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
211 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
213 /* for use after a quantifier and before an EXACT-like node -- japhy */
214 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
216 * NOTE that *nothing* that affects backtracking should be in here, specifically
217 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
218 * node that is in between two EXACT like nodes when ascertaining what the required
219 * "follow" character is. This should probably be moved to regex compile time
220 * although it may be done at run time beause of the REF possibility - more
221 * investigation required. -- demerphq
223 #define JUMPABLE(rn) ( \
225 (OP(rn) == CLOSE && \
226 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
228 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
229 OP(rn) == PLUS || OP(rn) == MINMOD || \
231 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
233 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
235 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
238 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
239 we don't need this definition. XXX These are now out-of-sync*/
240 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
241 #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 )
242 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
245 /* ... so we use this as its faster. */
246 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
247 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
248 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
249 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
254 Search for mandatory following text node; for lookahead, the text must
255 follow but for lookbehind (rn->flags != 0) we skip to the next step.
257 #define FIND_NEXT_IMPT(rn) STMT_START { \
258 while (JUMPABLE(rn)) { \
259 const OPCODE type = OP(rn); \
260 if (type == SUSPEND || PL_regkind[type] == CURLY) \
261 rn = NEXTOPER(NEXTOPER(rn)); \
262 else if (type == PLUS) \
264 else if (type == IFMATCH) \
265 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
266 else rn += NEXT_OFF(rn); \
270 #define SLAB_FIRST(s) (&(s)->states[0])
271 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
273 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
274 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
275 static regmatch_state * S_push_slab(pTHX);
277 #define REGCP_PAREN_ELEMS 3
278 #define REGCP_OTHER_ELEMS 3
279 #define REGCP_FRAME_ELEMS 1
280 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
281 * are needed for the regexp context stack bookkeeping. */
284 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
286 const int retval = PL_savestack_ix;
287 const int paren_elems_to_push =
288 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
289 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
290 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
292 GET_RE_DEBUG_FLAGS_DECL;
294 PERL_ARGS_ASSERT_REGCPPUSH;
296 if (paren_elems_to_push < 0)
297 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
298 (int)paren_elems_to_push, (int)maxopenparen,
299 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
301 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
302 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
303 " out of range (%lu-%ld)",
305 (unsigned long)maxopenparen,
308 SSGROW(total_elems + REGCP_FRAME_ELEMS);
311 if ((int)maxopenparen > (int)parenfloor)
312 Perl_re_exec_indentf( aTHX_
313 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
319 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
320 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
321 SSPUSHIV(rex->offs[p].end);
322 SSPUSHIV(rex->offs[p].start);
323 SSPUSHINT(rex->offs[p].start_tmp);
324 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
325 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
328 (IV)rex->offs[p].start,
329 (IV)rex->offs[p].start_tmp,
333 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
334 SSPUSHINT(maxopenparen);
335 SSPUSHINT(rex->lastparen);
336 SSPUSHINT(rex->lastcloseparen);
337 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
342 /* These are needed since we do not localize EVAL nodes: */
343 #define REGCP_SET(cp) \
345 Perl_re_exec_indentf( aTHX_ \
346 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
347 depth, (IV)PL_savestack_ix \
352 #define REGCP_UNWIND(cp) \
354 if (cp != PL_savestack_ix) \
355 Perl_re_exec_indentf( aTHX_ \
356 "Clearing an EVAL scope, savestack=%" \
357 IVdf "..%" IVdf "\n", \
358 depth, (IV)(cp), (IV)PL_savestack_ix \
363 #define UNWIND_PAREN(lp, lcp) \
364 for (n = rex->lastparen; n > lp; n--) \
365 rex->offs[n].end = -1; \
366 rex->lastparen = n; \
367 rex->lastcloseparen = lcp;
371 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
375 GET_RE_DEBUG_FLAGS_DECL;
377 PERL_ARGS_ASSERT_REGCPPOP;
379 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
381 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
382 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
383 rex->lastcloseparen = SSPOPINT;
384 rex->lastparen = SSPOPINT;
385 *maxopenparen_p = SSPOPINT;
387 i -= REGCP_OTHER_ELEMS;
388 /* Now restore the parentheses context. */
390 if (i || rex->lastparen + 1 <= rex->nparens)
391 Perl_re_exec_indentf( aTHX_
392 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
398 paren = *maxopenparen_p;
399 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
401 rex->offs[paren].start_tmp = SSPOPINT;
402 rex->offs[paren].start = SSPOPIV;
404 if (paren <= rex->lastparen)
405 rex->offs[paren].end = tmps;
406 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
407 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
410 (IV)rex->offs[paren].start,
411 (IV)rex->offs[paren].start_tmp,
412 (IV)rex->offs[paren].end,
413 (paren > rex->lastparen ? "(skipped)" : ""));
418 /* It would seem that the similar code in regtry()
419 * already takes care of this, and in fact it is in
420 * a better location to since this code can #if 0-ed out
421 * but the code in regtry() is needed or otherwise tests
422 * requiring null fields (pat.t#187 and split.t#{13,14}
423 * (as of patchlevel 7877) will fail. Then again,
424 * this code seems to be necessary or otherwise
425 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
426 * --jhi updated by dapm */
427 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
428 if (i > *maxopenparen_p)
429 rex->offs[i].start = -1;
430 rex->offs[i].end = -1;
431 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
432 " \\%" UVuf ": %s ..-1 undeffing\n",
435 (i > *maxopenparen_p) ? "-1" : " "
441 /* restore the parens and associated vars at savestack position ix,
442 * but without popping the stack */
445 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
447 I32 tmpix = PL_savestack_ix;
448 PERL_ARGS_ASSERT_REGCP_RESTORE;
450 PL_savestack_ix = ix;
451 regcppop(rex, maxopenparen_p);
452 PL_savestack_ix = tmpix;
455 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
457 #ifndef PERL_IN_XSUB_RE
460 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
462 /* Returns a boolean as to whether or not 'character' is a member of the
463 * Posix character class given by 'classnum' that should be equivalent to a
464 * value in the typedef '_char_class_number'.
466 * Ideally this could be replaced by a just an array of function pointers
467 * to the C library functions that implement the macros this calls.
468 * However, to compile, the precise function signatures are required, and
469 * these may vary from platform to to platform. To avoid having to figure
470 * out what those all are on each platform, I (khw) am using this method,
471 * which adds an extra layer of function call overhead (unless the C
472 * optimizer strips it away). But we don't particularly care about
473 * performance with locales anyway. */
475 switch ((_char_class_number) classnum) {
476 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
477 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
478 case _CC_ENUM_ASCII: return isASCII_LC(character);
479 case _CC_ENUM_BLANK: return isBLANK_LC(character);
480 case _CC_ENUM_CASED: return isLOWER_LC(character)
481 || isUPPER_LC(character);
482 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
483 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
484 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
485 case _CC_ENUM_LOWER: return isLOWER_LC(character);
486 case _CC_ENUM_PRINT: return isPRINT_LC(character);
487 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
488 case _CC_ENUM_SPACE: return isSPACE_LC(character);
489 case _CC_ENUM_UPPER: return isUPPER_LC(character);
490 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
491 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
492 default: /* VERTSPACE should never occur in locales */
493 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
496 NOT_REACHED; /* NOTREACHED */
503 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
505 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
506 * 'character' is a member of the Posix character class given by 'classnum'
507 * that should be equivalent to a value in the typedef
508 * '_char_class_number'.
510 * This just calls isFOO_lc on the code point for the character if it is in
511 * the range 0-255. Outside that range, all characters use Unicode
512 * rules, ignoring any locale. So use the Unicode function if this class
513 * requires a swash, and use the Unicode macro otherwise. */
515 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
517 if (UTF8_IS_INVARIANT(*character)) {
518 return isFOO_lc(classnum, *character);
520 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
521 return isFOO_lc(classnum,
522 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
525 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
527 if (classnum < _FIRST_NON_SWASH_CC) {
529 /* Initialize the swash unless done already */
530 if (! PL_utf8_swash_ptrs[classnum]) {
531 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
532 PL_utf8_swash_ptrs[classnum] =
533 _core_swash_init("utf8",
536 PL_XPosix_ptrs[classnum], &flags);
539 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
541 TRUE /* is UTF */ ));
544 switch ((_char_class_number) classnum) {
545 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
546 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
547 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
548 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
552 return FALSE; /* Things like CNTRL are always below 256 */
556 S_find_next_ascii(char * s, const char * send, const bool utf8_target)
558 /* Returns the position of the first ASCII byte in the sequence between 's'
559 * and 'send-1' inclusive; returns 'send' if none found */
561 PERL_ARGS_ASSERT_FIND_NEXT_ASCII;
565 if ((STRLEN) (send - s) >= PERL_WORDSIZE
567 /* This term is wordsize if subword; 0 if not */
568 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
571 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
574 /* Process per-byte until reach word boundary. XXX This loop could be
575 * eliminated if we knew that this platform had fast unaligned reads */
576 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
580 s++; /* khw didn't bother creating a separate loop for
584 /* Here, we know we have at least one full word to process. Process
585 * per-word as long as we have at least a full word left */
587 PERL_UINTMAX_T complemented = ~ * (PERL_UINTMAX_T *) s;
588 if (complemented & PERL_VARIANTS_WORD_MASK) {
590 #if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678 \
591 || BYTEORDER == 0x4321 || BYTEORDER == 0x87654321
593 s += _variant_byte_number(complemented);
596 #else /* If weird byte order, drop into next loop to do byte-at-a-time
605 } while (s + PERL_WORDSIZE <= send);
610 /* Process per-character */
632 S_find_next_non_ascii(char * s, const char * send, const bool utf8_target)
634 /* Returns the position of the first non-ASCII byte in the sequence between
635 * 's' and 'send-1' inclusive; returns 'send' if none found */
639 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
643 if ( ! isASCII(*s)) {
651 if ( ! isASCII(*s)) {
662 const U8 * next_non_ascii = NULL;
664 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
665 PERL_UNUSED_ARG(utf8_target);
667 /* On ASCII platforms invariants and ASCII are identical, so if the string
668 * is entirely invariants, there is no non-ASCII character */
669 return (is_utf8_invariant_string_loc((U8 *) s,
673 : (char *) next_non_ascii;
680 * pregexec and friends
683 #ifndef PERL_IN_XSUB_RE
685 - pregexec - match a regexp against a string
688 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
689 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
690 /* stringarg: the point in the string at which to begin matching */
691 /* strend: pointer to null at end of string */
692 /* strbeg: real beginning of string */
693 /* minend: end of match must be >= minend bytes after stringarg. */
694 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
695 * itself is accessed via the pointers above */
696 /* nosave: For optimizations. */
698 PERL_ARGS_ASSERT_PREGEXEC;
701 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
702 nosave ? 0 : REXEC_COPY_STR);
708 /* re_intuit_start():
710 * Based on some optimiser hints, try to find the earliest position in the
711 * string where the regex could match.
713 * rx: the regex to match against
714 * sv: the SV being matched: only used for utf8 flag; the string
715 * itself is accessed via the pointers below. Note that on
716 * something like an overloaded SV, SvPOK(sv) may be false
717 * and the string pointers may point to something unrelated to
719 * strbeg: real beginning of string
720 * strpos: the point in the string at which to begin matching
721 * strend: pointer to the byte following the last char of the string
722 * flags currently unused; set to 0
723 * data: currently unused; set to NULL
725 * The basic idea of re_intuit_start() is to use some known information
726 * about the pattern, namely:
728 * a) the longest known anchored substring (i.e. one that's at a
729 * constant offset from the beginning of the pattern; but not
730 * necessarily at a fixed offset from the beginning of the
732 * b) the longest floating substring (i.e. one that's not at a constant
733 * offset from the beginning of the pattern);
734 * c) Whether the pattern is anchored to the string; either
735 * an absolute anchor: /^../, or anchored to \n: /^.../m,
736 * or anchored to pos(): /\G/;
737 * d) A start class: a real or synthetic character class which
738 * represents which characters are legal at the start of the pattern;
740 * to either quickly reject the match, or to find the earliest position
741 * within the string at which the pattern might match, thus avoiding
742 * running the full NFA engine at those earlier locations, only to
743 * eventually fail and retry further along.
745 * Returns NULL if the pattern can't match, or returns the address within
746 * the string which is the earliest place the match could occur.
748 * The longest of the anchored and floating substrings is called 'check'
749 * and is checked first. The other is called 'other' and is checked
750 * second. The 'other' substring may not be present. For example,
752 * /(abc|xyz)ABC\d{0,3}DEFG/
756 * check substr (float) = "DEFG", offset 6..9 chars
757 * other substr (anchored) = "ABC", offset 3..3 chars
760 * Be aware that during the course of this function, sometimes 'anchored'
761 * refers to a substring being anchored relative to the start of the
762 * pattern, and sometimes to the pattern itself being anchored relative to
763 * the string. For example:
765 * /\dabc/: "abc" is anchored to the pattern;
766 * /^\dabc/: "abc" is anchored to the pattern and the string;
767 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
768 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
769 * but the pattern is anchored to the string.
773 Perl_re_intuit_start(pTHX_
776 const char * const strbeg,
780 re_scream_pos_data *data)
782 struct regexp *const prog = ReANY(rx);
783 SSize_t start_shift = prog->check_offset_min;
784 /* Should be nonnegative! */
785 SSize_t end_shift = 0;
786 /* current lowest pos in string where the regex can start matching */
787 char *rx_origin = strpos;
789 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
790 U8 other_ix = 1 - prog->substrs->check_ix;
792 char *other_last = strpos;/* latest pos 'other' substr already checked to */
793 char *check_at = NULL; /* check substr found at this pos */
794 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
795 RXi_GET_DECL(prog,progi);
796 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
797 regmatch_info *const reginfo = ®info_buf;
798 GET_RE_DEBUG_FLAGS_DECL;
800 PERL_ARGS_ASSERT_RE_INTUIT_START;
801 PERL_UNUSED_ARG(flags);
802 PERL_UNUSED_ARG(data);
804 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
805 "Intuit: trying to determine minimum start position...\n"));
807 /* for now, assume that all substr offsets are positive. If at some point
808 * in the future someone wants to do clever things with lookbehind and
809 * -ve offsets, they'll need to fix up any code in this function
810 * which uses these offsets. See the thread beginning
811 * <20140113145929.GF27210@iabyn.com>
813 assert(prog->substrs->data[0].min_offset >= 0);
814 assert(prog->substrs->data[0].max_offset >= 0);
815 assert(prog->substrs->data[1].min_offset >= 0);
816 assert(prog->substrs->data[1].max_offset >= 0);
817 assert(prog->substrs->data[2].min_offset >= 0);
818 assert(prog->substrs->data[2].max_offset >= 0);
820 /* for now, assume that if both present, that the floating substring
821 * doesn't start before the anchored substring.
822 * If you break this assumption (e.g. doing better optimisations
823 * with lookahead/behind), then you'll need to audit the code in this
824 * function carefully first
827 ! ( (prog->anchored_utf8 || prog->anchored_substr)
828 && (prog->float_utf8 || prog->float_substr))
829 || (prog->float_min_offset >= prog->anchored_offset));
831 /* byte rather than char calculation for efficiency. It fails
832 * to quickly reject some cases that can't match, but will reject
833 * them later after doing full char arithmetic */
834 if (prog->minlen > strend - strpos) {
835 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
836 " String too short...\n"));
840 RXp_MATCH_UTF8_set(prog, utf8_target);
841 reginfo->is_utf8_target = cBOOL(utf8_target);
842 reginfo->info_aux = NULL;
843 reginfo->strbeg = strbeg;
844 reginfo->strend = strend;
845 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
847 /* not actually used within intuit, but zero for safety anyway */
848 reginfo->poscache_maxiter = 0;
851 if ((!prog->anchored_utf8 && prog->anchored_substr)
852 || (!prog->float_utf8 && prog->float_substr))
853 to_utf8_substr(prog);
854 check = prog->check_utf8;
856 if (!prog->check_substr && prog->check_utf8) {
857 if (! to_byte_substr(prog)) {
858 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
861 check = prog->check_substr;
864 /* dump the various substring data */
865 DEBUG_OPTIMISE_MORE_r({
867 for (i=0; i<=2; i++) {
868 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
869 : prog->substrs->data[i].substr);
873 Perl_re_printf( aTHX_
874 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
875 " useful=%" IVdf " utf8=%d [%s]\n",
877 (IV)prog->substrs->data[i].min_offset,
878 (IV)prog->substrs->data[i].max_offset,
879 (IV)prog->substrs->data[i].end_shift,
886 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
888 /* ml_anch: check after \n?
890 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
891 * with /.*.../, these flags will have been added by the
893 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
894 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
896 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
897 && !(prog->intflags & PREGf_IMPLICIT);
899 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
900 /* we are only allowed to match at BOS or \G */
902 /* trivially reject if there's a BOS anchor and we're not at BOS.
904 * Note that we don't try to do a similar quick reject for
905 * \G, since generally the caller will have calculated strpos
906 * based on pos() and gofs, so the string is already correctly
907 * anchored by definition; and handling the exceptions would
908 * be too fiddly (e.g. REXEC_IGNOREPOS).
910 if ( strpos != strbeg
911 && (prog->intflags & PREGf_ANCH_SBOL))
913 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
914 " Not at start...\n"));
918 /* in the presence of an anchor, the anchored (relative to the
919 * start of the regex) substr must also be anchored relative
920 * to strpos. So quickly reject if substr isn't found there.
921 * This works for \G too, because the caller will already have
922 * subtracted gofs from pos, and gofs is the offset from the
923 * \G to the start of the regex. For example, in /.abc\Gdef/,
924 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
925 * caller will have set strpos=pos()-4; we look for the substr
926 * at position pos()-4+1, which lines up with the "a" */
928 if (prog->check_offset_min == prog->check_offset_max) {
929 /* Substring at constant offset from beg-of-str... */
930 SSize_t slen = SvCUR(check);
931 char *s = HOP3c(strpos, prog->check_offset_min, strend);
933 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
934 " Looking for check substr at fixed offset %" IVdf "...\n",
935 (IV)prog->check_offset_min));
938 /* In this case, the regex is anchored at the end too.
939 * Unless it's a multiline match, the lengths must match
940 * exactly, give or take a \n. NB: slen >= 1 since
941 * the last char of check is \n */
943 && ( strend - s > slen
944 || strend - s < slen - 1
945 || (strend - s == slen && strend[-1] != '\n')))
947 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
948 " String too long...\n"));
951 /* Now should match s[0..slen-2] */
954 if (slen && (strend - s < slen
955 || *SvPVX_const(check) != *s
956 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
958 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
959 " String not equal...\n"));
964 goto success_at_start;
969 end_shift = prog->check_end_shift;
971 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
973 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
974 (IV)end_shift, RX_PRECOMP(rx));
979 /* This is the (re)entry point of the main loop in this function.
980 * The goal of this loop is to:
981 * 1) find the "check" substring in the region rx_origin..strend
982 * (adjusted by start_shift / end_shift). If not found, reject
984 * 2) If it exists, look for the "other" substr too if defined; for
985 * example, if the check substr maps to the anchored substr, then
986 * check the floating substr, and vice-versa. If not found, go
987 * back to (1) with rx_origin suitably incremented.
988 * 3) If we find an rx_origin position that doesn't contradict
989 * either of the substrings, then check the possible additional
990 * constraints on rx_origin of /^.../m or a known start class.
991 * If these fail, then depending on which constraints fail, jump
992 * back to here, or to various other re-entry points further along
993 * that skip some of the first steps.
994 * 4) If we pass all those tests, update the BmUSEFUL() count on the
995 * substring. If the start position was determined to be at the
996 * beginning of the string - so, not rejected, but not optimised,
997 * since we have to run regmatch from position 0 - decrement the
998 * BmUSEFUL() count. Otherwise increment it.
1002 /* first, look for the 'check' substring */
1008 DEBUG_OPTIMISE_MORE_r({
1009 Perl_re_printf( aTHX_
1010 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
1011 " Start shift: %" IVdf " End shift %" IVdf
1012 " Real end Shift: %" IVdf "\n",
1013 (IV)(rx_origin - strbeg),
1014 (IV)prog->check_offset_min,
1017 (IV)prog->check_end_shift);
1020 end_point = HOPBACK3(strend, end_shift, rx_origin);
1023 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
1028 /* If the regex is absolutely anchored to either the start of the
1029 * string (SBOL) or to pos() (ANCH_GPOS), then
1030 * check_offset_max represents an upper bound on the string where
1031 * the substr could start. For the ANCH_GPOS case, we assume that
1032 * the caller of intuit will have already set strpos to
1033 * pos()-gofs, so in this case strpos + offset_max will still be
1034 * an upper bound on the substr.
1037 && prog->intflags & PREGf_ANCH
1038 && prog->check_offset_max != SSize_t_MAX)
1040 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
1041 const char * const anchor =
1042 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
1043 SSize_t targ_len = (char*)end_point - anchor;
1045 if (check_len > targ_len) {
1046 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1047 "Anchored string too short...\n"));
1051 /* do a bytes rather than chars comparison. It's conservative;
1052 * so it skips doing the HOP if the result can't possibly end
1053 * up earlier than the old value of end_point.
1055 assert(anchor + check_len <= (char *)end_point);
1056 if (prog->check_offset_max + check_len < targ_len) {
1057 end_point = HOP3lim((U8*)anchor,
1058 prog->check_offset_max,
1059 end_point - check_len
1065 check_at = fbm_instr( start_point, end_point,
1066 check, multiline ? FBMrf_MULTILINE : 0);
1068 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1069 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1070 (IV)((char*)start_point - strbeg),
1071 (IV)((char*)end_point - strbeg),
1072 (IV)(check_at ? check_at - strbeg : -1)
1075 /* Update the count-of-usability, remove useless subpatterns,
1079 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1080 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
1081 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
1082 (check_at ? "Found" : "Did not find"),
1083 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
1084 ? "anchored" : "floating"),
1087 (check_at ? " at offset " : "...\n") );
1092 /* set rx_origin to the minimum position where the regex could start
1093 * matching, given the constraint of the just-matched check substring.
1094 * But don't set it lower than previously.
1097 if (check_at - rx_origin > prog->check_offset_max)
1098 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
1099 /* Finish the diagnostic message */
1100 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1101 "%ld (rx_origin now %" IVdf ")...\n",
1102 (long)(check_at - strbeg),
1103 (IV)(rx_origin - strbeg)
1108 /* now look for the 'other' substring if defined */
1110 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
1111 : prog->substrs->data[other_ix].substr)
1113 /* Take into account the "other" substring. */
1117 struct reg_substr_datum *other;
1120 other = &prog->substrs->data[other_ix];
1122 /* if "other" is anchored:
1123 * we've previously found a floating substr starting at check_at.
1124 * This means that the regex origin must lie somewhere
1125 * between min (rx_origin): HOP3(check_at, -check_offset_max)
1126 * and max: HOP3(check_at, -check_offset_min)
1127 * (except that min will be >= strpos)
1128 * So the fixed substr must lie somewhere between
1129 * HOP3(min, anchored_offset)
1130 * HOP3(max, anchored_offset) + SvCUR(substr)
1133 /* if "other" is floating
1134 * Calculate last1, the absolute latest point where the
1135 * floating substr could start in the string, ignoring any
1136 * constraints from the earlier fixed match. It is calculated
1139 * strend - prog->minlen (in chars) is the absolute latest
1140 * position within the string where the origin of the regex
1141 * could appear. The latest start point for the floating
1142 * substr is float_min_offset(*) on from the start of the
1143 * regex. last1 simply combines thee two offsets.
1145 * (*) You might think the latest start point should be
1146 * float_max_offset from the regex origin, and technically
1147 * you'd be correct. However, consider
1149 * Here, float min, max are 3,5 and minlen is 7.
1150 * This can match either
1154 * In the first case, the regex matches minlen chars; in the
1155 * second, minlen+1, in the third, minlen+2.
1156 * In the first case, the floating offset is 3 (which equals
1157 * float_min), in the second, 4, and in the third, 5 (which
1158 * equals float_max). In all cases, the floating string bcd
1159 * can never start more than 4 chars from the end of the
1160 * string, which equals minlen - float_min. As the substring
1161 * starts to match more than float_min from the start of the
1162 * regex, it makes the regex match more than minlen chars,
1163 * and the two cancel each other out. So we can always use
1164 * float_min - minlen, rather than float_max - minlen for the
1165 * latest position in the string.
1167 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1168 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1171 assert(prog->minlen >= other->min_offset);
1172 last1 = HOP3c(strend,
1173 other->min_offset - prog->minlen, strbeg);
1175 if (other_ix) {/* i.e. if (other-is-float) */
1176 /* last is the latest point where the floating substr could
1177 * start, *given* any constraints from the earlier fixed
1178 * match. This constraint is that the floating string starts
1179 * <= float_max_offset chars from the regex origin (rx_origin).
1180 * If this value is less than last1, use it instead.
1182 assert(rx_origin <= last1);
1184 /* this condition handles the offset==infinity case, and
1185 * is a short-cut otherwise. Although it's comparing a
1186 * byte offset to a char length, it does so in a safe way,
1187 * since 1 char always occupies 1 or more bytes,
1188 * so if a string range is (last1 - rx_origin) bytes,
1189 * it will be less than or equal to (last1 - rx_origin)
1190 * chars; meaning it errs towards doing the accurate HOP3
1191 * rather than just using last1 as a short-cut */
1192 (last1 - rx_origin) < other->max_offset
1194 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1197 assert(strpos + start_shift <= check_at);
1198 last = HOP4c(check_at, other->min_offset - start_shift,
1202 s = HOP3c(rx_origin, other->min_offset, strend);
1203 if (s < other_last) /* These positions already checked */
1206 must = utf8_target ? other->utf8_substr : other->substr;
1207 assert(SvPOK(must));
1210 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1216 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1217 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1218 (IV)(from - strbeg),
1224 (unsigned char*)from,
1227 multiline ? FBMrf_MULTILINE : 0
1229 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1230 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1231 (IV)(from - strbeg),
1233 (IV)(s ? s - strbeg : -1)
1239 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1240 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1241 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1242 s ? "Found" : "Contradicts",
1243 other_ix ? "floating" : "anchored",
1244 quoted, RE_SV_TAIL(must));
1249 /* last1 is latest possible substr location. If we didn't
1250 * find it before there, we never will */
1251 if (last >= last1) {
1252 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1253 "; giving up...\n"));
1257 /* try to find the check substr again at a later
1258 * position. Maybe next time we'll find the "other" substr
1260 other_last = HOP3c(last, 1, strend) /* highest failure */;
1262 other_ix /* i.e. if other-is-float */
1263 ? HOP3c(rx_origin, 1, strend)
1264 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1265 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1266 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1267 (other_ix ? "floating" : "anchored"),
1268 (long)(HOP3c(check_at, 1, strend) - strbeg),
1269 (IV)(rx_origin - strbeg)
1274 if (other_ix) { /* if (other-is-float) */
1275 /* other_last is set to s, not s+1, since its possible for
1276 * a floating substr to fail first time, then succeed
1277 * second time at the same floating position; e.g.:
1278 * "-AB--AABZ" =~ /\wAB\d*Z/
1279 * The first time round, anchored and float match at
1280 * "-(AB)--AAB(Z)" then fail on the initial \w character
1281 * class. Second time round, they match at "-AB--A(AB)(Z)".
1286 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1287 other_last = HOP3c(s, 1, strend);
1289 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1290 " at offset %ld (rx_origin now %" IVdf ")...\n",
1292 (IV)(rx_origin - strbeg)
1298 DEBUG_OPTIMISE_MORE_r(
1299 Perl_re_printf( aTHX_
1300 " Check-only match: offset min:%" IVdf " max:%" IVdf
1301 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1302 " strend:%" IVdf "\n",
1303 (IV)prog->check_offset_min,
1304 (IV)prog->check_offset_max,
1305 (IV)(check_at-strbeg),
1306 (IV)(rx_origin-strbeg),
1307 (IV)(rx_origin-check_at),
1313 postprocess_substr_matches:
1315 /* handle the extra constraint of /^.../m if present */
1317 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1320 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1321 " looking for /^/m anchor"));
1323 /* we have failed the constraint of a \n before rx_origin.
1324 * Find the next \n, if any, even if it's beyond the current
1325 * anchored and/or floating substrings. Whether we should be
1326 * scanning ahead for the next \n or the next substr is debatable.
1327 * On the one hand you'd expect rare substrings to appear less
1328 * often than \n's. On the other hand, searching for \n means
1329 * we're effectively flipping between check_substr and "\n" on each
1330 * iteration as the current "rarest" string candidate, which
1331 * means for example that we'll quickly reject the whole string if
1332 * hasn't got a \n, rather than trying every substr position
1336 s = HOP3c(strend, - prog->minlen, strpos);
1337 if (s <= rx_origin ||
1338 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1340 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1341 " Did not find /%s^%s/m...\n",
1342 PL_colors[0], PL_colors[1]));
1346 /* earliest possible origin is 1 char after the \n.
1347 * (since *rx_origin == '\n', it's safe to ++ here rather than
1348 * HOP(rx_origin, 1)) */
1351 if (prog->substrs->check_ix == 0 /* check is anchored */
1352 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1354 /* Position contradicts check-string; either because
1355 * check was anchored (and thus has no wiggle room),
1356 * or check was float and rx_origin is above the float range */
1357 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1358 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1359 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1363 /* if we get here, the check substr must have been float,
1364 * is in range, and we may or may not have had an anchored
1365 * "other" substr which still contradicts */
1366 assert(prog->substrs->check_ix); /* check is float */
1368 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1369 /* whoops, the anchored "other" substr exists, so we still
1370 * contradict. On the other hand, the float "check" substr
1371 * didn't contradict, so just retry the anchored "other"
1373 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1374 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1375 PL_colors[0], PL_colors[1],
1376 (IV)(rx_origin - strbeg + prog->anchored_offset),
1377 (IV)(rx_origin - strbeg)
1379 goto do_other_substr;
1382 /* success: we don't contradict the found floating substring
1383 * (and there's no anchored substr). */
1384 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1385 " Found /%s^%s/m with rx_origin %ld...\n",
1386 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1389 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1390 " (multiline anchor test skipped)\n"));
1396 /* if we have a starting character class, then test that extra constraint.
1397 * (trie stclasses are too expensive to use here, we are better off to
1398 * leave it to regmatch itself) */
1400 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1401 const U8* const str = (U8*)STRING(progi->regstclass);
1403 /* XXX this value could be pre-computed */
1404 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1405 ? (reginfo->is_utf8_pat
1406 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1407 : STR_LEN(progi->regstclass))
1411 /* latest pos that a matching float substr constrains rx start to */
1412 char *rx_max_float = NULL;
1414 /* if the current rx_origin is anchored, either by satisfying an
1415 * anchored substring constraint, or a /^.../m constraint, then we
1416 * can reject the current origin if the start class isn't found
1417 * at the current position. If we have a float-only match, then
1418 * rx_origin is constrained to a range; so look for the start class
1419 * in that range. if neither, then look for the start class in the
1420 * whole rest of the string */
1422 /* XXX DAPM it's not clear what the minlen test is for, and why
1423 * it's not used in the floating case. Nothing in the test suite
1424 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1425 * Here are some old comments, which may or may not be correct:
1427 * minlen == 0 is possible if regstclass is \b or \B,
1428 * and the fixed substr is ''$.
1429 * Since minlen is already taken into account, rx_origin+1 is
1430 * before strend; accidentally, minlen >= 1 guaranties no false
1431 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1432 * 0) below assumes that regstclass does not come from lookahead...
1433 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1434 * This leaves EXACTF-ish only, which are dealt with in
1438 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1439 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1440 else if (prog->float_substr || prog->float_utf8) {
1441 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1442 endpos = HOP3clim(rx_max_float, cl_l, strend);
1447 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1448 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1449 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1450 (IV)start_shift, (IV)(check_at - strbeg),
1451 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1453 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1456 if (endpos == strend) {
1457 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1458 " Could not match STCLASS...\n") );
1461 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1462 " This position contradicts STCLASS...\n") );
1463 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1464 && !(prog->intflags & PREGf_IMPLICIT))
1467 /* Contradict one of substrings */
1468 if (prog->anchored_substr || prog->anchored_utf8) {
1469 if (prog->substrs->check_ix == 1) { /* check is float */
1470 /* Have both, check_string is floating */
1471 assert(rx_origin + start_shift <= check_at);
1472 if (rx_origin + start_shift != check_at) {
1473 /* not at latest position float substr could match:
1474 * Recheck anchored substring, but not floating.
1475 * The condition above is in bytes rather than
1476 * chars for efficiency. It's conservative, in
1477 * that it errs on the side of doing 'goto
1478 * do_other_substr'. In this case, at worst,
1479 * an extra anchored search may get done, but in
1480 * practice the extra fbm_instr() is likely to
1481 * get skipped anyway. */
1482 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1483 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1484 (long)(other_last - strbeg),
1485 (IV)(rx_origin - strbeg)
1487 goto do_other_substr;
1495 /* In the presence of ml_anch, we might be able to
1496 * find another \n without breaking the current float
1499 /* strictly speaking this should be HOP3c(..., 1, ...),
1500 * but since we goto a block of code that's going to
1501 * search for the next \n if any, its safe here */
1503 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1504 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1505 PL_colors[0], PL_colors[1],
1506 (long)(rx_origin - strbeg)) );
1507 goto postprocess_substr_matches;
1510 /* strictly speaking this can never be true; but might
1511 * be if we ever allow intuit without substrings */
1512 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1515 rx_origin = rx_max_float;
1518 /* at this point, any matching substrings have been
1519 * contradicted. Start again... */
1521 rx_origin = HOP3c(rx_origin, 1, strend);
1523 /* uses bytes rather than char calculations for efficiency.
1524 * It's conservative: it errs on the side of doing 'goto restart',
1525 * where there is code that does a proper char-based test */
1526 if (rx_origin + start_shift + end_shift > strend) {
1527 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1528 " Could not match STCLASS...\n") );
1531 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1532 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1533 (prog->substrs->check_ix ? "floating" : "anchored"),
1534 (long)(rx_origin + start_shift - strbeg),
1535 (IV)(rx_origin - strbeg)
1542 if (rx_origin != s) {
1543 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1544 " By STCLASS: moving %ld --> %ld\n",
1545 (long)(rx_origin - strbeg), (long)(s - strbeg))
1549 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1550 " Does not contradict STCLASS...\n");
1555 /* Decide whether using the substrings helped */
1557 if (rx_origin != strpos) {
1558 /* Fixed substring is found far enough so that the match
1559 cannot start at strpos. */
1561 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1562 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1565 /* The found rx_origin position does not prohibit matching at
1566 * strpos, so calling intuit didn't gain us anything. Decrement
1567 * the BmUSEFUL() count on the check substring, and if we reach
1569 if (!(prog->intflags & PREGf_NAUGHTY)
1571 prog->check_utf8 /* Could be deleted already */
1572 && --BmUSEFUL(prog->check_utf8) < 0
1573 && (prog->check_utf8 == prog->float_utf8)
1575 prog->check_substr /* Could be deleted already */
1576 && --BmUSEFUL(prog->check_substr) < 0
1577 && (prog->check_substr == prog->float_substr)
1580 /* If flags & SOMETHING - do not do it many times on the same match */
1581 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1582 /* XXX Does the destruction order has to change with utf8_target? */
1583 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1584 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1585 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1586 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1587 check = NULL; /* abort */
1588 /* XXXX This is a remnant of the old implementation. It
1589 looks wasteful, since now INTUIT can use many
1590 other heuristics. */
1591 prog->extflags &= ~RXf_USE_INTUIT;
1595 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1596 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1597 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1601 fail_finish: /* Substring not found */
1602 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1603 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1605 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1606 PL_colors[4], PL_colors[5]));
1611 #define DECL_TRIE_TYPE(scan) \
1612 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1613 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1614 trie_utf8l, trie_flu8 } \
1615 trie_type = ((scan->flags == EXACT) \
1616 ? (utf8_target ? trie_utf8 : trie_plain) \
1617 : (scan->flags == EXACTL) \
1618 ? (utf8_target ? trie_utf8l : trie_plain) \
1619 : (scan->flags == EXACTFA) \
1621 ? trie_utf8_exactfa_fold \
1622 : trie_latin_utf8_exactfa_fold) \
1623 : (scan->flags == EXACTFLU8 \
1627 : trie_latin_utf8_fold)))
1629 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1632 U8 flags = FOLD_FLAGS_FULL; \
1633 switch (trie_type) { \
1635 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1636 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1637 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1639 goto do_trie_utf8_fold; \
1640 case trie_utf8_exactfa_fold: \
1641 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1643 case trie_utf8_fold: \
1644 do_trie_utf8_fold: \
1645 if ( foldlen>0 ) { \
1646 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1651 len = UTF8SKIP(uc); \
1652 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc + len, foldbuf, &foldlen, \
1654 skiplen = UVCHR_SKIP( uvc ); \
1655 foldlen -= skiplen; \
1656 uscan = foldbuf + skiplen; \
1659 case trie_latin_utf8_exactfa_fold: \
1660 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1662 case trie_latin_utf8_fold: \
1663 if ( foldlen>0 ) { \
1664 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1670 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1671 skiplen = UVCHR_SKIP( uvc ); \
1672 foldlen -= skiplen; \
1673 uscan = foldbuf + skiplen; \
1677 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1678 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1679 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1683 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1690 charid = trie->charmap[ uvc ]; \
1694 if (widecharmap) { \
1695 SV** const svpp = hv_fetch(widecharmap, \
1696 (char*)&uvc, sizeof(UV), 0); \
1698 charid = (U16)SvIV(*svpp); \
1703 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1704 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1705 startpos, doutf8, depth)
1707 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1711 && (ln == 1 || folder(s, pat_string, ln)) \
1712 && (reginfo->intuit || regtry(reginfo, &s)) )\
1718 #define REXEC_FBC_UTF8_SCAN(CODE) \
1720 while (s < strend) { \
1726 #define REXEC_FBC_SCAN(CODE) \
1728 while (s < strend) { \
1734 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1735 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1737 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1746 #define REXEC_FBC_CLASS_SCAN(COND) \
1747 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1749 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1758 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1759 if (utf8_target) { \
1760 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1763 REXEC_FBC_CLASS_SCAN(COND); \
1766 /* The three macros below are slightly different versions of the same logic.
1768 * The first is for /a and /aa when the target string is UTF-8. This can only
1769 * match ascii, but it must advance based on UTF-8. The other two handle the
1770 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1771 * for the boundary (or non-boundary) between a word and non-word character.
1772 * The utf8 and non-utf8 cases have the same logic, but the details must be
1773 * different. Find the "wordness" of the character just prior to this one, and
1774 * compare it with the wordness of this one. If they differ, we have a
1775 * boundary. At the beginning of the string, pretend that the previous
1776 * character was a new-line.
1778 * All these macros uncleanly have side-effects with each other and outside
1779 * variables. So far it's been too much trouble to clean-up
1781 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1782 * a word character or not.
1783 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1785 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1787 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1788 * are looking for a boundary or for a non-boundary. If we are looking for a
1789 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1790 * see if this tentative match actually works, and if so, to quit the loop
1791 * here. And vice-versa if we are looking for a non-boundary.
1793 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1794 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1795 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1796 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1797 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1798 * complement. But in that branch we complement tmp, meaning that at the
1799 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1800 * which means at the top of the loop in the next iteration, it is
1801 * TEST_NON_UTF8(s-1) */
1802 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1803 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1804 tmp = TEST_NON_UTF8(tmp); \
1805 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1806 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1808 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1815 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1816 * TEST_UTF8 is a macro that for the same input code points returns identically
1817 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1818 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1819 if (s == reginfo->strbeg) { \
1822 else { /* Back-up to the start of the previous character */ \
1823 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1824 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1825 0, UTF8_ALLOW_DEFAULT); \
1827 tmp = TEST_UV(tmp); \
1828 LOAD_UTF8_CHARCLASS_ALNUM(); \
1829 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1830 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1839 /* Like the above two macros. UTF8_CODE is the complete code for handling
1840 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1842 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1843 if (utf8_target) { \
1846 else { /* Not utf8 */ \
1847 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1848 tmp = TEST_NON_UTF8(tmp); \
1849 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1850 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1859 /* Here, things have been set up by the previous code so that tmp is the \
1860 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1861 * utf8ness of the target). We also have to check if this matches against \
1862 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1863 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1865 if (tmp == ! TEST_NON_UTF8('\n')) { \
1872 /* This is the macro to use when we want to see if something that looks like it
1873 * could match, actually does, and if so exits the loop */
1874 #define REXEC_FBC_TRYIT \
1875 if ((reginfo->intuit || regtry(reginfo, &s))) \
1878 /* The only difference between the BOUND and NBOUND cases is that
1879 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1880 * NBOUND. This is accomplished by passing it as either the if or else clause,
1881 * with the other one being empty (PLACEHOLDER is defined as empty).
1883 * The TEST_FOO parameters are for operating on different forms of input, but
1884 * all should be ones that return identically for the same underlying code
1886 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1888 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1889 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1891 #define FBC_BOUND_A(TEST_NON_UTF8) \
1893 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1894 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1896 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1898 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1899 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1901 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1903 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1904 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1908 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1909 IV cp_out = Perl__invlist_search(invlist, cp_in);
1910 assert(cp_out >= 0);
1913 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1914 invmap[S_get_break_val_cp_checked(invlist, cp)]
1916 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1917 invmap[_invlist_search(invlist, cp)]
1920 /* Takes a pointer to an inversion list, a pointer to its corresponding
1921 * inversion map, and a code point, and returns the code point's value
1922 * according to the two arrays. It assumes that all code points have a value.
1923 * This is used as the base macro for macros for particular properties */
1924 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1925 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1927 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1928 * of a code point, returning the value for the first code point in the string.
1929 * And it takes the particular macro name that finds the desired value given a
1930 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1931 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1932 (__ASSERT_(pos < strend) \
1933 /* Note assumes is valid UTF-8 */ \
1934 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1936 /* Returns the GCB value for the input code point */
1937 #define getGCB_VAL_CP(cp) \
1938 _generic_GET_BREAK_VAL_CP( \
1943 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1944 * bounded by pos and strend */
1945 #define getGCB_VAL_UTF8(pos, strend) \
1946 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1948 /* Returns the LB value for the input code point */
1949 #define getLB_VAL_CP(cp) \
1950 _generic_GET_BREAK_VAL_CP( \
1955 /* Returns the LB value for the first code point in the UTF-8 encoded string
1956 * bounded by pos and strend */
1957 #define getLB_VAL_UTF8(pos, strend) \
1958 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1961 /* Returns the SB value for the input code point */
1962 #define getSB_VAL_CP(cp) \
1963 _generic_GET_BREAK_VAL_CP( \
1968 /* Returns the SB value for the first code point in the UTF-8 encoded string
1969 * bounded by pos and strend */
1970 #define getSB_VAL_UTF8(pos, strend) \
1971 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1973 /* Returns the WB value for the input code point */
1974 #define getWB_VAL_CP(cp) \
1975 _generic_GET_BREAK_VAL_CP( \
1980 /* Returns the WB value for the first code point in the UTF-8 encoded string
1981 * bounded by pos and strend */
1982 #define getWB_VAL_UTF8(pos, strend) \
1983 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1985 /* We know what class REx starts with. Try to find this position... */
1986 /* if reginfo->intuit, its a dryrun */
1987 /* annoyingly all the vars in this routine have different names from their counterparts
1988 in regmatch. /grrr */
1990 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1991 const char *strend, regmatch_info *reginfo)
1994 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1995 char *pat_string; /* The pattern's exactish string */
1996 char *pat_end; /* ptr to end char of pat_string */
1997 re_fold_t folder; /* Function for computing non-utf8 folds */
1998 const U8 *fold_array; /* array for folding ords < 256 */
2004 I32 tmp = 1; /* Scratch variable? */
2005 const bool utf8_target = reginfo->is_utf8_target;
2006 UV utf8_fold_flags = 0;
2007 const bool is_utf8_pat = reginfo->is_utf8_pat;
2008 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
2009 with a result inverts that result, as 0^1 =
2011 _char_class_number classnum;
2013 RXi_GET_DECL(prog,progi);
2015 PERL_ARGS_ASSERT_FIND_BYCLASS;
2017 /* We know what class it must start with. */
2020 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2022 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
2023 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
2030 REXEC_FBC_UTF8_CLASS_SCAN(
2031 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
2033 else if (ANYOF_FLAGS(c)) {
2034 REXEC_FBC_CLASS_SCAN(reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
2037 REXEC_FBC_CLASS_SCAN(ANYOF_BITMAP_TEST(c, *((U8*)s)));
2041 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
2042 assert(! is_utf8_pat);
2045 if (is_utf8_pat || utf8_target) {
2046 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2047 goto do_exactf_utf8;
2049 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
2050 folder = foldEQ_latin1; /* /a, except the sharp s one which */
2051 goto do_exactf_non_utf8; /* isn't dealt with by these */
2053 case EXACTF: /* This node only generated for non-utf8 patterns */
2054 assert(! is_utf8_pat);
2056 utf8_fold_flags = 0;
2057 goto do_exactf_utf8;
2059 fold_array = PL_fold;
2061 goto do_exactf_non_utf8;
2064 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2065 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
2066 utf8_fold_flags = FOLDEQ_LOCALE;
2067 goto do_exactf_utf8;
2069 fold_array = PL_fold_locale;
2070 folder = foldEQ_locale;
2071 goto do_exactf_non_utf8;
2075 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2077 goto do_exactf_utf8;
2080 if (! utf8_target) { /* All code points in this node require
2081 UTF-8 to express. */
2084 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
2085 | FOLDEQ_S2_FOLDS_SANE;
2086 goto do_exactf_utf8;
2089 if (is_utf8_pat || utf8_target) {
2090 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
2091 goto do_exactf_utf8;
2094 /* Any 'ss' in the pattern should have been replaced by regcomp,
2095 * so we don't have to worry here about this single special case
2096 * in the Latin1 range */
2097 fold_array = PL_fold_latin1;
2098 folder = foldEQ_latin1;
2102 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
2103 are no glitches with fold-length differences
2104 between the target string and pattern */
2106 /* The idea in the non-utf8 EXACTF* cases is to first find the
2107 * first character of the EXACTF* node and then, if necessary,
2108 * case-insensitively compare the full text of the node. c1 is the
2109 * first character. c2 is its fold. This logic will not work for
2110 * Unicode semantics and the german sharp ss, which hence should
2111 * not be compiled into a node that gets here. */
2112 pat_string = STRING(c);
2113 ln = STR_LEN(c); /* length to match in octets/bytes */
2115 /* We know that we have to match at least 'ln' bytes (which is the
2116 * same as characters, since not utf8). If we have to match 3
2117 * characters, and there are only 2 availabe, we know without
2118 * trying that it will fail; so don't start a match past the
2119 * required minimum number from the far end */
2120 e = HOP3c(strend, -((SSize_t)ln), s);
2125 c2 = fold_array[c1];
2126 if (c1 == c2) { /* If char and fold are the same */
2127 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
2130 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
2138 /* If one of the operands is in utf8, we can't use the simpler folding
2139 * above, due to the fact that many different characters can have the
2140 * same fold, or portion of a fold, or different- length fold */
2141 pat_string = STRING(c);
2142 ln = STR_LEN(c); /* length to match in octets/bytes */
2143 pat_end = pat_string + ln;
2144 lnc = is_utf8_pat /* length to match in characters */
2145 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2148 /* We have 'lnc' characters to match in the pattern, but because of
2149 * multi-character folding, each character in the target can match
2150 * up to 3 characters (Unicode guarantees it will never exceed
2151 * this) if it is utf8-encoded; and up to 2 if not (based on the
2152 * fact that the Latin 1 folds are already determined, and the
2153 * only multi-char fold in that range is the sharp-s folding to
2154 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2155 * string character. Adjust lnc accordingly, rounding up, so that
2156 * if we need to match at least 4+1/3 chars, that really is 5. */
2157 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2158 lnc = (lnc + expansion - 1) / expansion;
2160 /* As in the non-UTF8 case, if we have to match 3 characters, and
2161 * only 2 are left, it's guaranteed to fail, so don't start a
2162 * match that would require us to go beyond the end of the string
2164 e = HOP3c(strend, -((SSize_t)lnc), s);
2166 /* XXX Note that we could recalculate e to stop the loop earlier,
2167 * as the worst case expansion above will rarely be met, and as we
2168 * go along we would usually find that e moves further to the left.
2169 * This would happen only after we reached the point in the loop
2170 * where if there were no expansion we should fail. Unclear if
2171 * worth the expense */
2174 char *my_strend= (char *)strend;
2175 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2176 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2177 && (reginfo->intuit || regtry(reginfo, &s)) )
2181 s += (utf8_target) ? UTF8SKIP(s) : 1;
2187 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2188 if (FLAGS(c) != TRADITIONAL_BOUND) {
2189 if (! IN_UTF8_CTYPE_LOCALE) {
2190 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2191 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2196 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2200 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2201 if (FLAGS(c) != TRADITIONAL_BOUND) {
2202 if (! IN_UTF8_CTYPE_LOCALE) {
2203 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2204 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2209 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2212 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2214 assert(FLAGS(c) == TRADITIONAL_BOUND);
2216 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2219 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2221 assert(FLAGS(c) == TRADITIONAL_BOUND);
2223 FBC_BOUND_A(isWORDCHAR_A);
2226 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2228 assert(FLAGS(c) == TRADITIONAL_BOUND);
2230 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2233 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2235 assert(FLAGS(c) == TRADITIONAL_BOUND);
2237 FBC_NBOUND_A(isWORDCHAR_A);
2241 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2242 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2253 switch((bound_type) FLAGS(c)) {
2254 case TRADITIONAL_BOUND:
2255 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2258 if (s == reginfo->strbeg) {
2259 if (reginfo->intuit || regtry(reginfo, &s))
2264 /* Didn't match. Try at the next position (if there is one) */
2265 s += (utf8_target) ? UTF8SKIP(s) : 1;
2266 if (UNLIKELY(s >= reginfo->strend)) {
2272 GCB_enum before = getGCB_VAL_UTF8(
2274 (U8*)(reginfo->strbeg)),
2275 (U8*) reginfo->strend);
2276 while (s < strend) {
2277 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2278 (U8*) reginfo->strend);
2279 if ( (to_complement ^ isGCB(before,
2281 (U8*) reginfo->strbeg,
2284 && (reginfo->intuit || regtry(reginfo, &s)))
2292 else { /* Not utf8. Everything is a GCB except between CR and
2294 while (s < strend) {
2295 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2296 || UCHARAT(s) != '\n'))
2297 && (reginfo->intuit || regtry(reginfo, &s)))
2305 /* And, since this is a bound, it can match after the final
2306 * character in the string */
2307 if ((reginfo->intuit || regtry(reginfo, &s))) {
2313 if (s == reginfo->strbeg) {
2314 if (reginfo->intuit || regtry(reginfo, &s)) {
2317 s += (utf8_target) ? UTF8SKIP(s) : 1;
2318 if (UNLIKELY(s >= reginfo->strend)) {
2324 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2326 (U8*)(reginfo->strbeg)),
2327 (U8*) reginfo->strend);
2328 while (s < strend) {
2329 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2330 if (to_complement ^ isLB(before,
2332 (U8*) reginfo->strbeg,
2334 (U8*) reginfo->strend,
2336 && (reginfo->intuit || regtry(reginfo, &s)))
2344 else { /* Not utf8. */
2345 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2346 while (s < strend) {
2347 LB_enum after = getLB_VAL_CP((U8) *s);
2348 if (to_complement ^ isLB(before,
2350 (U8*) reginfo->strbeg,
2352 (U8*) reginfo->strend,
2354 && (reginfo->intuit || regtry(reginfo, &s)))
2363 if (reginfo->intuit || regtry(reginfo, &s)) {
2370 if (s == reginfo->strbeg) {
2371 if (reginfo->intuit || regtry(reginfo, &s)) {
2374 s += (utf8_target) ? UTF8SKIP(s) : 1;
2375 if (UNLIKELY(s >= reginfo->strend)) {
2381 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2383 (U8*)(reginfo->strbeg)),
2384 (U8*) reginfo->strend);
2385 while (s < strend) {
2386 SB_enum after = getSB_VAL_UTF8((U8*) s,
2387 (U8*) reginfo->strend);
2388 if ((to_complement ^ isSB(before,
2390 (U8*) reginfo->strbeg,
2392 (U8*) reginfo->strend,
2394 && (reginfo->intuit || regtry(reginfo, &s)))
2402 else { /* Not utf8. */
2403 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2404 while (s < strend) {
2405 SB_enum after = getSB_VAL_CP((U8) *s);
2406 if ((to_complement ^ isSB(before,
2408 (U8*) reginfo->strbeg,
2410 (U8*) reginfo->strend,
2412 && (reginfo->intuit || regtry(reginfo, &s)))
2421 /* Here are at the final position in the target string. The SB
2422 * value is always true here, so matches, depending on other
2424 if (reginfo->intuit || regtry(reginfo, &s)) {
2431 if (s == reginfo->strbeg) {
2432 if (reginfo->intuit || regtry(reginfo, &s)) {
2435 s += (utf8_target) ? UTF8SKIP(s) : 1;
2436 if (UNLIKELY(s >= reginfo->strend)) {
2442 /* We are at a boundary between char_sub_0 and char_sub_1.
2443 * We also keep track of the value for char_sub_-1 as we
2444 * loop through the line. Context may be needed to make a
2445 * determination, and if so, this can save having to
2447 WB_enum previous = WB_UNKNOWN;
2448 WB_enum before = getWB_VAL_UTF8(
2451 (U8*)(reginfo->strbeg)),
2452 (U8*) reginfo->strend);
2453 while (s < strend) {
2454 WB_enum after = getWB_VAL_UTF8((U8*) s,
2455 (U8*) reginfo->strend);
2456 if ((to_complement ^ isWB(previous,
2459 (U8*) reginfo->strbeg,
2461 (U8*) reginfo->strend,
2463 && (reginfo->intuit || regtry(reginfo, &s)))
2472 else { /* Not utf8. */
2473 WB_enum previous = WB_UNKNOWN;
2474 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2475 while (s < strend) {
2476 WB_enum after = getWB_VAL_CP((U8) *s);
2477 if ((to_complement ^ isWB(previous,
2480 (U8*) reginfo->strbeg,
2482 (U8*) reginfo->strend,
2484 && (reginfo->intuit || regtry(reginfo, &s)))
2494 if (reginfo->intuit || regtry(reginfo, &s)) {
2501 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2502 is_LNBREAK_latin1_safe(s, strend)
2507 s = find_next_ascii(s, strend, utf8_target);
2508 if (s < strend && (reginfo->intuit || regtry(reginfo, &s))) {
2515 s = find_next_non_ascii(s, strend, utf8_target);
2516 if (s < strend && (reginfo->intuit || regtry(reginfo, &s))) {
2522 /* The argument to all the POSIX node types is the class number to pass to
2523 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2530 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2531 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2532 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2547 /* The complement of something that matches only ASCII matches all
2548 * non-ASCII, plus everything in ASCII that isn't in the class. */
2549 REXEC_FBC_UTF8_CLASS_SCAN( ! isASCII_utf8_safe(s, strend)
2550 || ! _generic_isCC_A(*s, FLAGS(c)));
2558 /* Don't need to worry about utf8, as it can match only a single
2559 * byte invariant character. But we do anyway for performance reasons,
2560 * as otherwise we would have to examine all the continuation
2563 REXEC_FBC_UTF8_CLASS_SCAN(_generic_isCC_A(*s, FLAGS(c)));
2568 REXEC_FBC_CLASS_SCAN(
2569 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2577 if (! utf8_target) {
2578 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2584 classnum = (_char_class_number) FLAGS(c);
2585 if (classnum < _FIRST_NON_SWASH_CC) {
2586 while (s < strend) {
2588 /* We avoid loading in the swash as long as possible, but
2589 * should we have to, we jump to a separate loop. This
2590 * extra 'if' statement is what keeps this code from being
2591 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2592 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2593 goto found_above_latin1;
2595 if ((UTF8_IS_INVARIANT(*s)
2596 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2598 || ( UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, strend)
2599 && to_complement ^ cBOOL(
2600 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2604 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2616 else switch (classnum) { /* These classes are implemented as
2618 case _CC_ENUM_SPACE:
2619 REXEC_FBC_UTF8_CLASS_SCAN(
2620 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2623 case _CC_ENUM_BLANK:
2624 REXEC_FBC_UTF8_CLASS_SCAN(
2625 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2628 case _CC_ENUM_XDIGIT:
2629 REXEC_FBC_UTF8_CLASS_SCAN(
2630 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2633 case _CC_ENUM_VERTSPACE:
2634 REXEC_FBC_UTF8_CLASS_SCAN(
2635 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2638 case _CC_ENUM_CNTRL:
2639 REXEC_FBC_UTF8_CLASS_SCAN(
2640 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2644 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2645 NOT_REACHED; /* NOTREACHED */
2650 found_above_latin1: /* Here we have to load a swash to get the result
2651 for the current code point */
2652 if (! PL_utf8_swash_ptrs[classnum]) {
2653 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2654 PL_utf8_swash_ptrs[classnum] =
2655 _core_swash_init("utf8",
2658 PL_XPosix_ptrs[classnum], &flags);
2661 /* This is a copy of the loop above for swash classes, though using the
2662 * FBC macro instead of being expanded out. Since we've loaded the
2663 * swash, we don't have to check for that each time through the loop */
2664 REXEC_FBC_UTF8_CLASS_SCAN(
2665 to_complement ^ cBOOL(_generic_utf8_safe(
2669 swash_fetch(PL_utf8_swash_ptrs[classnum],
2677 /* what trie are we using right now */
2678 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2679 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2680 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2682 const char *last_start = strend - trie->minlen;
2684 const char *real_start = s;
2686 STRLEN maxlen = trie->maxlen;
2688 U8 **points; /* map of where we were in the input string
2689 when reading a given char. For ASCII this
2690 is unnecessary overhead as the relationship
2691 is always 1:1, but for Unicode, especially
2692 case folded Unicode this is not true. */
2693 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2697 GET_RE_DEBUG_FLAGS_DECL;
2699 /* We can't just allocate points here. We need to wrap it in
2700 * an SV so it gets freed properly if there is a croak while
2701 * running the match */
2704 sv_points=newSV(maxlen * sizeof(U8 *));
2705 SvCUR_set(sv_points,
2706 maxlen * sizeof(U8 *));
2707 SvPOK_on(sv_points);
2708 sv_2mortal(sv_points);
2709 points=(U8**)SvPV_nolen(sv_points );
2710 if ( trie_type != trie_utf8_fold
2711 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2714 bitmap=(U8*)trie->bitmap;
2716 bitmap=(U8*)ANYOF_BITMAP(c);
2718 /* this is the Aho-Corasick algorithm modified a touch
2719 to include special handling for long "unknown char" sequences.
2720 The basic idea being that we use AC as long as we are dealing
2721 with a possible matching char, when we encounter an unknown char
2722 (and we have not encountered an accepting state) we scan forward
2723 until we find a legal starting char.
2724 AC matching is basically that of trie matching, except that when
2725 we encounter a failing transition, we fall back to the current
2726 states "fail state", and try the current char again, a process
2727 we repeat until we reach the root state, state 1, or a legal
2728 transition. If we fail on the root state then we can either
2729 terminate if we have reached an accepting state previously, or
2730 restart the entire process from the beginning if we have not.
2733 while (s <= last_start) {
2734 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2742 U8 *uscan = (U8*)NULL;
2743 U8 *leftmost = NULL;
2745 U32 accepted_word= 0;
2749 while ( state && uc <= (U8*)strend ) {
2751 U32 word = aho->states[ state ].wordnum;
2755 DEBUG_TRIE_EXECUTE_r(
2756 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2757 dump_exec_pos( (char *)uc, c, strend, real_start,
2758 (char *)uc, utf8_target, 0 );
2759 Perl_re_printf( aTHX_
2760 " Scanning for legal start char...\n");
2764 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2768 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2774 if (uc >(U8*)last_start) break;
2778 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2779 if (!leftmost || lpos < leftmost) {
2780 DEBUG_r(accepted_word=word);
2786 points[pointpos++ % maxlen]= uc;
2787 if (foldlen || uc < (U8*)strend) {
2788 REXEC_TRIE_READ_CHAR(trie_type, trie,
2790 uscan, len, uvc, charid, foldlen,
2792 DEBUG_TRIE_EXECUTE_r({
2793 dump_exec_pos( (char *)uc, c, strend,
2794 real_start, s, utf8_target, 0);
2795 Perl_re_printf( aTHX_
2796 " Charid:%3u CP:%4" UVxf " ",
2808 word = aho->states[ state ].wordnum;
2810 base = aho->states[ state ].trans.base;
2812 DEBUG_TRIE_EXECUTE_r({
2814 dump_exec_pos( (char *)uc, c, strend, real_start,
2815 s, utf8_target, 0 );
2816 Perl_re_printf( aTHX_
2817 "%sState: %4" UVxf ", word=%" UVxf,
2818 failed ? " Fail transition to " : "",
2819 (UV)state, (UV)word);
2825 ( ((offset = base + charid
2826 - 1 - trie->uniquecharcount)) >= 0)
2827 && ((U32)offset < trie->lasttrans)
2828 && trie->trans[offset].check == state
2829 && (tmp=trie->trans[offset].next))
2831 DEBUG_TRIE_EXECUTE_r(
2832 Perl_re_printf( aTHX_ " - legal\n"));
2837 DEBUG_TRIE_EXECUTE_r(
2838 Perl_re_printf( aTHX_ " - fail\n"));
2840 state = aho->fail[state];
2844 /* we must be accepting here */
2845 DEBUG_TRIE_EXECUTE_r(
2846 Perl_re_printf( aTHX_ " - accepting\n"));
2855 if (!state) state = 1;
2858 if ( aho->states[ state ].wordnum ) {
2859 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2860 if (!leftmost || lpos < leftmost) {
2861 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2866 s = (char*)leftmost;
2867 DEBUG_TRIE_EXECUTE_r({
2868 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
2869 (UV)accepted_word, (IV)(s - real_start)
2872 if (reginfo->intuit || regtry(reginfo, &s)) {
2878 DEBUG_TRIE_EXECUTE_r({
2879 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2882 DEBUG_TRIE_EXECUTE_r(
2883 Perl_re_printf( aTHX_ "No match.\n"));
2892 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2899 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2900 * flags have same meanings as with regexec_flags() */
2903 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2910 struct regexp *const prog = ReANY(rx);
2912 if (flags & REXEC_COPY_STR) {
2915 DEBUG_C(Perl_re_printf( aTHX_
2916 "Copy on write: regexp capture, type %d\n",
2918 /* Create a new COW SV to share the match string and store
2919 * in saved_copy, unless the current COW SV in saved_copy
2920 * is valid and suitable for our purpose */
2921 if (( prog->saved_copy
2922 && SvIsCOW(prog->saved_copy)
2923 && SvPOKp(prog->saved_copy)
2926 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2928 /* just reuse saved_copy SV */
2929 if (RXp_MATCH_COPIED(prog)) {
2930 Safefree(prog->subbeg);
2931 RXp_MATCH_COPIED_off(prog);
2935 /* create new COW SV to share string */
2936 RXp_MATCH_COPY_FREE(prog);
2937 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2939 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2940 assert (SvPOKp(prog->saved_copy));
2941 prog->sublen = strend - strbeg;
2942 prog->suboffset = 0;
2943 prog->subcoffset = 0;
2948 SSize_t max = strend - strbeg;
2951 if ( (flags & REXEC_COPY_SKIP_POST)
2952 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2953 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2954 ) { /* don't copy $' part of string */
2957 /* calculate the right-most part of the string covered
2958 * by a capture. Due to lookahead, this may be to
2959 * the right of $&, so we have to scan all captures */
2960 while (n <= prog->lastparen) {
2961 if (prog->offs[n].end > max)
2962 max = prog->offs[n].end;
2966 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2967 ? prog->offs[0].start
2969 assert(max >= 0 && max <= strend - strbeg);
2972 if ( (flags & REXEC_COPY_SKIP_PRE)
2973 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2974 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2975 ) { /* don't copy $` part of string */
2978 /* calculate the left-most part of the string covered
2979 * by a capture. Due to lookbehind, this may be to
2980 * the left of $&, so we have to scan all captures */
2981 while (min && n <= prog->lastparen) {
2982 if ( prog->offs[n].start != -1
2983 && prog->offs[n].start < min)
2985 min = prog->offs[n].start;
2989 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2990 && min > prog->offs[0].end
2992 min = prog->offs[0].end;
2996 assert(min >= 0 && min <= max && min <= strend - strbeg);
2999 if (RXp_MATCH_COPIED(prog)) {
3000 if (sublen > prog->sublen)
3002 (char*)saferealloc(prog->subbeg, sublen+1);
3005 prog->subbeg = (char*)safemalloc(sublen+1);
3006 Copy(strbeg + min, prog->subbeg, sublen, char);
3007 prog->subbeg[sublen] = '\0';
3008 prog->suboffset = min;
3009 prog->sublen = sublen;
3010 RXp_MATCH_COPIED_on(prog);
3012 prog->subcoffset = prog->suboffset;
3013 if (prog->suboffset && utf8_target) {
3014 /* Convert byte offset to chars.
3015 * XXX ideally should only compute this if @-/@+
3016 * has been seen, a la PL_sawampersand ??? */
3018 /* If there's a direct correspondence between the
3019 * string which we're matching and the original SV,
3020 * then we can use the utf8 len cache associated with
3021 * the SV. In particular, it means that under //g,
3022 * sv_pos_b2u() will use the previously cached
3023 * position to speed up working out the new length of
3024 * subcoffset, rather than counting from the start of
3025 * the string each time. This stops
3026 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
3027 * from going quadratic */
3028 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
3029 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
3030 SV_GMAGIC|SV_CONST_RETURN);
3032 prog->subcoffset = utf8_length((U8*)strbeg,
3033 (U8*)(strbeg+prog->suboffset));
3037 RXp_MATCH_COPY_FREE(prog);
3038 prog->subbeg = strbeg;
3039 prog->suboffset = 0;
3040 prog->subcoffset = 0;
3041 prog->sublen = strend - strbeg;
3049 - regexec_flags - match a regexp against a string
3052 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
3053 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
3054 /* stringarg: the point in the string at which to begin matching */
3055 /* strend: pointer to null at end of string */
3056 /* strbeg: real beginning of string */
3057 /* minend: end of match must be >= minend bytes after stringarg. */
3058 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
3059 * itself is accessed via the pointers above */
3060 /* data: May be used for some additional optimizations.
3061 Currently unused. */
3062 /* flags: For optimizations. See REXEC_* in regexp.h */
3065 struct regexp *const prog = ReANY(rx);
3069 SSize_t minlen; /* must match at least this many chars */
3070 SSize_t dontbother = 0; /* how many characters not to try at end */
3071 const bool utf8_target = cBOOL(DO_UTF8(sv));
3073 RXi_GET_DECL(prog,progi);
3074 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
3075 regmatch_info *const reginfo = ®info_buf;
3076 regexp_paren_pair *swap = NULL;
3078 GET_RE_DEBUG_FLAGS_DECL;
3080 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
3081 PERL_UNUSED_ARG(data);
3083 /* Be paranoid... */
3085 Perl_croak(aTHX_ "NULL regexp parameter");
3089 debug_start_match(rx, utf8_target, stringarg, strend,
3093 startpos = stringarg;
3095 /* set these early as they may be used by the HOP macros below */
3096 reginfo->strbeg = strbeg;
3097 reginfo->strend = strend;
3098 reginfo->is_utf8_target = cBOOL(utf8_target);
3100 if (prog->intflags & PREGf_GPOS_SEEN) {
3103 /* set reginfo->ganch, the position where \G can match */
3106 (flags & REXEC_IGNOREPOS)
3107 ? stringarg /* use start pos rather than pos() */
3108 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
3109 /* Defined pos(): */
3110 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
3111 : strbeg; /* pos() not defined; use start of string */
3113 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3114 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
3116 /* in the presence of \G, we may need to start looking earlier in
3117 * the string than the suggested start point of stringarg:
3118 * if prog->gofs is set, then that's a known, fixed minimum
3121 * /ab|c\G/: gofs = 1
3122 * or if the minimum offset isn't known, then we have to go back
3123 * to the start of the string, e.g. /w+\G/
3126 if (prog->intflags & PREGf_ANCH_GPOS) {
3128 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
3130 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
3132 DEBUG_r(Perl_re_printf( aTHX_
3133 "fail: ganch-gofs before earliest possible start\n"));
3138 startpos = reginfo->ganch;
3140 else if (prog->gofs) {
3141 startpos = HOPBACKc(startpos, prog->gofs);
3145 else if (prog->intflags & PREGf_GPOS_FLOAT)
3149 minlen = prog->minlen;
3150 if ((startpos + minlen) > strend || startpos < strbeg) {
3151 DEBUG_r(Perl_re_printf( aTHX_
3152 "Regex match can't succeed, so not even tried\n"));
3156 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3157 * which will call destuctors to reset PL_regmatch_state, free higher
3158 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3159 * regmatch_info_aux_eval */
3161 oldsave = PL_savestack_ix;
3165 if ((prog->extflags & RXf_USE_INTUIT)
3166 && !(flags & REXEC_CHECKED))
3168 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3173 if (prog->extflags & RXf_CHECK_ALL) {
3174 /* we can match based purely on the result of INTUIT.
3175 * Set up captures etc just for $& and $-[0]
3176 * (an intuit-only match wont have $1,$2,..) */
3177 assert(!prog->nparens);
3179 /* s/// doesn't like it if $& is earlier than where we asked it to
3180 * start searching (which can happen on something like /.\G/) */
3181 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3184 /* this should only be possible under \G */
3185 assert(prog->intflags & PREGf_GPOS_SEEN);
3186 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3187 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3191 /* match via INTUIT shouldn't have any captures.
3192 * Let @-, @+, $^N know */
3193 prog->lastparen = prog->lastcloseparen = 0;
3194 RXp_MATCH_UTF8_set(prog, utf8_target);
3195 prog->offs[0].start = s - strbeg;
3196 prog->offs[0].end = utf8_target
3197 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3198 : s - strbeg + prog->minlenret;
3199 if ( !(flags & REXEC_NOT_FIRST) )
3200 S_reg_set_capture_string(aTHX_ rx,
3202 sv, flags, utf8_target);
3208 multiline = prog->extflags & RXf_PMf_MULTILINE;
3210 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3211 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3212 "String too short [regexec_flags]...\n"));
3216 /* Check validity of program. */
3217 if (UCHARAT(progi->program) != REG_MAGIC) {
3218 Perl_croak(aTHX_ "corrupted regexp program");
3221 RXp_MATCH_TAINTED_off(prog);
3222 RXp_MATCH_UTF8_set(prog, utf8_target);
3224 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3225 reginfo->intuit = 0;
3226 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3227 reginfo->warned = FALSE;
3229 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3230 /* see how far we have to get to not match where we matched before */
3231 reginfo->till = stringarg + minend;
3233 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3234 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3235 S_cleanup_regmatch_info_aux has executed (registered by
3236 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3237 magic belonging to this SV.
3238 Not newSVsv, either, as it does not COW.
3240 reginfo->sv = newSV(0);
3241 SvSetSV_nosteal(reginfo->sv, sv);
3242 SAVEFREESV(reginfo->sv);
3245 /* reserve next 2 or 3 slots in PL_regmatch_state:
3246 * slot N+0: may currently be in use: skip it
3247 * slot N+1: use for regmatch_info_aux struct
3248 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3249 * slot N+3: ready for use by regmatch()
3253 regmatch_state *old_regmatch_state;
3254 regmatch_slab *old_regmatch_slab;
3255 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3257 /* on first ever match, allocate first slab */
3258 if (!PL_regmatch_slab) {
3259 Newx(PL_regmatch_slab, 1, regmatch_slab);
3260 PL_regmatch_slab->prev = NULL;
3261 PL_regmatch_slab->next = NULL;
3262 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3265 old_regmatch_state = PL_regmatch_state;
3266 old_regmatch_slab = PL_regmatch_slab;
3268 for (i=0; i <= max; i++) {
3270 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3272 reginfo->info_aux_eval =
3273 reginfo->info_aux->info_aux_eval =
3274 &(PL_regmatch_state->u.info_aux_eval);
3276 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3277 PL_regmatch_state = S_push_slab(aTHX);
3280 /* note initial PL_regmatch_state position; at end of match we'll
3281 * pop back to there and free any higher slabs */
3283 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3284 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3285 reginfo->info_aux->poscache = NULL;
3287 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3289 if ((prog->extflags & RXf_EVAL_SEEN))
3290 S_setup_eval_state(aTHX_ reginfo);
3292 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3295 /* If there is a "must appear" string, look for it. */
3297 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3298 /* We have to be careful. If the previous successful match
3299 was from this regex we don't want a subsequent partially
3300 successful match to clobber the old results.
3301 So when we detect this possibility we add a swap buffer
3302 to the re, and switch the buffer each match. If we fail,
3303 we switch it back; otherwise we leave it swapped.
3306 /* do we need a save destructor here for eval dies? */
3307 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3308 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3309 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3317 if (prog->recurse_locinput)
3318 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3320 /* Simplest case: anchored match need be tried only once, or with
3321 * MBOL, only at the beginning of each line.
3323 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3324 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3325 * match at the start of the string then it won't match anywhere else
3326 * either; while with /.*.../, if it doesn't match at the beginning,
3327 * the earliest it could match is at the start of the next line */
3329 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3332 if (regtry(reginfo, &s))
3335 if (!(prog->intflags & PREGf_ANCH_MBOL))
3338 /* didn't match at start, try at other newline positions */
3341 dontbother = minlen - 1;
3342 end = HOP3c(strend, -dontbother, strbeg) - 1;
3344 /* skip to next newline */
3346 while (s <= end) { /* note it could be possible to match at the end of the string */
3347 /* NB: newlines are the same in unicode as they are in latin */
3350 if (prog->check_substr || prog->check_utf8) {
3351 /* note that with PREGf_IMPLICIT, intuit can only fail
3352 * or return the start position, so it's of limited utility.
3353 * Nevertheless, I made the decision that the potential for
3354 * quick fail was still worth it - DAPM */
3355 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3359 if (regtry(reginfo, &s))
3363 } /* end anchored search */
3365 if (prog->intflags & PREGf_ANCH_GPOS)
3367 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3368 assert(prog->intflags & PREGf_GPOS_SEEN);
3369 /* For anchored \G, the only position it can match from is
3370 * (ganch-gofs); we already set startpos to this above; if intuit
3371 * moved us on from there, we can't possibly succeed */
3372 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3373 if (s == startpos && regtry(reginfo, &s))
3378 /* Messy cases: unanchored match. */
3379 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3380 /* we have /x+whatever/ */
3381 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3387 if (! prog->anchored_utf8) {
3388 to_utf8_substr(prog);
3390 ch = SvPVX_const(prog->anchored_utf8)[0];
3393 DEBUG_EXECUTE_r( did_match = 1 );
3394 if (regtry(reginfo, &s)) goto got_it;
3396 while (s < strend && *s == ch)
3403 if (! prog->anchored_substr) {
3404 if (! to_byte_substr(prog)) {
3405 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3408 ch = SvPVX_const(prog->anchored_substr)[0];
3411 DEBUG_EXECUTE_r( did_match = 1 );
3412 if (regtry(reginfo, &s)) goto got_it;
3414 while (s < strend && *s == ch)
3419 DEBUG_EXECUTE_r(if (!did_match)
3420 Perl_re_printf( aTHX_
3421 "Did not find anchored character...\n")
3424 else if (prog->anchored_substr != NULL
3425 || prog->anchored_utf8 != NULL
3426 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3427 && prog->float_max_offset < strend - s)) {
3432 char *last1; /* Last position checked before */
3436 if (prog->anchored_substr || prog->anchored_utf8) {
3438 if (! prog->anchored_utf8) {
3439 to_utf8_substr(prog);
3441 must = prog->anchored_utf8;
3444 if (! prog->anchored_substr) {
3445 if (! to_byte_substr(prog)) {
3446 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3449 must = prog->anchored_substr;
3451 back_max = back_min = prog->anchored_offset;
3454 if (! prog->float_utf8) {
3455 to_utf8_substr(prog);
3457 must = prog->float_utf8;
3460 if (! prog->float_substr) {
3461 if (! to_byte_substr(prog)) {
3462 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3465 must = prog->float_substr;
3467 back_max = prog->float_max_offset;
3468 back_min = prog->float_min_offset;
3474 last = HOP3c(strend, /* Cannot start after this */
3475 -(SSize_t)(CHR_SVLEN(must)
3476 - (SvTAIL(must) != 0) + back_min), strbeg);
3478 if (s > reginfo->strbeg)
3479 last1 = HOPc(s, -1);
3481 last1 = s - 1; /* bogus */
3483 /* XXXX check_substr already used to find "s", can optimize if
3484 check_substr==must. */
3486 strend = HOPc(strend, -dontbother);
3487 while ( (s <= last) &&
3488 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3489 (unsigned char*)strend, must,
3490 multiline ? FBMrf_MULTILINE : 0)) ) {
3491 DEBUG_EXECUTE_r( did_match = 1 );
3492 if (HOPc(s, -back_max) > last1) {
3493 last1 = HOPc(s, -back_min);
3494 s = HOPc(s, -back_max);
3497 char * const t = (last1 >= reginfo->strbeg)
3498 ? HOPc(last1, 1) : last1 + 1;
3500 last1 = HOPc(s, -back_min);
3504 while (s <= last1) {
3505 if (regtry(reginfo, &s))
3508 s++; /* to break out of outer loop */
3515 while (s <= last1) {
3516 if (regtry(reginfo, &s))
3522 DEBUG_EXECUTE_r(if (!did_match) {
3523 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3524 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3525 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3526 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3527 ? "anchored" : "floating"),
3528 quoted, RE_SV_TAIL(must));
3532 else if ( (c = progi->regstclass) ) {
3534 const OPCODE op = OP(progi->regstclass);
3535 /* don't bother with what can't match */
3536 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3537 strend = HOPc(strend, -(minlen - 1));
3540 SV * const prop = sv_newmortal();
3541 regprop(prog, prop, c, reginfo, NULL);
3543 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3544 s,strend-s,PL_dump_re_max_len);
3545 Perl_re_printf( aTHX_
3546 "Matching stclass %.*s against %s (%d bytes)\n",
3547 (int)SvCUR(prop), SvPVX_const(prop),
3548 quoted, (int)(strend - s));
3551 if (find_byclass(prog, c, s, strend, reginfo))
3553 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3557 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3565 if (! prog->float_utf8) {
3566 to_utf8_substr(prog);
3568 float_real = prog->float_utf8;
3571 if (! prog->float_substr) {
3572 if (! to_byte_substr(prog)) {
3573 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3576 float_real = prog->float_substr;
3579 little = SvPV_const(float_real, len);
3580 if (SvTAIL(float_real)) {
3581 /* This means that float_real contains an artificial \n on
3582 * the end due to the presence of something like this:
3583 * /foo$/ where we can match both "foo" and "foo\n" at the
3584 * end of the string. So we have to compare the end of the
3585 * string first against the float_real without the \n and
3586 * then against the full float_real with the string. We
3587 * have to watch out for cases where the string might be
3588 * smaller than the float_real or the float_real without
3590 char *checkpos= strend - len;
3592 Perl_re_printf( aTHX_
3593 "%sChecking for float_real.%s\n",
3594 PL_colors[4], PL_colors[5]));
3595 if (checkpos + 1 < strbeg) {
3596 /* can't match, even if we remove the trailing \n
3597 * string is too short to match */
3599 Perl_re_printf( aTHX_
3600 "%sString shorter than required trailing substring, cannot match.%s\n",
3601 PL_colors[4], PL_colors[5]));
3603 } else if (memEQ(checkpos + 1, little, len - 1)) {
3604 /* can match, the end of the string matches without the
3606 last = checkpos + 1;
3607 } else if (checkpos < strbeg) {
3608 /* cant match, string is too short when the "\n" is
3611 Perl_re_printf( aTHX_
3612 "%sString does not contain required trailing substring, cannot match.%s\n",
3613 PL_colors[4], PL_colors[5]));
3615 } else if (!multiline) {
3616 /* non multiline match, so compare with the "\n" at the
3617 * end of the string */
3618 if (memEQ(checkpos, little, len)) {
3622 Perl_re_printf( aTHX_
3623 "%sString does not contain required trailing substring, cannot match.%s\n",
3624 PL_colors[4], PL_colors[5]));
3628 /* multiline match, so we have to search for a place
3629 * where the full string is located */
3635 last = rninstr(s, strend, little, little + len);
3637 last = strend; /* matching "$" */
3640 /* at one point this block contained a comment which was
3641 * probably incorrect, which said that this was a "should not
3642 * happen" case. Even if it was true when it was written I am
3643 * pretty sure it is not anymore, so I have removed the comment
3644 * and replaced it with this one. Yves */
3646 Perl_re_printf( aTHX_
3647 "%sString does not contain required substring, cannot match.%s\n",
3648 PL_colors[4], PL_colors[5]
3652 dontbother = strend - last + prog->float_min_offset;
3654 if (minlen && (dontbother < minlen))
3655 dontbother = minlen - 1;
3656 strend -= dontbother; /* this one's always in bytes! */
3657 /* We don't know much -- general case. */
3660 if (regtry(reginfo, &s))
3669 if (regtry(reginfo, &s))
3671 } while (s++ < strend);
3679 /* s/// doesn't like it if $& is earlier than where we asked it to
3680 * start searching (which can happen on something like /.\G/) */
3681 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3682 && (prog->offs[0].start < stringarg - strbeg))
3684 /* this should only be possible under \G */
3685 assert(prog->intflags & PREGf_GPOS_SEEN);
3686 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3687 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3693 Perl_re_exec_indentf( aTHX_
3694 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3702 /* clean up; this will trigger destructors that will free all slabs
3703 * above the current one, and cleanup the regmatch_info_aux
3704 * and regmatch_info_aux_eval sructs */
3706 LEAVE_SCOPE(oldsave);
3708 if (RXp_PAREN_NAMES(prog))
3709 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3711 /* make sure $`, $&, $', and $digit will work later */
3712 if ( !(flags & REXEC_NOT_FIRST) )
3713 S_reg_set_capture_string(aTHX_ rx,
3714 strbeg, reginfo->strend,
3715 sv, flags, utf8_target);
3720 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3721 PL_colors[4], PL_colors[5]));
3723 /* clean up; this will trigger destructors that will free all slabs
3724 * above the current one, and cleanup the regmatch_info_aux
3725 * and regmatch_info_aux_eval sructs */
3727 LEAVE_SCOPE(oldsave);
3730 /* we failed :-( roll it back */
3731 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3732 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3738 Safefree(prog->offs);
3745 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3746 * Do inc before dec, in case old and new rex are the same */
3747 #define SET_reg_curpm(Re2) \
3748 if (reginfo->info_aux_eval) { \
3749 (void)ReREFCNT_inc(Re2); \
3750 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3751 PM_SETRE((PL_reg_curpm), (Re2)); \
3756 - regtry - try match at specific point
3758 STATIC bool /* 0 failure, 1 success */
3759 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3762 REGEXP *const rx = reginfo->prog;
3763 regexp *const prog = ReANY(rx);
3766 U32 depth = 0; /* used by REGCP_SET */
3768 RXi_GET_DECL(prog,progi);
3769 GET_RE_DEBUG_FLAGS_DECL;
3771 PERL_ARGS_ASSERT_REGTRY;
3773 reginfo->cutpoint=NULL;
3775 prog->offs[0].start = *startposp - reginfo->strbeg;
3776 prog->lastparen = 0;
3777 prog->lastcloseparen = 0;
3779 /* XXXX What this code is doing here?!!! There should be no need
3780 to do this again and again, prog->lastparen should take care of
3783 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3784 * Actually, the code in regcppop() (which Ilya may be meaning by
3785 * prog->lastparen), is not needed at all by the test suite
3786 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3787 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3788 * Meanwhile, this code *is* needed for the
3789 * above-mentioned test suite tests to succeed. The common theme
3790 * on those tests seems to be returning null fields from matches.
3791 * --jhi updated by dapm */
3793 /* After encountering a variant of the issue mentioned above I think
3794 * the point Ilya was making is that if we properly unwind whenever
3795 * we set lastparen to a smaller value then we should not need to do
3796 * this every time, only when needed. So if we have tests that fail if
3797 * we remove this, then it suggests somewhere else we are improperly
3798 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3799 * places it is called, and related regcp() routines. - Yves */
3801 if (prog->nparens) {
3802 regexp_paren_pair *pp = prog->offs;
3804 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3812 result = regmatch(reginfo, *startposp, progi->program + 1);
3814 prog->offs[0].end = result;
3817 if (reginfo->cutpoint)
3818 *startposp= reginfo->cutpoint;
3819 REGCP_UNWIND(lastcp);
3824 #define sayYES goto yes
3825 #define sayNO goto no
3826 #define sayNO_SILENT goto no_silent
3828 /* we dont use STMT_START/END here because it leads to
3829 "unreachable code" warnings, which are bogus, but distracting. */
3830 #define CACHEsayNO \
3831 if (ST.cache_mask) \
3832 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3835 /* this is used to determine how far from the left messages like
3836 'failed...' are printed in regexec.c. It should be set such that
3837 messages are inline with the regop output that created them.
3839 #define REPORT_CODE_OFF 29
3840 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3843 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3847 PerlIO *f= Perl_debug_log;
3848 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3849 va_start(ap, depth);
3850 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3851 result = PerlIO_vprintf(f, fmt, ap);
3855 #endif /* DEBUGGING */
3858 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3859 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3860 #define CHRTEST_NOT_A_CP_1 -999
3861 #define CHRTEST_NOT_A_CP_2 -998
3863 /* grab a new slab and return the first slot in it */
3865 STATIC regmatch_state *
3868 regmatch_slab *s = PL_regmatch_slab->next;
3870 Newx(s, 1, regmatch_slab);
3871 s->prev = PL_regmatch_slab;
3873 PL_regmatch_slab->next = s;
3875 PL_regmatch_slab = s;
3876 return SLAB_FIRST(s);
3880 /* push a new state then goto it */
3882 #define PUSH_STATE_GOTO(state, node, input) \
3883 pushinput = input; \
3885 st->resume_state = state; \
3888 /* push a new state with success backtracking, then goto it */
3890 #define PUSH_YES_STATE_GOTO(state, node, input) \
3891 pushinput = input; \
3893 st->resume_state = state; \
3894 goto push_yes_state;
3901 regmatch() - main matching routine
3903 This is basically one big switch statement in a loop. We execute an op,
3904 set 'next' to point the next op, and continue. If we come to a point which
3905 we may need to backtrack to on failure such as (A|B|C), we push a
3906 backtrack state onto the backtrack stack. On failure, we pop the top
3907 state, and re-enter the loop at the state indicated. If there are no more
3908 states to pop, we return failure.
3910 Sometimes we also need to backtrack on success; for example /A+/, where
3911 after successfully matching one A, we need to go back and try to
3912 match another one; similarly for lookahead assertions: if the assertion
3913 completes successfully, we backtrack to the state just before the assertion
3914 and then carry on. In these cases, the pushed state is marked as
3915 'backtrack on success too'. This marking is in fact done by a chain of
3916 pointers, each pointing to the previous 'yes' state. On success, we pop to
3917 the nearest yes state, discarding any intermediate failure-only states.
3918 Sometimes a yes state is pushed just to force some cleanup code to be
3919 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3920 it to free the inner regex.
3922 Note that failure backtracking rewinds the cursor position, while
3923 success backtracking leaves it alone.
3925 A pattern is complete when the END op is executed, while a subpattern
3926 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3927 ops trigger the "pop to last yes state if any, otherwise return true"
3930 A common convention in this function is to use A and B to refer to the two
3931 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3932 the subpattern to be matched possibly multiple times, while B is the entire
3933 rest of the pattern. Variable and state names reflect this convention.
3935 The states in the main switch are the union of ops and failure/success of
3936 substates associated with with that op. For example, IFMATCH is the op
3937 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3938 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3939 successfully matched A and IFMATCH_A_fail is a state saying that we have
3940 just failed to match A. Resume states always come in pairs. The backtrack
3941 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3942 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3943 on success or failure.
3945 The struct that holds a backtracking state is actually a big union, with
3946 one variant for each major type of op. The variable st points to the
3947 top-most backtrack struct. To make the code clearer, within each
3948 block of code we #define ST to alias the relevant union.
3950 Here's a concrete example of a (vastly oversimplified) IFMATCH
3956 #define ST st->u.ifmatch
3958 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3959 ST.foo = ...; // some state we wish to save
3961 // push a yes backtrack state with a resume value of
3962 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3964 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3967 case IFMATCH_A: // we have successfully executed A; now continue with B
3969 bar = ST.foo; // do something with the preserved value
3972 case IFMATCH_A_fail: // A failed, so the assertion failed
3973 ...; // do some housekeeping, then ...
3974 sayNO; // propagate the failure
3981 For any old-timers reading this who are familiar with the old recursive
3982 approach, the code above is equivalent to:
3984 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3993 ...; // do some housekeeping, then ...
3994 sayNO; // propagate the failure
3997 The topmost backtrack state, pointed to by st, is usually free. If you
3998 want to claim it, populate any ST.foo fields in it with values you wish to
3999 save, then do one of
4001 PUSH_STATE_GOTO(resume_state, node, newinput);
4002 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
4004 which sets that backtrack state's resume value to 'resume_state', pushes a
4005 new free entry to the top of the backtrack stack, then goes to 'node'.
4006 On backtracking, the free slot is popped, and the saved state becomes the
4007 new free state. An ST.foo field in this new top state can be temporarily
4008 accessed to retrieve values, but once the main loop is re-entered, it
4009 becomes available for reuse.
4011 Note that the depth of the backtrack stack constantly increases during the
4012 left-to-right execution of the pattern, rather than going up and down with
4013 the pattern nesting. For example the stack is at its maximum at Z at the
4014 end of the pattern, rather than at X in the following:
4016 /(((X)+)+)+....(Y)+....Z/
4018 The only exceptions to this are lookahead/behind assertions and the cut,
4019 (?>A), which pop all the backtrack states associated with A before
4022 Backtrack state structs are allocated in slabs of about 4K in size.
4023 PL_regmatch_state and st always point to the currently active state,
4024 and PL_regmatch_slab points to the slab currently containing
4025 PL_regmatch_state. The first time regmatch() is called, the first slab is
4026 allocated, and is never freed until interpreter destruction. When the slab
4027 is full, a new one is allocated and chained to the end. At exit from
4028 regmatch(), slabs allocated since entry are freed.
4033 #define DEBUG_STATE_pp(pp) \
4035 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
4036 Perl_re_printf( aTHX_ \
4037 "%*s" pp " %s%s%s%s%s\n", \
4038 INDENT_CHARS(depth), "", \
4039 PL_reg_name[st->resume_state], \
4040 ((st==yes_state||st==mark_state) ? "[" : ""), \
4041 ((st==yes_state) ? "Y" : ""), \
4042 ((st==mark_state) ? "M" : ""), \
4043 ((st==yes_state||st==mark_state) ? "]" : "") \
4048 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
4053 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
4054 const char *start, const char *end, const char *blurb)
4056 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
4058 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
4063 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
4064 RX_PRECOMP_const(prog), RX_PRELEN(prog), PL_dump_re_max_len);
4066 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
4067 start, end - start, PL_dump_re_max_len);
4069 Perl_re_printf( aTHX_
4070 "%s%s REx%s %s against %s\n",
4071 PL_colors[4], blurb, PL_colors[5], s0, s1);
4073 if (utf8_target||utf8_pat)
4074 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
4075 utf8_pat ? "pattern" : "",
4076 utf8_pat && utf8_target ? " and " : "",
4077 utf8_target ? "string" : ""
4083 S_dump_exec_pos(pTHX_ const char *locinput,
4084 const regnode *scan,
4085 const char *loc_regeol,
4086 const char *loc_bostr,
4087 const char *loc_reg_starttry,
4088 const bool utf8_target,
4092 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
4093 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
4094 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
4095 /* The part of the string before starttry has one color
4096 (pref0_len chars), between starttry and current
4097 position another one (pref_len - pref0_len chars),
4098 after the current position the third one.
4099 We assume that pref0_len <= pref_len, otherwise we
4100 decrease pref0_len. */
4101 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
4102 ? (5 + taill) - l : locinput - loc_bostr;
4105 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
4107 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
4109 pref0_len = pref_len - (locinput - loc_reg_starttry);
4110 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
4111 l = ( loc_regeol - locinput > (5 + taill) - pref_len
4112 ? (5 + taill) - pref_len : loc_regeol - locinput);
4113 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
4117 if (pref0_len > pref_len)
4118 pref0_len = pref_len;
4120 const int is_uni = utf8_target ? 1 : 0;
4122 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
4123 (locinput - pref_len),pref0_len, PL_dump_re_max_len, 4, 5);
4125 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
4126 (locinput - pref_len + pref0_len),
4127 pref_len - pref0_len, PL_dump_re_max_len, 2, 3);
4129 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
4130 locinput, loc_regeol - locinput, 10, 0, 1);
4132 const STRLEN tlen=len0+len1+len2;
4133 Perl_re_printf( aTHX_
4134 "%4" IVdf " <%.*s%.*s%s%.*s>%*s|%4u| ",
4135 (IV)(locinput - loc_bostr),
4138 (docolor ? "" : "> <"),
4140 (int)(tlen > 19 ? 0 : 19 - tlen),
4148 /* reg_check_named_buff_matched()
4149 * Checks to see if a named buffer has matched. The data array of
4150 * buffer numbers corresponding to the buffer is expected to reside
4151 * in the regexp->data->data array in the slot stored in the ARG() of
4152 * node involved. Note that this routine doesn't actually care about the
4153 * name, that information is not preserved from compilation to execution.
4154 * Returns the index of the leftmost defined buffer with the given name
4155 * or 0 if non of the buffers matched.
4158 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
4161 RXi_GET_DECL(rex,rexi);
4162 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4163 I32 *nums=(I32*)SvPVX(sv_dat);
4165 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
4167 for ( n=0; n<SvIVX(sv_dat); n++ ) {
4168 if ((I32)rex->lastparen >= nums[n] &&
4169 rex->offs[nums[n]].end != -1)
4179 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
4180 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
4182 /* This function determines if there are one or two characters that match
4183 * the first character of the passed-in EXACTish node <text_node>, and if
4184 * so, returns them in the passed-in pointers.
4186 * If it determines that no possible character in the target string can
4187 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4188 * the first character in <text_node> requires UTF-8 to represent, and the
4189 * target string isn't in UTF-8.)
4191 * If there are more than two characters that could match the beginning of
4192 * <text_node>, or if more context is required to determine a match or not,
4193 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4195 * The motiviation behind this function is to allow the caller to set up
4196 * tight loops for matching. If <text_node> is of type EXACT, there is
4197 * only one possible character that can match its first character, and so
4198 * the situation is quite simple. But things get much more complicated if
4199 * folding is involved. It may be that the first character of an EXACTFish
4200 * node doesn't participate in any possible fold, e.g., punctuation, so it
4201 * can be matched only by itself. The vast majority of characters that are
4202 * in folds match just two things, their lower and upper-case equivalents.
4203 * But not all are like that; some have multiple possible matches, or match
4204 * sequences of more than one character. This function sorts all that out.
4206 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4207 * loop of trying to match A*, we know we can't exit where the thing
4208 * following it isn't a B. And something can't be a B unless it is the
4209 * beginning of B. By putting a quick test for that beginning in a tight
4210 * loop, we can rule out things that can't possibly be B without having to
4211 * break out of the loop, thus avoiding work. Similarly, if A is a single
4212 * character, we can make a tight loop matching A*, using the outputs of
4215 * If the target string to match isn't in UTF-8, and there aren't
4216 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4217 * the one or two possible octets (which are characters in this situation)
4218 * that can match. In all cases, if there is only one character that can
4219 * match, *<c1p> and *<c2p> will be identical.
4221 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4222 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4223 * can match the beginning of <text_node>. They should be declared with at
4224 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4225 * undefined what these contain.) If one or both of the buffers are
4226 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4227 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4228 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4229 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4230 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4232 const bool utf8_target = reginfo->is_utf8_target;
4234 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4235 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4236 bool use_chrtest_void = FALSE;
4237 const bool is_utf8_pat = reginfo->is_utf8_pat;
4239 /* Used when we have both utf8 input and utf8 output, to avoid converting
4240 * to/from code points */
4241 bool utf8_has_been_setup = FALSE;
4245 U8 *pat = (U8*)STRING(text_node);
4246 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4248 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4250 /* In an exact node, only one thing can be matched, that first
4251 * character. If both the pat and the target are UTF-8, we can just
4252 * copy the input to the output, avoiding finding the code point of
4257 else if (utf8_target) {
4258 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4259 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4260 utf8_has_been_setup = TRUE;
4263 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4266 else { /* an EXACTFish node */
4267 U8 *pat_end = pat + STR_LEN(text_node);
4269 /* An EXACTFL node has at least some characters unfolded, because what
4270 * they match is not known until now. So, now is the time to fold
4271 * the first few of them, as many as are needed to determine 'c1' and
4272 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4273 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4274 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4275 * need to fold as many characters as a single character can fold to,
4276 * so that later we can check if the first ones are such a multi-char
4277 * fold. But, in such a pattern only locale-problematic characters
4278 * aren't folded, so we can skip this completely if the first character
4279 * in the node isn't one of the tricky ones */
4280 if (OP(text_node) == EXACTFL) {
4282 if (! is_utf8_pat) {
4283 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4285 folded[0] = folded[1] = 's';
4287 pat_end = folded + 2;
4290 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4295 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4297 *(d++) = (U8) toFOLD_LC(*s);
4302 _toFOLD_utf8_flags(s,
4306 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4317 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4318 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4320 /* Multi-character folds require more context to sort out. Also
4321 * PL_utf8_foldclosures used below doesn't handle them, so have to
4322 * be handled outside this routine */
4323 use_chrtest_void = TRUE;
4325 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4326 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4328 /* Load the folds hash, if not already done */
4330 if (! PL_utf8_foldclosures) {
4331 _load_PL_utf8_foldclosures();
4334 /* The fold closures data structure is a hash with the keys
4335 * being the UTF-8 of every character that is folded to, like
4336 * 'k', and the values each an array of all code points that
4337 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4338 * Multi-character folds are not included */
4339 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4344 /* Not found in the hash, therefore there are no folds
4345 * containing it, so there is only a single character that
4349 else { /* Does participate in folds */
4350 AV* list = (AV*) *listp;
4351 if (av_tindex_skip_len_mg(list) != 1) {
4353 /* If there aren't exactly two folds to this, it is
4354 * outside the scope of this function */
4355 use_chrtest_void = TRUE;
4357 else { /* There are two. Get them */
4358 SV** c_p = av_fetch(list, 0, FALSE);
4360 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4364 c_p = av_fetch(list, 1, FALSE);
4366 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4370 /* Folds that cross the 255/256 boundary are forbidden
4371 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4372 * one is ASCIII. Since the pattern character is above
4373 * 255, and its only other match is below 256, the only
4374 * legal match will be to itself. We have thrown away
4375 * the original, so have to compute which is the one
4377 if ((c1 < 256) != (c2 < 256)) {
4378 if ((OP(text_node) == EXACTFL
4379 && ! IN_UTF8_CTYPE_LOCALE)
4380 || ((OP(text_node) == EXACTFA
4381 || OP(text_node) == EXACTFA_NO_TRIE)
4382 && (isASCII(c1) || isASCII(c2))))
4395 else /* Here, c1 is <= 255 */
4397 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4398 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4399 && ((OP(text_node) != EXACTFA
4400 && OP(text_node) != EXACTFA_NO_TRIE)
4403 /* Here, there could be something above Latin1 in the target
4404 * which folds to this character in the pattern. All such
4405 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4406 * than two characters involved in their folds, so are outside
4407 * the scope of this function */
4408 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4409 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4412 use_chrtest_void = TRUE;
4415 else { /* Here nothing above Latin1 can fold to the pattern
4417 switch (OP(text_node)) {
4419 case EXACTFL: /* /l rules */
4420 c2 = PL_fold_locale[c1];
4423 case EXACTF: /* This node only generated for non-utf8
4425 assert(! is_utf8_pat);
4426 if (! utf8_target) { /* /d rules */
4431 /* /u rules for all these. This happens to work for
4432 * EXACTFA as nothing in Latin1 folds to ASCII */
4433 case EXACTFA_NO_TRIE: /* This node only generated for
4434 non-utf8 patterns */
4435 assert(! is_utf8_pat);
4440 c2 = PL_fold_latin1[c1];
4444 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4445 NOT_REACHED; /* NOTREACHED */
4451 /* Here have figured things out. Set up the returns */
4452 if (use_chrtest_void) {
4453 *c2p = *c1p = CHRTEST_VOID;
4455 else if (utf8_target) {
4456 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4457 uvchr_to_utf8(c1_utf8, c1);
4458 uvchr_to_utf8(c2_utf8, c2);
4461 /* Invariants are stored in both the utf8 and byte outputs; Use
4462 * negative numbers otherwise for the byte ones. Make sure that the
4463 * byte ones are the same iff the utf8 ones are the same */
4464 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4465 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4468 ? CHRTEST_NOT_A_CP_1
4469 : CHRTEST_NOT_A_CP_2;
4471 else if (c1 > 255) {
4472 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4477 *c1p = *c2p = c2; /* c2 is the only representable value */
4479 else { /* c1 is representable; see about c2 */
4481 *c2p = (c2 < 256) ? c2 : c1;
4488 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4490 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4491 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4493 PERL_ARGS_ASSERT_ISGCB;
4495 switch (GCB_table[before][after]) {
4502 case GCB_RI_then_RI:
4505 U8 * temp_pos = (U8 *) curpos;
4507 /* Do not break within emoji flag sequences. That is, do not
4508 * break between regional indicator (RI) symbols if there is an
4509 * odd number of RI characters before the break point.
4510 * GB12 sot (RI RI)* RI × RI
4511 * GB13 [^RI] (RI RI)* RI × RI */
4513 while (backup_one_GCB(strbeg,
4515 utf8_target) == GCB_Regional_Indicator)
4520 return RI_count % 2 != 1;
4523 case GCB_EX_then_EM:
4525 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4527 U8 * temp_pos = (U8 *) curpos;
4531 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4533 while (prev == GCB_Extend);
4535 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4543 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4544 before, after, GCB_table[before][after]);
4551 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4555 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4557 if (*curpos < strbeg) {
4562 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4563 U8 * prev_prev_char_pos;
4565 if (! prev_char_pos) {
4569 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4570 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4571 *curpos = prev_char_pos;
4572 prev_char_pos = prev_prev_char_pos;
4575 *curpos = (U8 *) strbeg;
4580 if (*curpos - 2 < strbeg) {
4581 *curpos = (U8 *) strbeg;
4585 gcb = getGCB_VAL_CP(*(*curpos - 1));
4591 /* Combining marks attach to most classes that precede them, but this defines
4592 * the exceptions (from TR14) */
4593 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4594 || prev == LB_Mandatory_Break \
4595 || prev == LB_Carriage_Return \
4596 || prev == LB_Line_Feed \
4597 || prev == LB_Next_Line \
4598 || prev == LB_Space \
4599 || prev == LB_ZWSpace))
4602 S_isLB(pTHX_ LB_enum before,
4604 const U8 * const strbeg,
4605 const U8 * const curpos,
4606 const U8 * const strend,
4607 const bool utf8_target)
4609 U8 * temp_pos = (U8 *) curpos;
4610 LB_enum prev = before;
4612 /* Is the boundary between 'before' and 'after' line-breakable?
4613 * Most of this is just a table lookup of a generated table from Unicode
4614 * rules. But some rules require context to decide, and so have to be
4615 * implemented in code */
4617 PERL_ARGS_ASSERT_ISLB;
4619 /* Rule numbers in the comments below are as of Unicode 9.0 */
4623 switch (LB_table[before][after]) {
4628 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4631 case LB_SP_foo + LB_BREAKABLE:
4632 case LB_SP_foo + LB_NOBREAK:
4633 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4635 /* When we have something following a SP, we have to look at the
4636 * context in order to know what to do.
4638 * SP SP should not reach here because LB7: Do not break before
4639 * spaces. (For two spaces in a row there is nothing that
4640 * overrides that) */
4641 assert(after != LB_Space);
4643 /* Here we have a space followed by a non-space. Mostly this is a
4644 * case of LB18: "Break after spaces". But there are complications
4645 * as the handling of spaces is somewhat tricky. They are in a
4646 * number of rules, which have to be applied in priority order, but
4647 * something earlier in the string can cause a rule to be skipped
4648 * and a lower priority rule invoked. A prime example is LB7 which
4649 * says don't break before a space. But rule LB8 (lower priority)
4650 * says that the first break opportunity after a ZW is after any
4651 * span of spaces immediately after it. If a ZW comes before a SP
4652 * in the input, rule LB8 applies, and not LB7. Other such rules
4653 * involve combining marks which are rules 9 and 10, but they may
4654 * override higher priority rules if they come earlier in the
4655 * string. Since we're doing random access into the middle of the
4656 * string, we have to look for rules that should get applied based
4657 * on both string position and priority. Combining marks do not
4658 * attach to either ZW nor SP, so we don't have to consider them
4661 * To check for LB8, we have to find the first non-space character
4662 * before this span of spaces */
4664 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4666 while (prev == LB_Space);
4668 /* LB8 Break before any character following a zero-width space,
4669 * even if one or more spaces intervene.
4671 * So if we have a ZW just before this span, and to get here this
4672 * is the final space in the span. */
4673 if (prev == LB_ZWSpace) {
4677 /* Here, not ZW SP+. There are several rules that have higher
4678 * priority than LB18 and can be resolved now, as they don't depend
4679 * on anything earlier in the string (except ZW, which we have
4680 * already handled). One of these rules is LB11 Do not break
4681 * before Word joiner, but we have specially encoded that in the
4682 * lookup table so it is caught by the single test below which
4683 * catches the other ones. */
4684 if (LB_table[LB_Space][after] - LB_SP_foo
4685 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4690 /* If we get here, we have to XXX consider combining marks. */
4691 if (prev == LB_Combining_Mark) {
4693 /* What happens with these depends on the character they
4696 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4698 while (prev == LB_Combining_Mark);
4700 /* Most times these attach to and inherit the characteristics
4701 * of that character, but not always, and when not, they are to
4702 * be treated as AL by rule LB10. */
4703 if (! LB_CM_ATTACHES_TO(prev)) {
4704 prev = LB_Alphabetic;
4708 /* Here, we have the character preceding the span of spaces all set
4709 * up. We follow LB18: "Break after spaces" unless the table shows
4710 * that is overriden */
4711 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4715 /* We don't know how to treat the CM except by looking at the first
4716 * non-CM character preceding it. ZWJ is treated as CM */
4718 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4720 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4722 /* Here, 'prev' is that first earlier non-CM character. If the CM
4723 * attatches to it, then it inherits the behavior of 'prev'. If it
4724 * doesn't attach, it is to be treated as an AL */
4725 if (! LB_CM_ATTACHES_TO(prev)) {
4726 prev = LB_Alphabetic;
4731 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4732 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4734 /* LB21a Don't break after Hebrew + Hyphen.
4737 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4738 == LB_Hebrew_Letter)
4743 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4745 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4746 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4748 /* LB25a (PR | PO) × ( OP | HY )? NU */
4749 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4753 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4756 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4757 case LB_SY_or_IS_then_various + LB_NOBREAK:
4759 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4761 LB_enum temp = prev;
4763 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4765 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4766 if (temp == LB_Numeric) {
4770 return LB_table[prev][after] - LB_SY_or_IS_then_various
4774 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4775 case LB_various_then_PO_or_PR + LB_NOBREAK:
4777 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4779 LB_enum temp = prev;
4780 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4782 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4784 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4785 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4787 if (temp == LB_Numeric) {
4790 return LB_various_then_PO_or_PR;
4793 case LB_RI_then_RI + LB_NOBREAK:
4794 case LB_RI_then_RI + LB_BREAKABLE:
4798 /* LB30a Break between two regional indicator symbols if and
4799 * only if there are an even number of regional indicators
4800 * preceding the position of the break.
4802 * sot (RI RI)* RI × RI
4803 * [^RI] (RI RI)* RI × RI */
4805 while (backup_one_LB(strbeg,
4807 utf8_target) == LB_Regional_Indicator)
4812 return RI_count % 2 == 0;
4820 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4821 before, after, LB_table[before][after]);
4828 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4832 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4834 if (*curpos >= strend) {
4839 *curpos += UTF8SKIP(*curpos);
4840 if (*curpos >= strend) {
4843 lb = getLB_VAL_UTF8(*curpos, strend);
4847 if (*curpos >= strend) {
4850 lb = getLB_VAL_CP(**curpos);
4857 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4861 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4863 if (*curpos < strbeg) {
4868 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4869 U8 * prev_prev_char_pos;
4871 if (! prev_char_pos) {
4875 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4876 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4877 *curpos = prev_char_pos;
4878 prev_char_pos = prev_prev_char_pos;
4881 *curpos = (U8 *) strbeg;
4886 if (*curpos - 2 < strbeg) {
4887 *curpos = (U8 *) strbeg;
4891 lb = getLB_VAL_CP(*(*curpos - 1));
4898 S_isSB(pTHX_ SB_enum before,
4900 const U8 * const strbeg,
4901 const U8 * const curpos,
4902 const U8 * const strend,
4903 const bool utf8_target)
4905 /* returns a boolean indicating if there is a Sentence Boundary Break
4906 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4908 U8 * lpos = (U8 *) curpos;
4909 bool has_para_sep = FALSE;
4910 bool has_sp = FALSE;
4912 PERL_ARGS_ASSERT_ISSB;
4914 /* Break at the start and end of text.
4917 But unstated in Unicode is don't break if the text is empty */
4918 if (before == SB_EDGE || after == SB_EDGE) {
4919 return before != after;
4922 /* SB 3: Do not break within CRLF. */
4923 if (before == SB_CR && after == SB_LF) {
4927 /* Break after paragraph separators. CR and LF are considered
4928 * so because Unicode views text as like word processing text where there
4929 * are no newlines except between paragraphs, and the word processor takes
4930 * care of wrapping without there being hard line-breaks in the text *./
4931 SB4. Sep | CR | LF ÷ */
4932 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4936 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4937 * (See Section 6.2, Replacing Ignore Rules.)
4938 SB5. X (Extend | Format)* → X */
4939 if (after == SB_Extend || after == SB_Format) {
4941 /* Implied is that the these characters attach to everything
4942 * immediately prior to them except for those separator-type
4943 * characters. And the rules earlier have already handled the case
4944 * when one of those immediately precedes the extend char */
4948 if (before == SB_Extend || before == SB_Format) {
4949 U8 * temp_pos = lpos;
4950 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4951 if ( backup != SB_EDGE
4960 /* Here, both 'before' and 'backup' are these types; implied is that we
4961 * don't break between them */
4962 if (backup == SB_Extend || backup == SB_Format) {
4967 /* Do not break after ambiguous terminators like period, if they are
4968 * immediately followed by a number or lowercase letter, if they are
4969 * between uppercase letters, if the first following letter (optionally
4970 * after certain punctuation) is lowercase, or if they are followed by
4971 * "continuation" punctuation such as comma, colon, or semicolon. For
4972 * example, a period may be an abbreviation or numeric period, and thus may
4973 * not mark the end of a sentence.
4975 * SB6. ATerm × Numeric */
4976 if (before == SB_ATerm && after == SB_Numeric) {
4980 /* SB7. (Upper | Lower) ATerm × Upper */
4981 if (before == SB_ATerm && after == SB_Upper) {
4982 U8 * temp_pos = lpos;
4983 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4984 if (backup == SB_Upper || backup == SB_Lower) {
4989 /* The remaining rules that aren't the final one, all require an STerm or
4990 * an ATerm after having backed up over some Close* Sp*, and in one case an
4991 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4992 * So do that backup now, setting flags if either Sp or a paragraph
4993 * separator are found */
4995 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4996 has_para_sep = TRUE;
4997 before = backup_one_SB(strbeg, &lpos, utf8_target);
5000 if (before == SB_Sp) {
5003 before = backup_one_SB(strbeg, &lpos, utf8_target);
5005 while (before == SB_Sp);
5008 while (before == SB_Close) {
5009 before = backup_one_SB(strbeg, &lpos, utf8_target);
5012 /* The next few rules apply only when the backed-up-to is an ATerm, and in
5013 * most cases an STerm */
5014 if (before == SB_STerm || before == SB_ATerm) {
5016 /* So, here the lhs matches
5017 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
5018 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
5019 * The rules that apply here are:
5021 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
5022 | LF | STerm | ATerm) )* Lower
5023 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
5024 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
5025 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
5026 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
5029 /* And all but SB11 forbid having seen a paragraph separator */
5030 if (! has_para_sep) {
5031 if (before == SB_ATerm) { /* SB8 */
5032 U8 * rpos = (U8 *) curpos;
5033 SB_enum later = after;
5035 while ( later != SB_OLetter
5036 && later != SB_Upper
5037 && later != SB_Lower
5041 && later != SB_STerm
5042 && later != SB_ATerm
5043 && later != SB_EDGE)
5045 later = advance_one_SB(&rpos, strend, utf8_target);
5047 if (later == SB_Lower) {
5052 if ( after == SB_SContinue /* SB8a */
5053 || after == SB_STerm
5054 || after == SB_ATerm)
5059 if (! has_sp) { /* SB9 applies only if there was no Sp* */
5060 if ( after == SB_Close
5070 /* SB10. This and SB9 could probably be combined some way, but khw
5071 * has decided to follow the Unicode rule book precisely for
5072 * simplified maintenance */
5086 /* Otherwise, do not break.
5093 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
5097 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
5099 if (*curpos >= strend) {
5105 *curpos += UTF8SKIP(*curpos);
5106 if (*curpos >= strend) {
5109 sb = getSB_VAL_UTF8(*curpos, strend);
5110 } while (sb == SB_Extend || sb == SB_Format);
5115 if (*curpos >= strend) {
5118 sb = getSB_VAL_CP(**curpos);
5119 } while (sb == SB_Extend || sb == SB_Format);
5126 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5130 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
5132 if (*curpos < strbeg) {
5137 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5138 if (! prev_char_pos) {
5142 /* Back up over Extend and Format. curpos is always just to the right
5143 * of the characater whose value we are getting */
5145 U8 * prev_prev_char_pos;
5146 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
5149 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5150 *curpos = prev_char_pos;
5151 prev_char_pos = prev_prev_char_pos;
5154 *curpos = (U8 *) strbeg;
5157 } while (sb == SB_Extend || sb == SB_Format);
5161 if (*curpos - 2 < strbeg) {
5162 *curpos = (U8 *) strbeg;
5166 sb = getSB_VAL_CP(*(*curpos - 1));
5167 } while (sb == SB_Extend || sb == SB_Format);
5174 S_isWB(pTHX_ WB_enum previous,
5177 const U8 * const strbeg,
5178 const U8 * const curpos,
5179 const U8 * const strend,
5180 const bool utf8_target)
5182 /* Return a boolean as to if the boundary between 'before' and 'after' is
5183 * a Unicode word break, using their published algorithm, but tailored for
5184 * Perl by treating spans of white space as one unit. Context may be
5185 * needed to make this determination. If the value for the character
5186 * before 'before' is known, it is passed as 'previous'; otherwise that
5187 * should be set to WB_UNKNOWN. The other input parameters give the
5188 * boundaries and current position in the matching of the string. That
5189 * is, 'curpos' marks the position where the character whose wb value is
5190 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5192 U8 * before_pos = (U8 *) curpos;
5193 U8 * after_pos = (U8 *) curpos;
5194 WB_enum prev = before;
5197 PERL_ARGS_ASSERT_ISWB;
5199 /* Rule numbers in the comments below are as of Unicode 9.0 */
5203 switch (WB_table[before][after]) {
5210 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5211 next = advance_one_WB(&after_pos, strend, utf8_target,
5212 FALSE /* Don't skip Extend nor Format */ );
5213 /* A space immediately preceeding an Extend or Format is attached
5214 * to by them, and hence gets separated from previous spaces.
5215 * Otherwise don't break between horizontal white space */
5216 return next == WB_Extend || next == WB_Format;
5218 /* WB4 Ignore Format and Extend characters, except when they appear at
5219 * the beginning of a region of text. This code currently isn't
5220 * general purpose, but it works as the rules are currently and likely
5221 * to be laid out. The reason it works is that when 'they appear at
5222 * the beginning of a region of text', the rule is to break before
5223 * them, just like any other character. Therefore, the default rule
5224 * applies and we don't have to look in more depth. Should this ever
5225 * change, we would have to have 2 'case' statements, like in the rules
5226 * below, and backup a single character (not spacing over the extend
5227 * ones) and then see if that is one of the region-end characters and
5229 case WB_Ex_or_FO_or_ZWJ_then_foo:
5230 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5233 case WB_DQ_then_HL + WB_BREAKABLE:
5234 case WB_DQ_then_HL + WB_NOBREAK:
5236 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5238 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5239 == WB_Hebrew_Letter)
5244 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5246 case WB_HL_then_DQ + WB_BREAKABLE:
5247 case WB_HL_then_DQ + WB_NOBREAK:
5249 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5251 if (advance_one_WB(&after_pos, strend, utf8_target,
5252 TRUE /* Do skip Extend and Format */ )
5253 == WB_Hebrew_Letter)
5258 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5260 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5261 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5263 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5264 * | Single_Quote) (ALetter | Hebrew_Letter) */
5266 next = advance_one_WB(&after_pos, strend, utf8_target,
5267 TRUE /* Do skip Extend and Format */ );
5269 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5274 return WB_table[before][after]
5275 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5277 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5278 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5280 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5281 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5283 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5284 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5289 return WB_table[before][after]
5290 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5292 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5293 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5295 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5298 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5304 return WB_table[before][after]
5305 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5307 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5308 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5310 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5312 if (advance_one_WB(&after_pos, strend, utf8_target,
5313 TRUE /* Do skip Extend and Format */ )
5319 return WB_table[before][after]
5320 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5322 case WB_RI_then_RI + WB_NOBREAK:
5323 case WB_RI_then_RI + WB_BREAKABLE:
5327 /* Do not break within emoji flag sequences. That is, do not
5328 * break between regional indicator (RI) symbols if there is an
5329 * odd number of RI characters before the potential break
5332 * WB15 sot (RI RI)* RI × RI
5333 * WB16 [^RI] (RI RI)* RI × RI */
5335 while (backup_one_WB(&previous,
5338 utf8_target) == WB_Regional_Indicator)
5343 return RI_count % 2 != 1;
5351 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5352 before, after, WB_table[before][after]);
5359 S_advance_one_WB(pTHX_ U8 ** curpos,
5360 const U8 * const strend,
5361 const bool utf8_target,
5362 const bool skip_Extend_Format)
5366 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5368 if (*curpos >= strend) {
5374 /* Advance over Extend and Format */
5376 *curpos += UTF8SKIP(*curpos);
5377 if (*curpos >= strend) {
5380 wb = getWB_VAL_UTF8(*curpos, strend);
5381 } while ( skip_Extend_Format
5382 && (wb == WB_Extend || wb == WB_Format));
5387 if (*curpos >= strend) {
5390 wb = getWB_VAL_CP(**curpos);
5391 } while ( skip_Extend_Format
5392 && (wb == WB_Extend || wb == WB_Format));
5399 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5403 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5405 /* If we know what the previous character's break value is, don't have
5407 if (*previous != WB_UNKNOWN) {
5410 /* But we need to move backwards by one */
5412 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5414 *previous = WB_EDGE;
5415 *curpos = (U8 *) strbeg;
5418 *previous = WB_UNKNOWN;
5423 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5426 /* And we always back up over these three types */
5427 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5432 if (*curpos < strbeg) {
5437 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5438 if (! prev_char_pos) {
5442 /* Back up over Extend and Format. curpos is always just to the right
5443 * of the characater whose value we are getting */
5445 U8 * prev_prev_char_pos;
5446 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5450 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5451 *curpos = prev_char_pos;
5452 prev_char_pos = prev_prev_char_pos;
5455 *curpos = (U8 *) strbeg;
5458 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5462 if (*curpos - 2 < strbeg) {
5463 *curpos = (U8 *) strbeg;
5467 wb = getWB_VAL_CP(*(*curpos - 1));
5468 } while (wb == WB_Extend || wb == WB_Format);
5474 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5477 ( ( st )->u.eval.close_paren ) && \
5478 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5481 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5484 ( ( st )->u.eval.close_paren ) && \
5486 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5490 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5491 (st)->u.eval.close_paren = ( (expr) + 1 )
5493 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5494 (st)->u.eval.close_paren = 0
5496 /* returns -1 on failure, $+[0] on success */
5498 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5501 const bool utf8_target = reginfo->is_utf8_target;
5502 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5503 REGEXP *rex_sv = reginfo->prog;
5504 regexp *rex = ReANY(rex_sv);
5505 RXi_GET_DECL(rex,rexi);
5506 /* the current state. This is a cached copy of PL_regmatch_state */
5508 /* cache heavy used fields of st in registers */
5511 U32 n = 0; /* general value; init to avoid compiler warning */
5512 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5513 SSize_t endref = 0; /* offset of end of backref when ln is start */
5514 char *locinput = startpos;
5515 char *pushinput; /* where to continue after a PUSH */
5516 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5518 bool result = 0; /* return value of S_regmatch */
5519 U32 depth = 0; /* depth of backtrack stack */
5520 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5521 const U32 max_nochange_depth =
5522 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5523 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5524 regmatch_state *yes_state = NULL; /* state to pop to on success of
5526 /* mark_state piggy backs on the yes_state logic so that when we unwind
5527 the stack on success we can update the mark_state as we go */
5528 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5529 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5530 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5532 bool no_final = 0; /* prevent failure from backtracking? */
5533 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5534 char *startpoint = locinput;
5535 SV *popmark = NULL; /* are we looking for a mark? */
5536 SV *sv_commit = NULL; /* last mark name seen in failure */
5537 SV *sv_yes_mark = NULL; /* last mark name we have seen
5538 during a successful match */
5539 U32 lastopen = 0; /* last open we saw */
5540 bool has_cutgroup = RXp_HAS_CUTGROUP(rex) ? 1 : 0;
5541 SV* const oreplsv = GvSVn(PL_replgv);
5542 /* these three flags are set by various ops to signal information to
5543 * the very next op. They have a useful lifetime of exactly one loop
5544 * iteration, and are not preserved or restored by state pushes/pops
5546 bool sw = 0; /* the condition value in (?(cond)a|b) */
5547 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5548 int logical = 0; /* the following EVAL is:
5552 or the following IFMATCH/UNLESSM is:
5553 false: plain (?=foo)
5554 true: used as a condition: (?(?=foo))
5556 PAD* last_pad = NULL;
5558 U8 gimme = G_SCALAR;
5559 CV *caller_cv = NULL; /* who called us */
5560 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5561 U32 maxopenparen = 0; /* max '(' index seen so far */
5562 int to_complement; /* Invert the result? */
5563 _char_class_number classnum;
5564 bool is_utf8_pat = reginfo->is_utf8_pat;
5566 I32 orig_savestack_ix = PL_savestack_ix;
5567 U8 * script_run_begin = NULL;
5569 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5570 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5571 # define SOLARIS_BAD_OPTIMIZER
5572 const U32 *pl_charclass_dup = PL_charclass;
5573 # define PL_charclass pl_charclass_dup
5577 GET_RE_DEBUG_FLAGS_DECL;
5580 /* protect against undef(*^R) */
5581 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5583 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5584 multicall_oldcatch = 0;
5585 PERL_UNUSED_VAR(multicall_cop);
5587 PERL_ARGS_ASSERT_REGMATCH;
5589 st = PL_regmatch_state;
5591 /* Note that nextchr is a byte even in UTF */
5595 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5596 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5597 Perl_re_printf( aTHX_ "regmatch start\n" );
5600 while (scan != NULL) {
5601 next = scan + NEXT_OFF(scan);
5604 state_num = OP(scan);
5608 if (state_num <= REGNODE_MAX) {
5609 SV * const prop = sv_newmortal();
5610 regnode *rnext = regnext(scan);
5612 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5613 regprop(rex, prop, scan, reginfo, NULL);
5614 Perl_re_printf( aTHX_
5615 "%*s%" IVdf ":%s(%" IVdf ")\n",
5616 INDENT_CHARS(depth), "",
5617 (IV)(scan - rexi->program),
5619 (PL_regkind[OP(scan)] == END || !rnext) ?
5620 0 : (IV)(rnext - rexi->program));
5627 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5629 switch (state_num) {
5630 case SBOL: /* /^../ and /\A../ */
5631 if (locinput == reginfo->strbeg)
5635 case MBOL: /* /^../m */
5636 if (locinput == reginfo->strbeg ||
5637 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5644 if (locinput == reginfo->ganch)
5648 case KEEPS: /* \K */
5649 /* update the startpoint */
5650 st->u.keeper.val = rex->offs[0].start;
5651 rex->offs[0].start = locinput - reginfo->strbeg;
5652 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5653 NOT_REACHED; /* NOTREACHED */
5655 case KEEPS_next_fail:
5656 /* rollback the start point change */
5657 rex->offs[0].start = st->u.keeper.val;
5659 NOT_REACHED; /* NOTREACHED */
5661 case MEOL: /* /..$/m */
5662 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5666 case SEOL: /* /..$/ */
5667 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5669 if (reginfo->strend - locinput > 1)
5674 if (!NEXTCHR_IS_EOS)
5678 case SANY: /* /./s */
5681 goto increment_locinput;
5683 case REG_ANY: /* /./ */
5684 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5686 goto increment_locinput;
5690 #define ST st->u.trie
5691 case TRIEC: /* (ab|cd) with known charclass */
5692 /* In this case the charclass data is available inline so
5693 we can fail fast without a lot of extra overhead.
5695 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5697 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5698 depth, PL_colors[4], PL_colors[5])
5701 NOT_REACHED; /* NOTREACHED */
5704 case TRIE: /* (ab|cd) */
5705 /* the basic plan of execution of the trie is:
5706 * At the beginning, run though all the states, and
5707 * find the longest-matching word. Also remember the position
5708 * of the shortest matching word. For example, this pattern:
5711 * when matched against the string "abcde", will generate
5712 * accept states for all words except 3, with the longest
5713 * matching word being 4, and the shortest being 2 (with
5714 * the position being after char 1 of the string).
5716 * Then for each matching word, in word order (i.e. 1,2,4,5),
5717 * we run the remainder of the pattern; on each try setting
5718 * the current position to the character following the word,
5719 * returning to try the next word on failure.
5721 * We avoid having to build a list of words at runtime by
5722 * using a compile-time structure, wordinfo[].prev, which
5723 * gives, for each word, the previous accepting word (if any).
5724 * In the case above it would contain the mappings 1->2, 2->0,
5725 * 3->0, 4->5, 5->1. We can use this table to generate, from
5726 * the longest word (4 above), a list of all words, by
5727 * following the list of prev pointers; this gives us the
5728 * unordered list 4,5,1,2. Then given the current word we have
5729 * just tried, we can go through the list and find the
5730 * next-biggest word to try (so if we just failed on word 2,
5731 * the next in the list is 4).
5733 * Since at runtime we don't record the matching position in
5734 * the string for each word, we have to work that out for
5735 * each word we're about to process. The wordinfo table holds
5736 * the character length of each word; given that we recorded
5737 * at the start: the position of the shortest word and its
5738 * length in chars, we just need to move the pointer the
5739 * difference between the two char lengths. Depending on
5740 * Unicode status and folding, that's cheap or expensive.
5742 * This algorithm is optimised for the case where are only a
5743 * small number of accept states, i.e. 0,1, or maybe 2.
5744 * With lots of accepts states, and having to try all of them,
5745 * it becomes quadratic on number of accept states to find all
5750 /* what type of TRIE am I? (utf8 makes this contextual) */
5751 DECL_TRIE_TYPE(scan);
5753 /* what trie are we using right now */
5754 reg_trie_data * const trie
5755 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5756 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5757 U32 state = trie->startstate;
5759 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5760 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5762 && nextchr >= 0 /* guard against negative EOS value in nextchr */
5763 && UTF8_IS_ABOVE_LATIN1(nextchr)
5764 && scan->flags == EXACTL)
5766 /* We only output for EXACTL, as we let the folder
5767 * output this message for EXACTFLU8 to avoid
5769 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5774 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5776 if (trie->states[ state ].wordnum) {
5778 Perl_re_exec_indentf( aTHX_ "%smatched empty string...%s\n",
5779 depth, PL_colors[4], PL_colors[5])
5785 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5786 depth, PL_colors[4], PL_colors[5])
5793 U8 *uc = ( U8* )locinput;
5797 U8 *uscan = (U8*)NULL;
5798 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5799 U32 charcount = 0; /* how many input chars we have matched */
5800 U32 accepted = 0; /* have we seen any accepting states? */
5802 ST.jump = trie->jump;
5805 ST.longfold = FALSE; /* char longer if folded => it's harder */
5808 /* fully traverse the TRIE; note the position of the
5809 shortest accept state and the wordnum of the longest
5812 while ( state && uc <= (U8*)(reginfo->strend) ) {
5813 U32 base = trie->states[ state ].trans.base;
5817 wordnum = trie->states[ state ].wordnum;
5819 if (wordnum) { /* it's an accept state */
5822 /* record first match position */
5824 ST.firstpos = (U8*)locinput;
5829 ST.firstchars = charcount;
5832 if (!ST.nextword || wordnum < ST.nextword)
5833 ST.nextword = wordnum;
5834 ST.topword = wordnum;
5837 DEBUG_TRIE_EXECUTE_r({
5838 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
5840 PerlIO_printf( Perl_debug_log,
5841 "%*s%sState: %4" UVxf " Accepted: %c ",
5842 INDENT_CHARS(depth), "", PL_colors[4],
5843 (UV)state, (accepted ? 'Y' : 'N'));
5846 /* read a char and goto next state */
5847 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5849 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5850 uscan, len, uvc, charid, foldlen,
5857 base + charid - 1 - trie->uniquecharcount)) >= 0)
5859 && ((U32)offset < trie->lasttrans)
5860 && trie->trans[offset].check == state)
5862 state = trie->trans[offset].next;
5873 DEBUG_TRIE_EXECUTE_r(
5874 Perl_re_printf( aTHX_
5875 "Charid:%3x CP:%4" UVxf " After State: %4" UVxf "%s\n",
5876 charid, uvc, (UV)state, PL_colors[5] );
5882 /* calculate total number of accept states */
5887 w = trie->wordinfo[w].prev;
5890 ST.accepted = accepted;
5894 Perl_re_exec_indentf( aTHX_ "%sgot %" IVdf " possible matches%s\n",
5896 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5898 goto trie_first_try; /* jump into the fail handler */
5900 NOT_REACHED; /* NOTREACHED */
5902 case TRIE_next_fail: /* we failed - try next alternative */
5906 /* undo any captures done in the tail part of a branch,
5908 * /(?:X(.)(.)|Y(.)).../
5909 * where the trie just matches X then calls out to do the
5910 * rest of the branch */
5911 REGCP_UNWIND(ST.cp);
5912 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5914 if (!--ST.accepted) {
5916 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
5924 /* Find next-highest word to process. Note that this code
5925 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5928 U16 const nextword = ST.nextword;
5929 reg_trie_wordinfo * const wordinfo
5930 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5931 for (word=ST.topword; word; word=wordinfo[word].prev) {
5932 if (word > nextword && (!min || word < min))
5945 ST.lastparen = rex->lastparen;
5946 ST.lastcloseparen = rex->lastcloseparen;
5950 /* find start char of end of current word */
5952 U32 chars; /* how many chars to skip */
5953 reg_trie_data * const trie
5954 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5956 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5958 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5963 /* the hard option - fold each char in turn and find
5964 * its folded length (which may be different */
5965 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5973 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5981 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5986 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
6002 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
6003 ? ST.jump[ST.nextword]
6007 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
6015 if ( ST.accepted > 1 || has_cutgroup || ST.jump ) {
6016 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
6017 NOT_REACHED; /* NOTREACHED */
6019 /* only one choice left - just continue */
6021 AV *const trie_words
6022 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
6023 SV ** const tmp = trie_words
6024 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
6025 SV *sv= tmp ? sv_newmortal() : NULL;
6027 Perl_re_exec_indentf( aTHX_ "%sonly one match left, short-circuiting: #%d <%s>%s\n",
6028 depth, PL_colors[4],
6030 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
6031 PL_colors[0], PL_colors[1],
6032 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
6034 : "not compiled under -Dr",
6038 locinput = (char*)uc;
6039 continue; /* execute rest of RE */
6044 case EXACTL: /* /abc/l */
6045 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6047 /* Complete checking would involve going through every character
6048 * matched by the string to see if any is above latin1. But the
6049 * comparision otherwise might very well be a fast assembly
6050 * language routine, and I (khw) don't think slowing things down
6051 * just to check for this warning is worth it. So this just checks
6052 * the first character */
6053 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
6054 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6057 case EXACT: { /* /abc/ */
6058 char *s = STRING(scan);
6060 if (utf8_target != is_utf8_pat) {
6061 /* The target and the pattern have differing utf8ness. */
6063 const char * const e = s + ln;
6066 /* The target is utf8, the pattern is not utf8.
6067 * Above-Latin1 code points can't match the pattern;
6068 * invariants match exactly, and the other Latin1 ones need
6069 * to be downgraded to a single byte in order to do the
6070 * comparison. (If we could be confident that the target
6071 * is not malformed, this could be refactored to have fewer
6072 * tests by just assuming that if the first bytes match, it
6073 * is an invariant, but there are tests in the test suite
6074 * dealing with (??{...}) which violate this) */
6076 if (l >= reginfo->strend
6077 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
6081 if (UTF8_IS_INVARIANT(*(U8*)l)) {
6088 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
6098 /* The target is not utf8, the pattern is utf8. */
6100 if (l >= reginfo->strend
6101 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
6105 if (UTF8_IS_INVARIANT(*(U8*)s)) {
6112 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
6124 /* The target and the pattern have the same utf8ness. */
6125 /* Inline the first character, for speed. */
6126 if (reginfo->strend - locinput < ln
6127 || UCHARAT(s) != nextchr
6128 || (ln > 1 && memNE(s, locinput, ln)))
6137 case EXACTFL: { /* /abc/il */
6139 const U8 * fold_array;
6141 U32 fold_utf8_flags;
6143 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6144 folder = foldEQ_locale;
6145 fold_array = PL_fold_locale;
6146 fold_utf8_flags = FOLDEQ_LOCALE;
6149 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
6150 is effectively /u; hence to match, target
6152 if (! utf8_target) {
6155 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
6156 | FOLDEQ_S1_FOLDS_SANE;
6157 folder = foldEQ_latin1;
6158 fold_array = PL_fold_latin1;
6161 case EXACTFU_SS: /* /\x{df}/iu */
6162 case EXACTFU: /* /abc/iu */
6163 folder = foldEQ_latin1;
6164 fold_array = PL_fold_latin1;
6165 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
6168 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
6170 assert(! is_utf8_pat);
6172 case EXACTFA: /* /abc/iaa */
6173 folder = foldEQ_latin1;
6174 fold_array = PL_fold_latin1;
6175 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6178 case EXACTF: /* /abc/i This node only generated for
6179 non-utf8 patterns */
6180 assert(! is_utf8_pat);
6182 fold_array = PL_fold;
6183 fold_utf8_flags = 0;
6191 || state_num == EXACTFU_SS
6192 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6194 /* Either target or the pattern are utf8, or has the issue where
6195 * the fold lengths may differ. */
6196 const char * const l = locinput;
6197 char *e = reginfo->strend;
6199 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6200 l, &e, 0, utf8_target, fold_utf8_flags))
6208 /* Neither the target nor the pattern are utf8 */
6209 if (UCHARAT(s) != nextchr
6211 && UCHARAT(s) != fold_array[nextchr])
6215 if (reginfo->strend - locinput < ln)
6217 if (ln > 1 && ! folder(s, locinput, ln))
6223 case NBOUNDL: /* /\B/l */
6227 case BOUNDL: /* /\b/l */
6230 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6232 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6233 if (! IN_UTF8_CTYPE_LOCALE) {
6234 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6235 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6241 if (locinput == reginfo->strbeg)
6242 b1 = isWORDCHAR_LC('\n');
6244 b1 = isWORDCHAR_LC_utf8_safe(reghop3((U8*)locinput, -1,
6245 (U8*)(reginfo->strbeg)),
6246 (U8*)(reginfo->strend));
6248 b2 = (NEXTCHR_IS_EOS)
6249 ? isWORDCHAR_LC('\n')
6250 : isWORDCHAR_LC_utf8_safe((U8*) locinput,
6251 (U8*) reginfo->strend);
6253 else { /* Here the string isn't utf8 */
6254 b1 = (locinput == reginfo->strbeg)
6255 ? isWORDCHAR_LC('\n')
6256 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6257 b2 = (NEXTCHR_IS_EOS)
6258 ? isWORDCHAR_LC('\n')
6259 : isWORDCHAR_LC(nextchr);
6261 if (to_complement ^ (b1 == b2)) {
6267 case NBOUND: /* /\B/ */
6271 case BOUND: /* /\b/ */
6275 goto bound_ascii_match_only;
6277 case NBOUNDA: /* /\B/a */
6281 case BOUNDA: /* /\b/a */
6285 bound_ascii_match_only:
6286 /* Here the string isn't utf8, or is utf8 and only ascii characters
6287 * are to match \w. In the latter case looking at the byte just
6288 * prior to the current one may be just the final byte of a
6289 * multi-byte character. This is ok. There are two cases:
6290 * 1) it is a single byte character, and then the test is doing
6291 * just what it's supposed to.
6292 * 2) it is a multi-byte character, in which case the final byte is
6293 * never mistakable for ASCII, and so the test will say it is
6294 * not a word character, which is the correct answer. */
6295 b1 = (locinput == reginfo->strbeg)
6296 ? isWORDCHAR_A('\n')
6297 : isWORDCHAR_A(UCHARAT(locinput - 1));
6298 b2 = (NEXTCHR_IS_EOS)
6299 ? isWORDCHAR_A('\n')
6300 : isWORDCHAR_A(nextchr);
6301 if (to_complement ^ (b1 == b2)) {
6307 case NBOUNDU: /* /\B/u */
6311 case BOUNDU: /* /\b/u */
6314 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6317 else if (utf8_target) {
6319 switch((bound_type) FLAGS(scan)) {
6320 case TRADITIONAL_BOUND:
6323 b1 = (locinput == reginfo->strbeg)
6324 ? 0 /* isWORDCHAR_L1('\n') */
6325 : isWORDCHAR_utf8_safe(
6326 reghop3((U8*)locinput,
6328 (U8*)(reginfo->strbeg)),
6329 (U8*) reginfo->strend);
6330 b2 = (NEXTCHR_IS_EOS)
6331 ? 0 /* isWORDCHAR_L1('\n') */
6332 : isWORDCHAR_utf8_safe((U8*)locinput,
6333 (U8*) reginfo->strend);
6334 match = cBOOL(b1 != b2);
6338 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6339 match = TRUE; /* GCB always matches at begin and
6343 /* Find the gcb values of previous and current
6344 * chars, then see if is a break point */
6345 match = isGCB(getGCB_VAL_UTF8(
6346 reghop3((U8*)locinput,
6348 (U8*)(reginfo->strbeg)),
6349 (U8*) reginfo->strend),
6350 getGCB_VAL_UTF8((U8*) locinput,
6351 (U8*) reginfo->strend),
6352 (U8*) reginfo->strbeg,
6359 if (locinput == reginfo->strbeg) {
6362 else if (NEXTCHR_IS_EOS) {
6366 match = isLB(getLB_VAL_UTF8(
6367 reghop3((U8*)locinput,
6369 (U8*)(reginfo->strbeg)),
6370 (U8*) reginfo->strend),
6371 getLB_VAL_UTF8((U8*) locinput,
6372 (U8*) reginfo->strend),
6373 (U8*) reginfo->strbeg,
6375 (U8*) reginfo->strend,
6380 case SB_BOUND: /* Always matches at begin and end */
6381 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6385 match = isSB(getSB_VAL_UTF8(
6386 reghop3((U8*)locinput,
6388 (U8*)(reginfo->strbeg)),
6389 (U8*) reginfo->strend),
6390 getSB_VAL_UTF8((U8*) locinput,
6391 (U8*) reginfo->strend),
6392 (U8*) reginfo->strbeg,
6394 (U8*) reginfo->strend,
6400 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6404 match = isWB(WB_UNKNOWN,
6406 reghop3((U8*)locinput,
6408 (U8*)(reginfo->strbeg)),
6409 (U8*) reginfo->strend),
6410 getWB_VAL_UTF8((U8*) locinput,
6411 (U8*) reginfo->strend),
6412 (U8*) reginfo->strbeg,
6414 (U8*) reginfo->strend,
6420 else { /* Not utf8 target */
6421 switch((bound_type) FLAGS(scan)) {
6422 case TRADITIONAL_BOUND:
6425 b1 = (locinput == reginfo->strbeg)
6426 ? 0 /* isWORDCHAR_L1('\n') */
6427 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6428 b2 = (NEXTCHR_IS_EOS)
6429 ? 0 /* isWORDCHAR_L1('\n') */
6430 : isWORDCHAR_L1(nextchr);
6431 match = cBOOL(b1 != b2);
6436 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6437 match = TRUE; /* GCB always matches at begin and
6440 else { /* Only CR-LF combo isn't a GCB in 0-255
6442 match = UCHARAT(locinput - 1) != '\r'
6443 || UCHARAT(locinput) != '\n';
6448 if (locinput == reginfo->strbeg) {
6451 else if (NEXTCHR_IS_EOS) {
6455 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6456 getLB_VAL_CP(UCHARAT(locinput)),
6457 (U8*) reginfo->strbeg,
6459 (U8*) reginfo->strend,
6464 case SB_BOUND: /* Always matches at begin and end */
6465 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6469 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6470 getSB_VAL_CP(UCHARAT(locinput)),
6471 (U8*) reginfo->strbeg,
6473 (U8*) reginfo->strend,
6479 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6483 match = isWB(WB_UNKNOWN,
6484 getWB_VAL_CP(UCHARAT(locinput -1)),
6485 getWB_VAL_CP(UCHARAT(locinput)),
6486 (U8*) reginfo->strbeg,
6488 (U8*) reginfo->strend,
6495 if (to_complement ^ ! match) {
6500 case ANYOFL: /* /[abc]/l */
6501 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6503 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6505 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6508 case ANYOFD: /* /[abc]/d */
6509 case ANYOF: /* /[abc]/ */
6512 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6513 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6516 locinput += UTF8SKIP(locinput);
6519 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6526 if (NEXTCHR_IS_EOS || ! isASCII(UCHARAT(locinput))) {
6530 locinput++; /* ASCII is always single byte */
6534 if (NEXTCHR_IS_EOS || isASCII(UCHARAT(locinput))) {
6538 goto increment_locinput;
6541 /* The argument (FLAGS) to all the POSIX node types is the class number
6544 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6548 case POSIXL: /* \w or [:punct:] etc. under /l */
6549 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6553 /* Use isFOO_lc() for characters within Latin1. (Note that
6554 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6555 * wouldn't be invariant) */
6556 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6557 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6565 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6566 /* An above Latin-1 code point, or malformed */
6567 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
6569 goto utf8_posix_above_latin1;
6572 /* Here is a UTF-8 variant code point below 256 and the target is
6574 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6575 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6576 *(locinput + 1))))))
6581 goto increment_locinput;
6583 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6587 case POSIXD: /* \w or [:punct:] etc. under /d */
6593 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6595 if (NEXTCHR_IS_EOS) {
6599 /* All UTF-8 variants match */
6600 if (! UTF8_IS_INVARIANT(nextchr)) {
6601 goto increment_locinput;
6607 case POSIXA: /* \w or [:punct:] etc. under /a */
6610 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6611 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6612 * character is a single byte */
6614 if (NEXTCHR_IS_EOS) {
6620 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6626 /* Here we are either not in utf8, or we matched a utf8-invariant,
6627 * so the next char is the next byte */
6631 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6635 case POSIXU: /* \w or [:punct:] etc. under /u */
6637 if (NEXTCHR_IS_EOS) {
6641 /* Use _generic_isCC() for characters within Latin1. (Note that
6642 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6643 * wouldn't be invariant) */
6644 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6645 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6652 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6653 if (! (to_complement
6654 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6662 else { /* Handle above Latin-1 code points */
6663 utf8_posix_above_latin1:
6664 classnum = (_char_class_number) FLAGS(scan);
6665 if (classnum < _FIRST_NON_SWASH_CC) {
6667 /* Here, uses a swash to find such code points. Load if if
6668 * not done already */
6669 if (! PL_utf8_swash_ptrs[classnum]) {
6670 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6671 PL_utf8_swash_ptrs[classnum]
6672 = _core_swash_init("utf8",
6675 PL_XPosix_ptrs[classnum], &flags);
6677 if (! (to_complement
6678 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6679 (U8 *) locinput, TRUE))))
6684 else { /* Here, uses macros to find above Latin-1 code points */
6686 case _CC_ENUM_SPACE:
6687 if (! (to_complement
6688 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6693 case _CC_ENUM_BLANK:
6694 if (! (to_complement
6695 ^ cBOOL(is_HORIZWS_high(locinput))))
6700 case _CC_ENUM_XDIGIT:
6701 if (! (to_complement
6702 ^ cBOOL(is_XDIGIT_high(locinput))))
6707 case _CC_ENUM_VERTSPACE:
6708 if (! (to_complement
6709 ^ cBOOL(is_VERTWS_high(locinput))))
6714 default: /* The rest, e.g. [:cntrl:], can't match
6716 if (! to_complement) {
6722 locinput += UTF8SKIP(locinput);
6726 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6727 a Unicode extended Grapheme Cluster */
6730 if (! utf8_target) {
6732 /* Match either CR LF or '.', as all the other possibilities
6734 locinput++; /* Match the . or CR */
6735 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6737 && locinput < reginfo->strend
6738 && UCHARAT(locinput) == '\n')
6745 /* Get the gcb type for the current character */
6746 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6747 (U8*) reginfo->strend);
6749 /* Then scan through the input until we get to the first
6750 * character whose type is supposed to be a gcb with the
6751 * current character. (There is always a break at the
6753 locinput += UTF8SKIP(locinput);
6754 while (locinput < reginfo->strend) {
6755 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6756 (U8*) reginfo->strend);
6757 if (isGCB(prev_gcb, cur_gcb,
6758 (U8*) reginfo->strbeg, (U8*) locinput,
6765 locinput += UTF8SKIP(locinput);
6772 case NREFFL: /* /\g{name}/il */
6773 { /* The capture buffer cases. The ones beginning with N for the
6774 named buffers just convert to the equivalent numbered and
6775 pretend they were called as the corresponding numbered buffer
6777 /* don't initialize these in the declaration, it makes C++
6782 const U8 *fold_array;
6785 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6786 folder = foldEQ_locale;
6787 fold_array = PL_fold_locale;
6789 utf8_fold_flags = FOLDEQ_LOCALE;
6792 case NREFFA: /* /\g{name}/iaa */
6793 folder = foldEQ_latin1;
6794 fold_array = PL_fold_latin1;
6796 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6799 case NREFFU: /* /\g{name}/iu */
6800 folder = foldEQ_latin1;
6801 fold_array = PL_fold_latin1;
6803 utf8_fold_flags = 0;
6806 case NREFF: /* /\g{name}/i */
6808 fold_array = PL_fold;
6810 utf8_fold_flags = 0;
6813 case NREF: /* /\g{name}/ */
6817 utf8_fold_flags = 0;
6820 /* For the named back references, find the corresponding buffer
6822 n = reg_check_named_buff_matched(rex,scan);
6827 goto do_nref_ref_common;
6829 case REFFL: /* /\1/il */
6830 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6831 folder = foldEQ_locale;
6832 fold_array = PL_fold_locale;
6833 utf8_fold_flags = FOLDEQ_LOCALE;
6836 case REFFA: /* /\1/iaa */
6837 folder = foldEQ_latin1;
6838 fold_array = PL_fold_latin1;
6839 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6842 case REFFU: /* /\1/iu */
6843 folder = foldEQ_latin1;
6844 fold_array = PL_fold_latin1;
6845 utf8_fold_flags = 0;
6848 case REFF: /* /\1/i */
6850 fold_array = PL_fold;
6851 utf8_fold_flags = 0;
6854 case REF: /* /\1/ */
6857 utf8_fold_flags = 0;
6861 n = ARG(scan); /* which paren pair */
6864 ln = rex->offs[n].start;
6865 endref = rex->offs[n].end;
6866 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6867 if (rex->lastparen < n || ln == -1 || endref == -1)
6868 sayNO; /* Do not match unless seen CLOSEn. */
6872 s = reginfo->strbeg + ln;
6873 if (type != REF /* REF can do byte comparison */
6874 && (utf8_target || type == REFFU || type == REFFL))
6876 char * limit = reginfo->strend;
6878 /* This call case insensitively compares the entire buffer
6879 * at s, with the current input starting at locinput, but
6880 * not going off the end given by reginfo->strend, and
6881 * returns in <limit> upon success, how much of the
6882 * current input was matched */
6883 if (! foldEQ_utf8_flags(s, NULL, endref - ln, utf8_target,
6884 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6892 /* Not utf8: Inline the first character, for speed. */
6893 if (!NEXTCHR_IS_EOS &&
6894 UCHARAT(s) != nextchr &&
6896 UCHARAT(s) != fold_array[nextchr]))
6899 if (locinput + ln > reginfo->strend)
6901 if (ln > 1 && (type == REF
6902 ? memNE(s, locinput, ln)
6903 : ! folder(s, locinput, ln)))
6909 case NOTHING: /* null op; e.g. the 'nothing' following
6910 * the '*' in m{(a+|b)*}' */
6912 case TAIL: /* placeholder while compiling (A|B|C) */
6916 #define ST st->u.eval
6917 #define CUR_EVAL cur_eval->u.eval
6923 regexp_internal *rei;
6924 regnode *startpoint;
6927 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6928 arg= (U32)ARG(scan);
6929 if (cur_eval && cur_eval->locinput == locinput) {
6930 if ( ++nochange_depth > max_nochange_depth )
6932 "Pattern subroutine nesting without pos change"
6933 " exceeded limit in regex");
6940 startpoint = scan + ARG2L(scan);
6941 EVAL_CLOSE_PAREN_SET( st, arg );
6942 /* Detect infinite recursion
6944 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
6945 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
6946 * So we track the position in the string we are at each time
6947 * we recurse and if we try to enter the same routine twice from
6948 * the same position we throw an error.
6950 if ( rex->recurse_locinput[arg] == locinput ) {
6951 /* FIXME: we should show the regop that is failing as part
6952 * of the error message. */
6953 Perl_croak(aTHX_ "Infinite recursion in regex");
6955 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
6956 rex->recurse_locinput[arg]= locinput;
6959 GET_RE_DEBUG_FLAGS_DECL;
6961 Perl_re_exec_indentf( aTHX_
6962 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
6963 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
6969 /* Save all the positions seen so far. */
6970 ST.cp = regcppush(rex, 0, maxopenparen);
6971 REGCP_SET(ST.lastcp);
6973 /* and then jump to the code we share with EVAL */
6974 goto eval_recurse_doit;
6977 case EVAL: /* /(?{...})B/ /(??{A})B/ and /(?(?{...})X|Y)B/ */
6978 if (cur_eval && cur_eval->locinput==locinput) {
6979 if ( ++nochange_depth > max_nochange_depth )
6980 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6985 /* execute the code in the {...} */
6989 OP * const oop = PL_op;
6990 COP * const ocurcop = PL_curcop;
6994 /* save *all* paren positions */
6995 regcppush(rex, 0, maxopenparen);
6996 REGCP_SET(ST.lastcp);
6999 caller_cv = find_runcv(NULL);
7003 if (rexi->data->what[n] == 'r') { /* code from an external qr */
7005 (REGEXP*)(rexi->data->data[n])
7007 nop = (OP*)rexi->data->data[n+1];
7009 else if (rexi->data->what[n] == 'l') { /* literal code */
7011 nop = (OP*)rexi->data->data[n];
7012 assert(CvDEPTH(newcv));
7015 /* literal with own CV */
7016 assert(rexi->data->what[n] == 'L');
7017 newcv = rex->qr_anoncv;
7018 nop = (OP*)rexi->data->data[n];
7021 /* Some notes about MULTICALL and the context and save stacks.
7024 * /...(?{ my $x)}...(?{ my $y)}...(?{ my $z)}.../
7025 * since codeblocks don't introduce a new scope (so that
7026 * local() etc accumulate), at the end of a successful
7027 * match there will be a SAVEt_CLEARSV on the savestack
7028 * for each of $x, $y, $z. If the three code blocks above
7029 * happen to have come from different CVs (e.g. via
7030 * embedded qr//s), then we must ensure that during any
7031 * savestack unwinding, PL_comppad always points to the
7032 * right pad at each moment. We achieve this by
7033 * interleaving SAVEt_COMPPAD's on the savestack whenever
7034 * there is a change of pad.
7035 * In theory whenever we call a code block, we should
7036 * push a CXt_SUB context, then pop it on return from
7037 * that code block. This causes a bit of an issue in that
7038 * normally popping a context also clears the savestack
7039 * back to cx->blk_oldsaveix, but here we specifically
7040 * don't want to clear the save stack on exit from the
7042 * Also for efficiency we don't want to keep pushing and
7043 * popping the single SUB context as we backtrack etc.
7044 * So instead, we push a single context the first time
7045 * we need, it, then hang onto it until the end of this
7046 * function. Whenever we encounter a new code block, we
7047 * update the CV etc if that's changed. During the times
7048 * in this function where we're not executing a code
7049 * block, having the SUB context still there is a bit
7050 * naughty - but we hope that no-one notices.
7051 * When the SUB context is initially pushed, we fake up
7052 * cx->blk_oldsaveix to be as if we'd pushed this context
7053 * on first entry to S_regmatch rather than at some random
7054 * point during the regexe execution. That way if we
7055 * croak, popping the context stack will ensure that
7056 * *everything* SAVEd by this function is undone and then
7057 * the context popped, rather than e.g., popping the
7058 * context (and restoring the original PL_comppad) then
7059 * popping more of the savestack and restoring a bad
7063 /* If this is the first EVAL, push a MULTICALL. On
7064 * subsequent calls, if we're executing a different CV, or
7065 * if PL_comppad has got messed up from backtracking
7066 * through SAVECOMPPADs, then refresh the context.
7068 if (newcv != last_pushed_cv || PL_comppad != last_pad)
7070 U8 flags = (CXp_SUB_RE |
7071 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
7073 if (last_pushed_cv) {
7074 CHANGE_MULTICALL_FLAGS(newcv, flags);
7077 PUSH_MULTICALL_FLAGS(newcv, flags);
7079 /* see notes above */
7080 CX_CUR()->blk_oldsaveix = orig_savestack_ix;
7082 last_pushed_cv = newcv;
7085 /* these assignments are just to silence compiler
7087 multicall_cop = NULL;
7089 last_pad = PL_comppad;
7091 /* the initial nextstate you would normally execute
7092 * at the start of an eval (which would cause error
7093 * messages to come from the eval), may be optimised
7094 * away from the execution path in the regex code blocks;
7095 * so manually set PL_curcop to it initially */
7097 OP *o = cUNOPx(nop)->op_first;
7098 assert(o->op_type == OP_NULL);
7099 if (o->op_targ == OP_SCOPE) {
7100 o = cUNOPo->op_first;
7103 assert(o->op_targ == OP_LEAVE);
7104 o = cUNOPo->op_first;
7105 assert(o->op_type == OP_ENTER);
7109 if (o->op_type != OP_STUB) {
7110 assert( o->op_type == OP_NEXTSTATE
7111 || o->op_type == OP_DBSTATE
7112 || (o->op_type == OP_NULL
7113 && ( o->op_targ == OP_NEXTSTATE
7114 || o->op_targ == OP_DBSTATE
7118 PL_curcop = (COP*)o;
7123 DEBUG_STATE_r( Perl_re_printf( aTHX_
7124 " re EVAL PL_op=0x%" UVxf "\n", PTR2UV(nop)) );
7126 rex->offs[0].end = locinput - reginfo->strbeg;
7127 if (reginfo->info_aux_eval->pos_magic)
7128 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
7129 reginfo->sv, reginfo->strbeg,
7130 locinput - reginfo->strbeg);
7133 SV *sv_mrk = get_sv("REGMARK", 1);
7134 sv_setsv(sv_mrk, sv_yes_mark);
7137 /* we don't use MULTICALL here as we want to call the
7138 * first op of the block of interest, rather than the
7139 * first op of the sub. Also, we don't want to free
7140 * the savestack frame */
7141 before = (IV)(SP-PL_stack_base);
7143 CALLRUNOPS(aTHX); /* Scalar context. */
7145 if ((IV)(SP-PL_stack_base) == before)
7146 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
7152 /* before restoring everything, evaluate the returned
7153 * value, so that 'uninit' warnings don't use the wrong
7154 * PL_op or pad. Also need to process any magic vars
7155 * (e.g. $1) *before* parentheses are restored */
7160 if (logical == 0) /* (?{})/ */
7161 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
7162 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
7163 sw = cBOOL(SvTRUE_NN(ret));
7166 else { /* /(??{}) */
7167 /* if its overloaded, let the regex compiler handle
7168 * it; otherwise extract regex, or stringify */
7169 if (SvGMAGICAL(ret))
7170 ret = sv_mortalcopy(ret);
7171 if (!SvAMAGIC(ret)) {
7175 if (SvTYPE(sv) == SVt_REGEXP)
7176 re_sv = (REGEXP*) sv;
7177 else if (SvSMAGICAL(ret)) {
7178 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
7180 re_sv = (REGEXP *) mg->mg_obj;
7183 /* force any undef warnings here */
7184 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
7185 ret = sv_mortalcopy(ret);
7186 (void) SvPV_force_nolen(ret);
7192 /* *** Note that at this point we don't restore
7193 * PL_comppad, (or pop the CxSUB) on the assumption it may
7194 * be used again soon. This is safe as long as nothing
7195 * in the regexp code uses the pad ! */
7197 PL_curcop = ocurcop;
7198 regcp_restore(rex, ST.lastcp, &maxopenparen);
7199 PL_curpm_under = PL_curpm;
7200 PL_curpm = PL_reg_curpm;
7203 PUSH_STATE_GOTO(EVAL_B, next, locinput);
7208 /* only /(??{})/ from now on */
7211 /* extract RE object from returned value; compiling if
7215 re_sv = reg_temp_copy(NULL, re_sv);
7220 if (SvUTF8(ret) && IN_BYTES) {
7221 /* In use 'bytes': make a copy of the octet
7222 * sequence, but without the flag on */
7224 const char *const p = SvPV(ret, len);
7225 ret = newSVpvn_flags(p, len, SVs_TEMP);
7227 if (rex->intflags & PREGf_USE_RE_EVAL)
7228 pm_flags |= PMf_USE_RE_EVAL;
7230 /* if we got here, it should be an engine which
7231 * supports compiling code blocks and stuff */
7232 assert(rex->engine && rex->engine->op_comp);
7233 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
7234 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
7235 rex->engine, NULL, NULL,
7236 /* copy /msixn etc to inner pattern */
7241 & (SVs_TEMP | SVs_GMG | SVf_ROK))
7242 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
7243 /* This isn't a first class regexp. Instead, it's
7244 caching a regexp onto an existing, Perl visible
7246 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
7252 RXp_MATCH_COPIED_off(re);
7253 re->subbeg = rex->subbeg;
7254 re->sublen = rex->sublen;
7255 re->suboffset = rex->suboffset;
7256 re->subcoffset = rex->subcoffset;
7258 re->lastcloseparen = 0;
7261 debug_start_match(re_sv, utf8_target, locinput,
7262 reginfo->strend, "Matching embedded");
7264 startpoint = rei->program + 1;
7265 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7266 * close_paren only for GOSUB */
7267 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7268 /* Save all the seen positions so far. */
7269 ST.cp = regcppush(rex, 0, maxopenparen);
7270 REGCP_SET(ST.lastcp);
7271 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7273 /* run the pattern returned from (??{...}) */
7275 eval_recurse_doit: /* Share code with GOSUB below this line
7276 * At this point we expect the stack context to be
7277 * set up correctly */
7279 /* invalidate the S-L poscache. We're now executing a
7280 * different set of WHILEM ops (and their associated
7281 * indexes) against the same string, so the bits in the
7282 * cache are meaningless. Setting maxiter to zero forces
7283 * the cache to be invalidated and zeroed before reuse.
7284 * XXX This is too dramatic a measure. Ideally we should
7285 * save the old cache and restore when running the outer
7287 reginfo->poscache_maxiter = 0;
7289 /* the new regexp might have a different is_utf8_pat than we do */
7290 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7292 ST.prev_rex = rex_sv;
7293 ST.prev_curlyx = cur_curlyx;
7295 SET_reg_curpm(rex_sv);
7300 ST.prev_eval = cur_eval;
7302 /* now continue from first node in postoned RE */
7303 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, startpoint, locinput);
7304 NOT_REACHED; /* NOTREACHED */
7307 case EVAL_postponed_AB: /* cleanup after a successful (??{A})B */
7308 /* note: this is called twice; first after popping B, then A */
7310 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7311 depth, cur_eval, ST.prev_eval);
7314 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7315 if ( cur_eval && CUR_EVAL.close_paren ) {\
7317 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7319 CUR_EVAL.close_paren - 1,\
7323 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7326 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7328 rex_sv = ST.prev_rex;
7329 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7330 SET_reg_curpm(rex_sv);
7331 rex = ReANY(rex_sv);
7332 rexi = RXi_GET(rex);
7334 /* preserve $^R across LEAVE's. See Bug 121070. */
7335 SV *save_sv= GvSV(PL_replgv);
7336 SvREFCNT_inc(save_sv);
7337 regcpblow(ST.cp); /* LEAVE in disguise */
7338 sv_setsv(GvSV(PL_replgv), save_sv);
7339 SvREFCNT_dec(save_sv);
7341 cur_eval = ST.prev_eval;
7342 cur_curlyx = ST.prev_curlyx;
7344 /* Invalidate cache. See "invalidate" comment above. */
7345 reginfo->poscache_maxiter = 0;
7346 if ( nochange_depth )
7349 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7353 case EVAL_B_fail: /* unsuccessful B in (?{...})B */
7354 REGCP_UNWIND(ST.lastcp);
7357 case EVAL_postponed_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7358 /* note: this is called twice; first after popping B, then A */
7360 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7361 depth, cur_eval, ST.prev_eval);
7364 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7366 rex_sv = ST.prev_rex;
7367 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7368 SET_reg_curpm(rex_sv);
7369 rex = ReANY(rex_sv);
7370 rexi = RXi_GET(rex);
7372 REGCP_UNWIND(ST.lastcp);
7373 regcppop(rex, &maxopenparen);
7374 cur_eval = ST.prev_eval;
7375 cur_curlyx = ST.prev_curlyx;
7377 /* Invalidate cache. See "invalidate" comment above. */
7378 reginfo->poscache_maxiter = 0;
7379 if ( nochange_depth )
7382 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7387 n = ARG(scan); /* which paren pair */
7388 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7389 if (n > maxopenparen)
7391 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
7392 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf " tmp; maxopenparen=%" UVuf "\n",
7397 (IV)rex->offs[n].start_tmp,
7403 case SROPEN: /* (*SCRIPT_RUN: */
7404 script_run_begin = (U8 *) locinput;
7407 /* XXX really need to log other places start/end are set too */
7408 #define CLOSE_CAPTURE \
7409 rex->offs[n].start = rex->offs[n].start_tmp; \
7410 rex->offs[n].end = locinput - reginfo->strbeg; \
7411 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
7412 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf "\n", \
7415 PTR2UV(rex->offs), \
7417 (IV)rex->offs[n].start, \
7418 (IV)rex->offs[n].end \
7422 n = ARG(scan); /* which paren pair */
7424 if (n > rex->lastparen)
7426 rex->lastcloseparen = n;
7427 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7432 case SRCLOSE: /* (*SCRIPT_RUN: ... ) */
7434 if (! isSCRIPT_RUN(script_run_begin, (U8 *) locinput, utf8_target))
7442 case ACCEPT: /* (*ACCEPT) */
7444 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7448 cursor && OP(cursor)!=END;
7449 cursor=regnext(cursor))
7451 if ( OP(cursor)==CLOSE ){
7453 if ( n <= lastopen ) {
7455 if (n > rex->lastparen)
7457 rex->lastcloseparen = n;
7458 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7467 case GROUPP: /* (?(1)) */
7468 n = ARG(scan); /* which paren pair */
7469 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7472 case NGROUPP: /* (?(<name>)) */
7473 /* reg_check_named_buff_matched returns 0 for no match */
7474 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7477 case INSUBP: /* (?(R)) */
7479 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7480 * of SCAN is already set up as matches a eval.close_paren */
7481 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7484 case DEFINEP: /* (?(DEFINE)) */
7488 case IFTHEN: /* (?(cond)A|B) */
7489 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7491 next = NEXTOPER(NEXTOPER(scan));
7493 next = scan + ARG(scan);
7494 if (OP(next) == IFTHEN) /* Fake one. */
7495 next = NEXTOPER(NEXTOPER(next));
7499 case LOGICAL: /* modifier for EVAL and IFMATCH */
7500 logical = scan->flags;
7503 /*******************************************************************
7505 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7506 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7507 STAR/PLUS/CURLY/CURLYN are used instead.)
7509 A*B is compiled as <CURLYX><A><WHILEM><B>
7511 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7512 state, which contains the current count, initialised to -1. It also sets
7513 cur_curlyx to point to this state, with any previous value saved in the
7516 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7517 since the pattern may possibly match zero times (i.e. it's a while {} loop
7518 rather than a do {} while loop).
7520 Each entry to WHILEM represents a successful match of A. The count in the
7521 CURLYX block is incremented, another WHILEM state is pushed, and execution
7522 passes to A or B depending on greediness and the current count.
7524 For example, if matching against the string a1a2a3b (where the aN are
7525 substrings that match /A/), then the match progresses as follows: (the
7526 pushed states are interspersed with the bits of strings matched so far):
7529 <CURLYX cnt=0><WHILEM>
7530 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7531 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7532 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7533 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7535 (Contrast this with something like CURLYM, which maintains only a single
7539 a1 <CURLYM cnt=1> a2
7540 a1 a2 <CURLYM cnt=2> a3
7541 a1 a2 a3 <CURLYM cnt=3> b
7544 Each WHILEM state block marks a point to backtrack to upon partial failure
7545 of A or B, and also contains some minor state data related to that
7546 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7547 overall state, such as the count, and pointers to the A and B ops.
7549 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7550 must always point to the *current* CURLYX block, the rules are:
7552 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7553 and set cur_curlyx to point the new block.
7555 When popping the CURLYX block after a successful or unsuccessful match,
7556 restore the previous cur_curlyx.
7558 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7559 to the outer one saved in the CURLYX block.
7561 When popping the WHILEM block after a successful or unsuccessful B match,
7562 restore the previous cur_curlyx.
7564 Here's an example for the pattern (AI* BI)*BO
7565 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7568 curlyx backtrack stack
7569 ------ ---------------
7571 CO <CO prev=NULL> <WO>
7572 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7573 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7574 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7576 At this point the pattern succeeds, and we work back down the stack to
7577 clean up, restoring as we go:
7579 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7580 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7581 CO <CO prev=NULL> <WO>
7584 *******************************************************************/
7586 #define ST st->u.curlyx
7588 case CURLYX: /* start of /A*B/ (for complex A) */
7590 /* No need to save/restore up to this paren */
7591 I32 parenfloor = scan->flags;
7593 assert(next); /* keep Coverity happy */
7594 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7597 /* XXXX Probably it is better to teach regpush to support
7598 parenfloor > maxopenparen ... */
7599 if (parenfloor > (I32)rex->lastparen)
7600 parenfloor = rex->lastparen; /* Pessimization... */
7602 ST.prev_curlyx= cur_curlyx;
7604 ST.cp = PL_savestack_ix;
7606 /* these fields contain the state of the current curly.
7607 * they are accessed by subsequent WHILEMs */
7608 ST.parenfloor = parenfloor;
7613 ST.count = -1; /* this will be updated by WHILEM */
7614 ST.lastloc = NULL; /* this will be updated by WHILEM */
7616 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7617 NOT_REACHED; /* NOTREACHED */
7620 case CURLYX_end: /* just finished matching all of A*B */
7621 cur_curlyx = ST.prev_curlyx;
7623 NOT_REACHED; /* NOTREACHED */
7625 case CURLYX_end_fail: /* just failed to match all of A*B */
7627 cur_curlyx = ST.prev_curlyx;
7629 NOT_REACHED; /* NOTREACHED */
7633 #define ST st->u.whilem
7635 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7637 /* see the discussion above about CURLYX/WHILEM */
7642 assert(cur_curlyx); /* keep Coverity happy */
7644 min = ARG1(cur_curlyx->u.curlyx.me);
7645 max = ARG2(cur_curlyx->u.curlyx.me);
7646 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7647 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7648 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7649 ST.cache_offset = 0;
7653 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: matched %ld out of %d..%d\n",
7654 depth, (long)n, min, max)
7657 /* First just match a string of min A's. */
7660 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor, maxopenparen);
7661 cur_curlyx->u.curlyx.lastloc = locinput;
7662 REGCP_SET(ST.lastcp);
7664 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7665 NOT_REACHED; /* NOTREACHED */
7668 /* If degenerate A matches "", assume A done. */
7670 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7671 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: empty match detected, trying continuation...\n",
7674 goto do_whilem_B_max;
7677 /* super-linear cache processing.
7679 * The idea here is that for certain types of CURLYX/WHILEM -
7680 * principally those whose upper bound is infinity (and
7681 * excluding regexes that have things like \1 and other very
7682 * non-regular expresssiony things), then if a pattern like
7683 * /....A*.../ fails and we backtrack to the WHILEM, then we
7684 * make a note that this particular WHILEM op was at string
7685 * position 47 (say) when the rest of pattern failed. Then, if
7686 * we ever find ourselves back at that WHILEM, and at string
7687 * position 47 again, we can just fail immediately rather than
7688 * running the rest of the pattern again.
7690 * This is very handy when patterns start to go
7691 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7692 * with a combinatorial explosion of backtracking.
7694 * The cache is implemented as a bit array, with one bit per
7695 * string byte position per WHILEM op (up to 16) - so its
7696 * between 0.25 and 2x the string size.
7698 * To avoid allocating a poscache buffer every time, we do an
7699 * initially countdown; only after we have executed a WHILEM
7700 * op (string-length x #WHILEMs) times do we allocate the
7703 * The top 4 bits of scan->flags byte say how many different
7704 * relevant CURLLYX/WHILEM op pairs there are, while the
7705 * bottom 4-bits is the identifying index number of this
7711 if (!reginfo->poscache_maxiter) {
7712 /* start the countdown: Postpone detection until we
7713 * know the match is not *that* much linear. */
7714 reginfo->poscache_maxiter
7715 = (reginfo->strend - reginfo->strbeg + 1)
7717 /* possible overflow for long strings and many CURLYX's */
7718 if (reginfo->poscache_maxiter < 0)
7719 reginfo->poscache_maxiter = I32_MAX;
7720 reginfo->poscache_iter = reginfo->poscache_maxiter;
7723 if (reginfo->poscache_iter-- == 0) {
7724 /* initialise cache */
7725 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7726 regmatch_info_aux *const aux = reginfo->info_aux;
7727 if (aux->poscache) {
7728 if ((SSize_t)reginfo->poscache_size < size) {
7729 Renew(aux->poscache, size, char);
7730 reginfo->poscache_size = size;
7732 Zero(aux->poscache, size, char);
7735 reginfo->poscache_size = size;
7736 Newxz(aux->poscache, size, char);
7738 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7739 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7740 PL_colors[4], PL_colors[5])
7744 if (reginfo->poscache_iter < 0) {
7745 /* have we already failed at this position? */
7746 SSize_t offset, mask;
7748 reginfo->poscache_iter = -1; /* stop eventual underflow */
7749 offset = (scan->flags & 0xf) - 1
7750 + (locinput - reginfo->strbeg)
7752 mask = 1 << (offset % 8);
7754 if (reginfo->info_aux->poscache[offset] & mask) {
7755 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: (cache) already tried at this position...\n",
7758 cur_curlyx->u.curlyx.count--;
7759 sayNO; /* cache records failure */
7761 ST.cache_offset = offset;
7762 ST.cache_mask = mask;
7766 /* Prefer B over A for minimal matching. */
7768 if (cur_curlyx->u.curlyx.minmod) {
7769 ST.save_curlyx = cur_curlyx;
7770 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7771 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7773 NOT_REACHED; /* NOTREACHED */
7776 /* Prefer A over B for maximal matching. */
7778 if (n < max) { /* More greed allowed? */
7779 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7781 cur_curlyx->u.curlyx.lastloc = locinput;
7782 REGCP_SET(ST.lastcp);
7783 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7784 NOT_REACHED; /* NOTREACHED */
7786 goto do_whilem_B_max;
7788 NOT_REACHED; /* NOTREACHED */
7790 case WHILEM_B_min: /* just matched B in a minimal match */
7791 case WHILEM_B_max: /* just matched B in a maximal match */
7792 cur_curlyx = ST.save_curlyx;
7794 NOT_REACHED; /* NOTREACHED */
7796 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7797 cur_curlyx = ST.save_curlyx;
7798 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7799 cur_curlyx->u.curlyx.count--;
7801 NOT_REACHED; /* NOTREACHED */
7803 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7804 REGCP_UNWIND(ST.lastcp);
7805 regcppop(rex, &maxopenparen);
7807 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7808 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7809 cur_curlyx->u.curlyx.count--;
7811 NOT_REACHED; /* NOTREACHED */
7813 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7814 REGCP_UNWIND(ST.lastcp);
7815 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7816 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "whilem: failed, trying continuation...\n",
7820 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7821 && ckWARN(WARN_REGEXP)
7822 && !reginfo->warned)
7824 reginfo->warned = TRUE;
7825 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7826 "Complex regular subexpression recursion limit (%d) "
7832 ST.save_curlyx = cur_curlyx;
7833 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7834 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7836 NOT_REACHED; /* NOTREACHED */
7838 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7839 cur_curlyx = ST.save_curlyx;
7841 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7842 /* Maximum greed exceeded */
7843 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7844 && ckWARN(WARN_REGEXP)
7845 && !reginfo->warned)
7847 reginfo->warned = TRUE;
7848 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7849 "Complex regular subexpression recursion "
7850 "limit (%d) exceeded",
7853 cur_curlyx->u.curlyx.count--;
7857 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "trying longer...\n", depth)
7859 /* Try grabbing another A and see if it helps. */
7860 cur_curlyx->u.curlyx.lastloc = locinput;
7861 PUSH_STATE_GOTO(WHILEM_A_min,
7862 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7864 NOT_REACHED; /* NOTREACHED */
7867 #define ST st->u.branch
7869 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7870 next = scan + ARG(scan);
7873 scan = NEXTOPER(scan);
7876 case BRANCH: /* /(...|A|...)/ */
7877 scan = NEXTOPER(scan); /* scan now points to inner node */
7878 ST.lastparen = rex->lastparen;
7879 ST.lastcloseparen = rex->lastcloseparen;
7880 ST.next_branch = next;
7883 /* Now go into the branch */
7885 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7887 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7889 NOT_REACHED; /* NOTREACHED */
7891 case CUTGROUP: /* /(*THEN)/ */
7892 sv_yes_mark = st->u.mark.mark_name = scan->flags
7893 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7895 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7896 NOT_REACHED; /* NOTREACHED */
7898 case CUTGROUP_next_fail:
7901 if (st->u.mark.mark_name)
7902 sv_commit = st->u.mark.mark_name;
7904 NOT_REACHED; /* NOTREACHED */
7908 NOT_REACHED; /* NOTREACHED */
7910 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7915 REGCP_UNWIND(ST.cp);
7916 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7917 scan = ST.next_branch;
7918 /* no more branches? */
7919 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7921 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
7928 continue; /* execute next BRANCH[J] op */
7931 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7936 #define ST st->u.curlym
7938 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7940 /* This is an optimisation of CURLYX that enables us to push
7941 * only a single backtracking state, no matter how many matches
7942 * there are in {m,n}. It relies on the pattern being constant
7943 * length, with no parens to influence future backrefs
7947 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7949 ST.lastparen = rex->lastparen;
7950 ST.lastcloseparen = rex->lastcloseparen;
7952 /* if paren positive, emulate an OPEN/CLOSE around A */
7954 U32 paren = ST.me->flags;
7955 if (paren > maxopenparen)
7956 maxopenparen = paren;
7957 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7965 ST.c1 = CHRTEST_UNINIT;
7968 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7971 curlym_do_A: /* execute the A in /A{m,n}B/ */
7972 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7973 NOT_REACHED; /* NOTREACHED */
7975 case CURLYM_A: /* we've just matched an A */
7977 /* after first match, determine A's length: u.curlym.alen */
7978 if (ST.count == 1) {
7979 if (reginfo->is_utf8_target) {
7980 char *s = st->locinput;
7981 while (s < locinput) {
7987 ST.alen = locinput - st->locinput;
7990 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7993 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %" IVdf " times, len=%" IVdf "...\n",
7994 depth, (IV) ST.count, (IV)ST.alen)
7997 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8001 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
8002 if ( max == REG_INFTY || ST.count < max )
8003 goto curlym_do_A; /* try to match another A */
8005 goto curlym_do_B; /* try to match B */
8007 case CURLYM_A_fail: /* just failed to match an A */
8008 REGCP_UNWIND(ST.cp);
8011 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
8012 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8015 curlym_do_B: /* execute the B in /A{m,n}B/ */
8016 if (ST.c1 == CHRTEST_UNINIT) {
8017 /* calculate c1 and c2 for possible match of 1st char
8018 * following curly */
8019 ST.c1 = ST.c2 = CHRTEST_VOID;
8021 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
8022 regnode *text_node = ST.B;
8023 if (! HAS_TEXT(text_node))
8024 FIND_NEXT_IMPT(text_node);
8027 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
8029 But the former is redundant in light of the latter.
8031 if this changes back then the macro for
8032 IS_TEXT and friends need to change.
8034 if (PL_regkind[OP(text_node)] == EXACT) {
8035 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8036 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8046 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%" IVdf "...\n",
8047 depth, (IV)ST.count)
8049 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
8050 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
8051 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8052 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8054 /* simulate B failing */
8056 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%" UVXf " c1=0x%" UVXf " c2=0x%" UVXf "\n",
8058 valid_utf8_to_uvchr((U8 *) locinput, NULL),
8059 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
8060 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
8062 state_num = CURLYM_B_fail;
8063 goto reenter_switch;
8066 else if (nextchr != ST.c1 && nextchr != ST.c2) {
8067 /* simulate B failing */
8069 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
8071 (int) nextchr, ST.c1, ST.c2)
8073 state_num = CURLYM_B_fail;
8074 goto reenter_switch;
8079 /* emulate CLOSE: mark current A as captured */
8080 I32 paren = ST.me->flags;
8082 rex->offs[paren].start
8083 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
8084 rex->offs[paren].end = locinput - reginfo->strbeg;
8085 if ((U32)paren > rex->lastparen)
8086 rex->lastparen = paren;
8087 rex->lastcloseparen = paren;
8090 rex->offs[paren].end = -1;
8092 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8101 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
8102 NOT_REACHED; /* NOTREACHED */
8104 case CURLYM_B_fail: /* just failed to match a B */
8105 REGCP_UNWIND(ST.cp);
8106 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8108 I32 max = ARG2(ST.me);
8109 if (max != REG_INFTY && ST.count == max)
8111 goto curlym_do_A; /* try to match a further A */
8113 /* backtrack one A */
8114 if (ST.count == ARG1(ST.me) /* min */)
8117 SET_locinput(HOPc(locinput, -ST.alen));
8118 goto curlym_do_B; /* try to match B */
8121 #define ST st->u.curly
8123 #define CURLY_SETPAREN(paren, success) \
8126 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
8127 rex->offs[paren].end = locinput - reginfo->strbeg; \
8128 if (paren > rex->lastparen) \
8129 rex->lastparen = paren; \
8130 rex->lastcloseparen = paren; \
8133 rex->offs[paren].end = -1; \
8134 rex->lastparen = ST.lastparen; \
8135 rex->lastcloseparen = ST.lastcloseparen; \
8139 case STAR: /* /A*B/ where A is width 1 char */
8143 scan = NEXTOPER(scan);
8146 case PLUS: /* /A+B/ where A is width 1 char */
8150 scan = NEXTOPER(scan);
8153 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
8154 ST.paren = scan->flags; /* Which paren to set */
8155 ST.lastparen = rex->lastparen;
8156 ST.lastcloseparen = rex->lastcloseparen;
8157 if (ST.paren > maxopenparen)
8158 maxopenparen = ST.paren;
8159 ST.min = ARG1(scan); /* min to match */
8160 ST.max = ARG2(scan); /* max to match */
8161 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8166 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
8169 case CURLY: /* /A{m,n}B/ where A is width 1 char */
8171 ST.min = ARG1(scan); /* min to match */
8172 ST.max = ARG2(scan); /* max to match */
8173 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
8176 * Lookahead to avoid useless match attempts
8177 * when we know what character comes next.
8179 * Used to only do .*x and .*?x, but now it allows
8180 * for )'s, ('s and (?{ ... })'s to be in the way
8181 * of the quantifier and the EXACT-like node. -- japhy
8184 assert(ST.min <= ST.max);
8185 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
8186 ST.c1 = ST.c2 = CHRTEST_VOID;
8189 regnode *text_node = next;
8191 if (! HAS_TEXT(text_node))
8192 FIND_NEXT_IMPT(text_node);
8194 if (! HAS_TEXT(text_node))
8195 ST.c1 = ST.c2 = CHRTEST_VOID;
8197 if ( PL_regkind[OP(text_node)] != EXACT ) {
8198 ST.c1 = ST.c2 = CHRTEST_VOID;
8202 /* Currently we only get here when
8204 PL_rekind[OP(text_node)] == EXACT
8206 if this changes back then the macro for IS_TEXT and
8207 friends need to change. */
8208 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8209 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8221 char *li = locinput;
8224 regrepeat(rex, &li, ST.A, reginfo, ST.min)
8230 if (ST.c1 == CHRTEST_VOID)
8231 goto curly_try_B_min;
8233 ST.oldloc = locinput;
8235 /* set ST.maxpos to the furthest point along the
8236 * string that could possibly match */
8237 if (ST.max == REG_INFTY) {
8238 ST.maxpos = reginfo->strend - 1;
8240 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
8243 else if (utf8_target) {
8244 int m = ST.max - ST.min;
8245 for (ST.maxpos = locinput;
8246 m >0 && ST.maxpos < reginfo->strend; m--)
8247 ST.maxpos += UTF8SKIP(ST.maxpos);
8250 ST.maxpos = locinput + ST.max - ST.min;
8251 if (ST.maxpos >= reginfo->strend)
8252 ST.maxpos = reginfo->strend - 1;
8254 goto curly_try_B_min_known;
8258 /* avoid taking address of locinput, so it can remain
8260 char *li = locinput;
8261 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max);
8262 if (ST.count < ST.min)
8265 if ((ST.count > ST.min)
8266 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
8268 /* A{m,n} must come at the end of the string, there's
8269 * no point in backing off ... */
8271 /* ...except that $ and \Z can match before *and* after
8272 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8273 We may back off by one in this case. */
8274 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8278 goto curly_try_B_max;
8280 NOT_REACHED; /* NOTREACHED */
8282 case CURLY_B_min_known_fail:
8283 /* failed to find B in a non-greedy match where c1,c2 valid */
8285 REGCP_UNWIND(ST.cp);
8287 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8289 /* Couldn't or didn't -- move forward. */
8290 ST.oldloc = locinput;
8292 locinput += UTF8SKIP(locinput);
8296 curly_try_B_min_known:
8297 /* find the next place where 'B' could work, then call B */
8301 n = (ST.oldloc == locinput) ? 0 : 1;
8302 if (ST.c1 == ST.c2) {
8303 /* set n to utf8_distance(oldloc, locinput) */
8304 while (locinput <= ST.maxpos
8305 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8307 locinput += UTF8SKIP(locinput);
8312 /* set n to utf8_distance(oldloc, locinput) */
8313 while (locinput <= ST.maxpos
8314 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8315 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8317 locinput += UTF8SKIP(locinput);
8322 else { /* Not utf8_target */
8323 if (ST.c1 == ST.c2) {
8324 locinput = (char *) memchr(locinput,
8326 ST.maxpos + 1 - locinput);
8328 locinput = ST.maxpos + 1;
8332 U8 c1_c2_bits_differing = ST.c1 ^ ST.c2;
8334 if (! isPOWER_OF_2(c1_c2_bits_differing)) {
8335 while ( locinput <= ST.maxpos
8336 && UCHARAT(locinput) != ST.c1
8337 && UCHARAT(locinput) != ST.c2)
8343 /* If c1 and c2 only differ by a single bit, we can
8344 * avoid a conditional each time through the loop,
8345 * at the expense of a little preliminary setup and
8346 * an extra mask each iteration. By masking out
8347 * that bit, we match exactly two characters, c1
8348 * and c2, and so we don't have to test for both.
8349 * On both ASCII and EBCDIC platforms, most of the
8350 * ASCII-range and Latin1-range folded equivalents
8351 * differ only in a single bit, so this is actually
8352 * the most common case. (e.g. 'A' 0x41 vs 'a'
8354 U8 c1_masked = ST.c1 &~ c1_c2_bits_differing;
8355 U8 c1_c2_mask = ~ c1_c2_bits_differing;
8356 while ( locinput <= ST.maxpos
8357 && (UCHARAT(locinput) & c1_c2_mask)
8364 n = locinput - ST.oldloc;
8366 if (locinput > ST.maxpos)
8369 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8370 * at b; check that everything between oldloc and
8371 * locinput matches */
8372 char *li = ST.oldloc;
8374 if (regrepeat(rex, &li, ST.A, reginfo, n) < n)
8376 assert(n == REG_INFTY || locinput == li);
8378 CURLY_SETPAREN(ST.paren, ST.count);
8379 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8381 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8383 NOT_REACHED; /* NOTREACHED */
8385 case CURLY_B_min_fail:
8386 /* failed to find B in a non-greedy match where c1,c2 invalid */
8388 REGCP_UNWIND(ST.cp);
8390 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8392 /* failed -- move forward one */
8394 char *li = locinput;
8395 if (!regrepeat(rex, &li, ST.A, reginfo, 1)) {
8402 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8403 ST.count > 0)) /* count overflow ? */
8406 CURLY_SETPAREN(ST.paren, ST.count);
8407 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8409 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8413 NOT_REACHED; /* NOTREACHED */
8416 /* a successful greedy match: now try to match B */
8417 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8420 bool could_match = locinput < reginfo->strend;
8422 /* If it could work, try it. */
8423 if (ST.c1 != CHRTEST_VOID && could_match) {
8424 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8426 could_match = memEQ(locinput,
8431 UTF8SKIP(locinput));
8434 could_match = UCHARAT(locinput) == ST.c1
8435 || UCHARAT(locinput) == ST.c2;
8438 if (ST.c1 == CHRTEST_VOID || could_match) {
8439 CURLY_SETPAREN(ST.paren, ST.count);
8440 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8441 NOT_REACHED; /* NOTREACHED */
8446 case CURLY_B_max_fail:
8447 /* failed to find B in a greedy match */
8449 REGCP_UNWIND(ST.cp);
8451 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8454 if (--ST.count < ST.min)
8456 locinput = HOPc(locinput, -1);
8457 goto curly_try_B_max;
8461 case END: /* last op of main pattern */
8464 /* we've just finished A in /(??{A})B/; now continue with B */
8465 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8466 st->u.eval.prev_rex = rex_sv; /* inner */
8468 /* Save *all* the positions. */
8469 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8470 rex_sv = CUR_EVAL.prev_rex;
8471 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8472 SET_reg_curpm(rex_sv);
8473 rex = ReANY(rex_sv);
8474 rexi = RXi_GET(rex);
8476 st->u.eval.prev_curlyx = cur_curlyx;
8477 cur_curlyx = CUR_EVAL.prev_curlyx;
8479 REGCP_SET(st->u.eval.lastcp);
8481 /* Restore parens of the outer rex without popping the
8483 regcp_restore(rex, CUR_EVAL.lastcp, &maxopenparen);
8485 st->u.eval.prev_eval = cur_eval;
8486 cur_eval = CUR_EVAL.prev_eval;
8488 Perl_re_exec_indentf( aTHX_ "EVAL trying tail ... (cur_eval=%p)\n",
8490 if ( nochange_depth )
8493 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8495 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, st->u.eval.prev_eval->u.eval.B,
8496 locinput); /* match B */
8499 if (locinput < reginfo->till) {
8500 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8501 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8503 (long)(locinput - startpos),
8504 (long)(reginfo->till - startpos),
8507 sayNO_SILENT; /* Cannot match: too short. */
8509 sayYES; /* Success! */
8511 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8513 Perl_re_exec_indentf( aTHX_ "%ssubpattern success...%s\n",
8514 depth, PL_colors[4], PL_colors[5]));
8515 sayYES; /* Success! */
8518 #define ST st->u.ifmatch
8523 case SUSPEND: /* (?>A) */
8525 newstart = locinput;
8528 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8530 goto ifmatch_trivial_fail_test;
8532 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8534 ifmatch_trivial_fail_test:
8536 char * const s = HOPBACKc(locinput, scan->flags);
8541 sw = 1 - cBOOL(ST.wanted);
8545 next = scan + ARG(scan);
8553 newstart = locinput;
8557 ST.logical = logical;
8558 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8560 /* execute body of (?...A) */
8561 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8562 NOT_REACHED; /* NOTREACHED */
8565 case IFMATCH_A_fail: /* body of (?...A) failed */
8566 ST.wanted = !ST.wanted;
8569 case IFMATCH_A: /* body of (?...A) succeeded */
8571 sw = cBOOL(ST.wanted);
8573 else if (!ST.wanted)
8576 if (OP(ST.me) != SUSPEND) {
8577 /* restore old position except for (?>...) */
8578 locinput = st->locinput;
8580 scan = ST.me + ARG(ST.me);
8583 continue; /* execute B */
8587 case LONGJMP: /* alternative with many branches compiles to
8588 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8589 next = scan + ARG(scan);
8594 case COMMIT: /* (*COMMIT) */
8595 reginfo->cutpoint = reginfo->strend;
8598 case PRUNE: /* (*PRUNE) */
8600 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8601 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8602 NOT_REACHED; /* NOTREACHED */
8604 case COMMIT_next_fail:
8608 NOT_REACHED; /* NOTREACHED */
8610 case OPFAIL: /* (*FAIL) */
8612 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8614 /* deal with (?(?!)X|Y) properly,
8615 * make sure we trigger the no branch
8616 * of the trailing IFTHEN structure*/
8622 NOT_REACHED; /* NOTREACHED */
8624 #define ST st->u.mark
8625 case MARKPOINT: /* (*MARK:foo) */
8626 ST.prev_mark = mark_state;
8627 ST.mark_name = sv_commit = sv_yes_mark
8628 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8630 ST.mark_loc = locinput;
8631 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8632 NOT_REACHED; /* NOTREACHED */
8634 case MARKPOINT_next:
8635 mark_state = ST.prev_mark;
8637 NOT_REACHED; /* NOTREACHED */
8639 case MARKPOINT_next_fail:
8640 if (popmark && sv_eq(ST.mark_name,popmark))
8642 if (ST.mark_loc > startpoint)
8643 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8644 popmark = NULL; /* we found our mark */
8645 sv_commit = ST.mark_name;
8648 Perl_re_exec_indentf( aTHX_ "%ssetting cutpoint to mark:%" SVf "...%s\n",
8650 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8653 mark_state = ST.prev_mark;
8654 sv_yes_mark = mark_state ?
8655 mark_state->u.mark.mark_name : NULL;
8657 NOT_REACHED; /* NOTREACHED */
8659 case SKIP: /* (*SKIP) */
8661 /* (*SKIP) : if we fail we cut here*/
8662 ST.mark_name = NULL;
8663 ST.mark_loc = locinput;
8664 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8666 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8667 otherwise do nothing. Meaning we need to scan
8669 regmatch_state *cur = mark_state;
8670 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8673 if ( sv_eq( cur->u.mark.mark_name,
8676 ST.mark_name = find;
8677 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8679 cur = cur->u.mark.prev_mark;
8682 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8685 case SKIP_next_fail:
8687 /* (*CUT:NAME) - Set up to search for the name as we
8688 collapse the stack*/
8689 popmark = ST.mark_name;
8691 /* (*CUT) - No name, we cut here.*/
8692 if (ST.mark_loc > startpoint)
8693 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8694 /* but we set sv_commit to latest mark_name if there
8695 is one so they can test to see how things lead to this
8698 sv_commit=mark_state->u.mark.mark_name;
8702 NOT_REACHED; /* NOTREACHED */
8705 case LNBREAK: /* \R */
8706 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8713 PerlIO_printf(Perl_error_log, "%" UVxf " %d\n",
8714 PTR2UV(scan), OP(scan));
8715 Perl_croak(aTHX_ "regexp memory corruption");
8717 /* this is a point to jump to in order to increment
8718 * locinput by one character */
8720 assert(!NEXTCHR_IS_EOS);
8722 locinput += PL_utf8skip[nextchr];
8723 /* locinput is allowed to go 1 char off the end (signifying
8724 * EOS), but not 2+ */
8725 if (locinput > reginfo->strend)
8734 /* switch break jumps here */
8735 scan = next; /* prepare to execute the next op and ... */
8736 continue; /* ... jump back to the top, reusing st */
8740 /* push a state that backtracks on success */
8741 st->u.yes.prev_yes_state = yes_state;
8745 /* push a new regex state, then continue at scan */
8747 regmatch_state *newst;
8750 regmatch_state *cur = st;
8751 regmatch_state *curyes = yes_state;
8753 regmatch_slab *slab = PL_regmatch_slab;
8754 for (i = 0; i < 3 && i <= depth; cur--,i++) {
8755 if (cur < SLAB_FIRST(slab)) {
8757 cur = SLAB_LAST(slab);
8759 Perl_re_exec_indentf( aTHX_ "%4s #%-3d %-10s %s\n",
8762 depth - i, PL_reg_name[cur->resume_state],
8763 (curyes == cur) ? "yes" : ""
8766 curyes = cur->u.yes.prev_yes_state;
8769 DEBUG_STATE_pp("push")
8772 st->locinput = locinput;
8774 if (newst > SLAB_LAST(PL_regmatch_slab))
8775 newst = S_push_slab(aTHX);
8776 PL_regmatch_state = newst;
8778 locinput = pushinput;
8784 #ifdef SOLARIS_BAD_OPTIMIZER
8785 # undef PL_charclass
8789 * We get here only if there's trouble -- normally "case END" is
8790 * the terminating point.
8792 Perl_croak(aTHX_ "corrupted regexp pointers");
8793 NOT_REACHED; /* NOTREACHED */
8797 /* we have successfully completed a subexpression, but we must now
8798 * pop to the state marked by yes_state and continue from there */
8799 assert(st != yes_state);
8801 while (st != yes_state) {
8803 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8804 PL_regmatch_slab = PL_regmatch_slab->prev;
8805 st = SLAB_LAST(PL_regmatch_slab);
8809 DEBUG_STATE_pp("pop (no final)");
8811 DEBUG_STATE_pp("pop (yes)");
8817 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8818 || yes_state > SLAB_LAST(PL_regmatch_slab))
8820 /* not in this slab, pop slab */
8821 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8822 PL_regmatch_slab = PL_regmatch_slab->prev;
8823 st = SLAB_LAST(PL_regmatch_slab);
8825 depth -= (st - yes_state);
8828 yes_state = st->u.yes.prev_yes_state;
8829 PL_regmatch_state = st;
8832 locinput= st->locinput;
8833 state_num = st->resume_state + no_final;
8834 goto reenter_switch;
8837 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
8838 PL_colors[4], PL_colors[5]));
8840 if (reginfo->info_aux_eval) {
8841 /* each successfully executed (?{...}) block does the equivalent of
8842 * local $^R = do {...}
8843 * When popping the save stack, all these locals would be undone;
8844 * bypass this by setting the outermost saved $^R to the latest
8846 /* I dont know if this is needed or works properly now.
8847 * see code related to PL_replgv elsewhere in this file.
8850 if (oreplsv != GvSV(PL_replgv))
8851 sv_setsv(oreplsv, GvSV(PL_replgv));
8858 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
8860 PL_colors[4], PL_colors[5])
8872 /* there's a previous state to backtrack to */
8874 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8875 PL_regmatch_slab = PL_regmatch_slab->prev;
8876 st = SLAB_LAST(PL_regmatch_slab);
8878 PL_regmatch_state = st;
8879 locinput= st->locinput;
8881 DEBUG_STATE_pp("pop");
8883 if (yes_state == st)
8884 yes_state = st->u.yes.prev_yes_state;
8886 state_num = st->resume_state + 1; /* failure = success + 1 */
8888 goto reenter_switch;
8893 if (rex->intflags & PREGf_VERBARG_SEEN) {
8894 SV *sv_err = get_sv("REGERROR", 1);
8895 SV *sv_mrk = get_sv("REGMARK", 1);
8897 sv_commit = &PL_sv_no;
8899 sv_yes_mark = &PL_sv_yes;
8902 sv_commit = &PL_sv_yes;
8903 sv_yes_mark = &PL_sv_no;
8907 sv_setsv(sv_err, sv_commit);
8908 sv_setsv(sv_mrk, sv_yes_mark);
8912 if (last_pushed_cv) {
8914 /* see "Some notes about MULTICALL" above */
8916 PERL_UNUSED_VAR(SP);
8919 LEAVE_SCOPE(orig_savestack_ix);
8921 assert(!result || locinput - reginfo->strbeg >= 0);
8922 return result ? locinput - reginfo->strbeg : -1;
8926 - regrepeat - repeatedly match something simple, report how many
8928 * What 'simple' means is a node which can be the operand of a quantifier like
8931 * startposp - pointer a pointer to the start position. This is updated
8932 * to point to the byte following the highest successful
8934 * p - the regnode to be repeatedly matched against.
8935 * reginfo - struct holding match state, such as strend
8936 * max - maximum number of things to match.
8937 * depth - (for debugging) backtracking depth.
8940 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8941 regmatch_info *const reginfo, I32 max _pDEPTH)
8943 char *scan; /* Pointer to current position in target string */
8945 char *loceol = reginfo->strend; /* local version */
8946 I32 hardcount = 0; /* How many matches so far */
8947 bool utf8_target = reginfo->is_utf8_target;
8948 unsigned int to_complement = 0; /* Invert the result? */
8950 _char_class_number classnum;
8952 PERL_ARGS_ASSERT_REGREPEAT;
8955 if (max == REG_INFTY)
8957 else if (! utf8_target && loceol - scan > max)
8958 loceol = scan + max;
8960 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8961 * to the maximum of how far we should go in it (leaving it set to the real
8962 * end, if the maximum permissible would take us beyond that). This allows
8963 * us to make the loop exit condition that we haven't gone past <loceol> to
8964 * also mean that we haven't exceeded the max permissible count, saving a
8965 * test each time through the loop. But it assumes that the OP matches a
8966 * single byte, which is true for most of the OPs below when applied to a
8967 * non-UTF-8 target. Those relatively few OPs that don't have this
8968 * characteristic will have to compensate.
8970 * There is no adjustment for UTF-8 targets, as the number of bytes per
8971 * character varies. OPs will have to test both that the count is less
8972 * than the max permissible (using <hardcount> to keep track), and that we
8973 * are still within the bounds of the string (using <loceol>. A few OPs
8974 * match a single byte no matter what the encoding. They can omit the max
8975 * test if, for the UTF-8 case, they do the adjustment that was skipped
8978 * Thus, the code above sets things up for the common case; and exceptional
8979 * cases need extra work; the common case is to make sure <scan> doesn't
8980 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8981 * count doesn't exceed the maximum permissible */
8986 while (scan < loceol && hardcount < max && *scan != '\n') {
8987 scan += UTF8SKIP(scan);
8991 while (scan < loceol && *scan != '\n')
8997 while (scan < loceol && hardcount < max) {
8998 scan += UTF8SKIP(scan);
9006 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9007 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
9008 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
9012 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
9016 /* Can use a simple loop if the pattern char to match on is invariant
9017 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
9018 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
9019 * true iff it doesn't matter if the argument is in UTF-8 or not */
9020 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
9021 if (utf8_target && loceol - scan > max) {
9022 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
9023 * since here, to match at all, 1 char == 1 byte */
9024 loceol = scan + max;
9026 while (scan < loceol && UCHARAT(scan) == c) {
9030 else if (reginfo->is_utf8_pat) {
9032 STRLEN scan_char_len;
9034 /* When both target and pattern are UTF-8, we have to do
9036 while (hardcount < max
9038 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
9039 && memEQ(scan, STRING(p), scan_char_len))
9041 scan += scan_char_len;
9045 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
9047 /* Target isn't utf8; convert the character in the UTF-8
9048 * pattern to non-UTF8, and do a simple loop */
9049 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
9050 while (scan < loceol && UCHARAT(scan) == c) {
9053 } /* else pattern char is above Latin1, can't possibly match the
9058 /* Here, the string must be utf8; pattern isn't, and <c> is
9059 * different in utf8 than not, so can't compare them directly.
9060 * Outside the loop, find the two utf8 bytes that represent c, and
9061 * then look for those in sequence in the utf8 string */
9062 U8 high = UTF8_TWO_BYTE_HI(c);
9063 U8 low = UTF8_TWO_BYTE_LO(c);
9065 while (hardcount < max
9066 && scan + 1 < loceol
9067 && UCHARAT(scan) == high
9068 && UCHARAT(scan + 1) == low)
9076 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
9077 assert(! reginfo->is_utf8_pat);
9080 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
9084 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9085 utf8_flags = FOLDEQ_LOCALE;
9088 case EXACTF: /* This node only generated for non-utf8 patterns */
9089 assert(! reginfo->is_utf8_pat);
9094 if (! utf8_target) {
9097 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
9098 | FOLDEQ_S2_FOLDS_SANE;
9103 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
9107 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
9109 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
9111 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
9114 if (c1 == CHRTEST_VOID) {
9115 /* Use full Unicode fold matching */
9116 char *tmpeol = reginfo->strend;
9117 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
9118 while (hardcount < max
9119 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
9120 STRING(p), NULL, pat_len,
9121 reginfo->is_utf8_pat, utf8_flags))
9124 tmpeol = reginfo->strend;
9128 else if (utf8_target) {
9130 while (scan < loceol
9132 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
9134 scan += UTF8SKIP(scan);
9139 while (scan < loceol
9141 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
9142 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
9144 scan += UTF8SKIP(scan);
9149 else if (c1 == c2) {
9150 while (scan < loceol && UCHARAT(scan) == c1) {
9155 /* See comments in regmatch() CURLY_B_min_known_fail. We avoid
9156 * a conditional each time through the loop if the characters
9157 * differ only in a single bit, as is the usual situation */
9158 U8 c1_c2_bits_differing = c1 ^ c2;
9160 if (isPOWER_OF_2(c1_c2_bits_differing)) {
9161 U8 c1_masked = c1 & ~ c1_c2_bits_differing;
9162 U8 c1_c2_mask = ~ c1_c2_bits_differing;
9164 while ( scan < loceol
9165 && (UCHARAT(scan) & c1_c2_mask) == c1_masked)
9171 while ( scan < loceol
9172 && (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
9182 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9184 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
9185 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
9191 while (hardcount < max
9193 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
9195 scan += UTF8SKIP(scan);
9199 else if (ANYOF_FLAGS(p)) {
9200 while (scan < loceol
9201 && reginclass(prog, p, (U8*)scan, (U8*)scan+1, 0))
9205 while (scan < loceol && ANYOF_BITMAP_TEST(p, *((U8*)scan)))
9211 if (utf8_target && loceol - scan > max) {
9213 /* We didn't adjust <loceol> at the beginning of this routine
9214 * because is UTF-8, but it is actually ok to do so, since here, to
9215 * match, 1 char == 1 byte. */
9216 loceol = scan + max;
9219 scan = find_next_non_ascii(scan, loceol, utf8_target);
9224 while ( hardcount < max
9226 && ! isASCII_utf8_safe(scan, loceol))
9228 scan += UTF8SKIP(scan);
9233 scan = find_next_ascii(scan, loceol, utf8_target);
9237 /* The argument (FLAGS) to all the POSIX node types is the class number */
9244 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9245 if (! utf8_target) {
9246 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
9252 while (hardcount < max && scan < loceol
9253 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
9256 scan += UTF8SKIP(scan);
9269 if (utf8_target && loceol - scan > max) {
9271 /* We didn't adjust <loceol> at the beginning of this routine
9272 * because is UTF-8, but it is actually ok to do so, since here, to
9273 * match, 1 char == 1 byte. */
9274 loceol = scan + max;
9276 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
9289 if (! utf8_target) {
9290 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
9296 /* The complement of something that matches only ASCII matches all
9297 * non-ASCII, plus everything in ASCII that isn't in the class. */
9298 while (hardcount < max && scan < loceol
9299 && ( ! isASCII_utf8_safe(scan, reginfo->strend)
9300 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
9302 scan += UTF8SKIP(scan);
9313 if (! utf8_target) {
9314 while (scan < loceol && to_complement
9315 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
9322 classnum = (_char_class_number) FLAGS(p);
9323 if (classnum < _FIRST_NON_SWASH_CC) {
9325 /* Here, a swash is needed for above-Latin1 code points.
9326 * Process as many Latin1 code points using the built-in rules.
9327 * Go to another loop to finish processing upon encountering
9328 * the first Latin1 code point. We could do that in this loop
9329 * as well, but the other way saves having to test if the swash
9330 * has been loaded every time through the loop: extra space to
9332 while (hardcount < max && scan < loceol) {
9333 if (UTF8_IS_INVARIANT(*scan)) {
9334 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
9341 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
9342 if (! (to_complement
9343 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
9352 goto found_above_latin1;
9359 /* For these character classes, the knowledge of how to handle
9360 * every code point is compiled in to Perl via a macro. This
9361 * code is written for making the loops as tight as possible.
9362 * It could be refactored to save space instead */
9364 case _CC_ENUM_SPACE:
9365 while (hardcount < max
9368 ^ cBOOL(isSPACE_utf8_safe(scan, loceol))))
9370 scan += UTF8SKIP(scan);
9374 case _CC_ENUM_BLANK:
9375 while (hardcount < max
9378 ^ cBOOL(isBLANK_utf8_safe(scan, loceol))))
9380 scan += UTF8SKIP(scan);
9384 case _CC_ENUM_XDIGIT:
9385 while (hardcount < max
9388 ^ cBOOL(isXDIGIT_utf8_safe(scan, loceol))))
9390 scan += UTF8SKIP(scan);
9394 case _CC_ENUM_VERTSPACE:
9395 while (hardcount < max
9398 ^ cBOOL(isVERTWS_utf8_safe(scan, loceol))))
9400 scan += UTF8SKIP(scan);
9404 case _CC_ENUM_CNTRL:
9405 while (hardcount < max
9408 ^ cBOOL(isCNTRL_utf8_safe(scan, loceol))))
9410 scan += UTF8SKIP(scan);
9415 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
9421 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
9423 /* Load the swash if not already present */
9424 if (! PL_utf8_swash_ptrs[classnum]) {
9425 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
9426 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
9430 PL_XPosix_ptrs[classnum], &flags);
9433 while (hardcount < max && scan < loceol
9434 && to_complement ^ cBOOL(_generic_utf8_safe(
9438 swash_fetch(PL_utf8_swash_ptrs[classnum],
9442 scan += UTF8SKIP(scan);
9449 while (hardcount < max && scan < loceol &&
9450 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9455 /* LNBREAK can match one or two latin chars, which is ok, but we
9456 * have to use hardcount in this situation, and throw away the
9457 * adjustment to <loceol> done before the switch statement */
9458 loceol = reginfo->strend;
9459 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9468 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9482 /* These are all 0 width, so match right here or not at all. */
9486 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9487 NOT_REACHED; /* NOTREACHED */
9494 c = scan - *startposp;
9498 GET_RE_DEBUG_FLAGS_DECL;
9500 SV * const prop = sv_newmortal();
9501 regprop(prog, prop, p, reginfo, NULL);
9502 Perl_re_exec_indentf( aTHX_ "%s can match %" IVdf " times out of %" IVdf "...\n",
9503 depth, SvPVX_const(prop),(IV)c,(IV)max);
9511 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9513 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9514 create a copy so that changes the caller makes won't change the shared one.
9515 If <altsvp> is non-null, will return NULL in it, for back-compat.
9518 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9520 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9526 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9529 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9532 - reginclass - determine if a character falls into a character class
9534 n is the ANYOF-type regnode
9535 p is the target string
9536 p_end points to one byte beyond the end of the target string
9537 utf8_target tells whether p is in UTF-8.
9539 Returns true if matched; false otherwise.
9541 Note that this can be a synthetic start class, a combination of various
9542 nodes, so things you think might be mutually exclusive, such as locale,
9543 aren't. It can match both locale and non-locale
9548 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9551 const char flags = ANYOF_FLAGS(n);
9555 PERL_ARGS_ASSERT_REGINCLASS;
9557 /* If c is not already the code point, get it. Note that
9558 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9559 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9561 const U32 utf8n_flags = UTF8_ALLOW_DEFAULT;
9562 c = utf8n_to_uvchr(p, p_end - p, &c_len, utf8n_flags | UTF8_CHECK_ONLY);
9563 if (c_len == (STRLEN)-1) {
9564 _force_out_malformed_utf8_message(p, p_end,
9566 1 /* 1 means die */ );
9567 NOT_REACHED; /* NOTREACHED */
9569 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9570 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9574 /* If this character is potentially in the bitmap, check it */
9575 if (c < NUM_ANYOF_CODE_POINTS) {
9576 if (ANYOF_BITMAP_TEST(n, c))
9579 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9586 else if (flags & ANYOF_LOCALE_FLAGS) {
9587 if ((flags & ANYOFL_FOLD)
9589 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9593 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9597 /* The data structure is arranged so bits 0, 2, 4, ... are set
9598 * if the class includes the Posix character class given by
9599 * bit/2; and 1, 3, 5, ... are set if the class includes the
9600 * complemented Posix class given by int(bit/2). So we loop
9601 * through the bits, each time changing whether we complement
9602 * the result or not. Suppose for the sake of illustration
9603 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9604 * is set, it means there is a match for this ANYOF node if the
9605 * character is in the class given by the expression (0 / 2 = 0
9606 * = \w). If it is in that class, isFOO_lc() will return 1,
9607 * and since 'to_complement' is 0, the result will stay TRUE,
9608 * and we exit the loop. Suppose instead that bit 0 is 0, but
9609 * bit 1 is 1. That means there is a match if the character
9610 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9611 * but will on bit 1. On the second iteration 'to_complement'
9612 * will be 1, so the exclusive or will reverse things, so we
9613 * are testing for \W. On the third iteration, 'to_complement'
9614 * will be 0, and we would be testing for \s; the fourth
9615 * iteration would test for \S, etc.
9617 * Note that this code assumes that all the classes are closed
9618 * under folding. For example, if a character matches \w, then
9619 * its fold does too; and vice versa. This should be true for
9620 * any well-behaved locale for all the currently defined Posix
9621 * classes, except for :lower: and :upper:, which are handled
9622 * by the pseudo-class :cased: which matches if either of the
9623 * other two does. To get rid of this assumption, an outer
9624 * loop could be used below to iterate over both the source
9625 * character, and its fold (if different) */
9628 int to_complement = 0;
9630 while (count < ANYOF_MAX) {
9631 if (ANYOF_POSIXL_TEST(n, count)
9632 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9645 /* If the bitmap didn't (or couldn't) match, and something outside the
9646 * bitmap could match, try that. */
9648 if (c >= NUM_ANYOF_CODE_POINTS
9649 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9651 match = TRUE; /* Everything above the bitmap matches */
9653 /* Here doesn't match everything above the bitmap. If there is
9654 * some information available beyond the bitmap, we may find a
9655 * match in it. If so, this is most likely because the code point
9656 * is outside the bitmap range. But rarely, it could be because of
9657 * some other reason. If so, various flags are set to indicate
9658 * this possibility. On ANYOFD nodes, there may be matches that
9659 * happen only when the target string is UTF-8; or for other node
9660 * types, because runtime lookup is needed, regardless of the
9661 * UTF-8ness of the target string. Finally, under /il, there may
9662 * be some matches only possible if the locale is a UTF-8 one. */
9663 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9664 && ( c >= NUM_ANYOF_CODE_POINTS
9665 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9666 && ( UNLIKELY(OP(n) != ANYOFD)
9667 || (utf8_target && ! isASCII_uni(c)
9668 # if NUM_ANYOF_CODE_POINTS > 256
9672 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9673 && IN_UTF8_CTYPE_LOCALE)))
9675 SV* only_utf8_locale = NULL;
9676 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9677 &only_utf8_locale, NULL);
9683 } else { /* Convert to utf8 */
9684 utf8_p = utf8_buffer;
9685 append_utf8_from_native_byte(*p, &utf8_p);
9686 utf8_p = utf8_buffer;
9689 if (swash_fetch(sw, utf8_p, TRUE)) {
9693 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9694 match = _invlist_contains_cp(only_utf8_locale, c);
9698 if (UNICODE_IS_SUPER(c)
9700 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9702 && ckWARN_d(WARN_NON_UNICODE))
9704 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9705 "Matched non-Unicode code point 0x%04" UVXf " against Unicode property; may not be portable", c);
9709 #if ANYOF_INVERT != 1
9710 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9712 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9715 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9716 return (flags & ANYOF_INVERT) ^ match;
9720 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9722 /* return the position 'off' UTF-8 characters away from 's', forward if
9723 * 'off' >= 0, backwards if negative. But don't go outside of position
9724 * 'lim', which better be < s if off < 0 */
9726 PERL_ARGS_ASSERT_REGHOP3;
9729 while (off-- && s < lim) {
9730 /* XXX could check well-formedness here */
9731 U8 *new_s = s + UTF8SKIP(s);
9732 if (new_s > lim) /* lim may be in the middle of a long character */
9738 while (off++ && s > lim) {
9740 if (UTF8_IS_CONTINUED(*s)) {
9741 while (s > lim && UTF8_IS_CONTINUATION(*s))
9743 if (! UTF8_IS_START(*s)) {
9744 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9747 /* XXX could check well-formedness here */
9754 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9756 PERL_ARGS_ASSERT_REGHOP4;
9759 while (off-- && s < rlim) {
9760 /* XXX could check well-formedness here */
9765 while (off++ && s > llim) {
9767 if (UTF8_IS_CONTINUED(*s)) {
9768 while (s > llim && UTF8_IS_CONTINUATION(*s))
9770 if (! UTF8_IS_START(*s)) {
9771 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9774 /* XXX could check well-formedness here */
9780 /* like reghop3, but returns NULL on overrun, rather than returning last
9784 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9786 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9789 while (off-- && s < lim) {
9790 /* XXX could check well-formedness here */
9797 while (off++ && s > lim) {
9799 if (UTF8_IS_CONTINUED(*s)) {
9800 while (s > lim && UTF8_IS_CONTINUATION(*s))
9802 if (! UTF8_IS_START(*s)) {
9803 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9806 /* XXX could check well-formedness here */
9815 /* when executing a regex that may have (?{}), extra stuff needs setting
9816 up that will be visible to the called code, even before the current
9817 match has finished. In particular:
9819 * $_ is localised to the SV currently being matched;
9820 * pos($_) is created if necessary, ready to be updated on each call-out
9822 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9823 isn't set until the current pattern is successfully finished), so that
9824 $1 etc of the match-so-far can be seen;
9825 * save the old values of subbeg etc of the current regex, and set then
9826 to the current string (again, this is normally only done at the end
9831 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9834 regexp *const rex = ReANY(reginfo->prog);
9835 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9837 eval_state->rex = rex;
9840 /* Make $_ available to executed code. */
9841 if (reginfo->sv != DEFSV) {
9843 DEFSV_set(reginfo->sv);
9846 if (!(mg = mg_find_mglob(reginfo->sv))) {
9847 /* prepare for quick setting of pos */
9848 mg = sv_magicext_mglob(reginfo->sv);
9851 eval_state->pos_magic = mg;
9852 eval_state->pos = mg->mg_len;
9853 eval_state->pos_flags = mg->mg_flags;
9856 eval_state->pos_magic = NULL;
9858 if (!PL_reg_curpm) {
9859 /* PL_reg_curpm is a fake PMOP that we can attach the current
9860 * regex to and point PL_curpm at, so that $1 et al are visible
9861 * within a /(?{})/. It's just allocated once per interpreter the
9862 * first time its needed */
9863 Newxz(PL_reg_curpm, 1, PMOP);
9866 SV* const repointer = &PL_sv_undef;
9867 /* this regexp is also owned by the new PL_reg_curpm, which
9868 will try to free it. */
9869 av_push(PL_regex_padav, repointer);
9870 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9871 PL_regex_pad = AvARRAY(PL_regex_padav);
9875 SET_reg_curpm(reginfo->prog);
9876 eval_state->curpm = PL_curpm;
9877 PL_curpm_under = PL_curpm;
9878 PL_curpm = PL_reg_curpm;
9879 if (RXp_MATCH_COPIED(rex)) {
9880 /* Here is a serious problem: we cannot rewrite subbeg,
9881 since it may be needed if this match fails. Thus
9882 $` inside (?{}) could fail... */
9883 eval_state->subbeg = rex->subbeg;
9884 eval_state->sublen = rex->sublen;
9885 eval_state->suboffset = rex->suboffset;
9886 eval_state->subcoffset = rex->subcoffset;
9888 eval_state->saved_copy = rex->saved_copy;
9890 RXp_MATCH_COPIED_off(rex);
9893 eval_state->subbeg = NULL;
9894 rex->subbeg = (char *)reginfo->strbeg;
9896 rex->subcoffset = 0;
9897 rex->sublen = reginfo->strend - reginfo->strbeg;
9901 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9904 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9906 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9907 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9910 Safefree(aux->poscache);
9914 /* undo the effects of S_setup_eval_state() */
9916 if (eval_state->subbeg) {
9917 regexp * const rex = eval_state->rex;
9918 rex->subbeg = eval_state->subbeg;
9919 rex->sublen = eval_state->sublen;
9920 rex->suboffset = eval_state->suboffset;
9921 rex->subcoffset = eval_state->subcoffset;
9923 rex->saved_copy = eval_state->saved_copy;
9925 RXp_MATCH_COPIED_on(rex);
9927 if (eval_state->pos_magic)
9929 eval_state->pos_magic->mg_len = eval_state->pos;
9930 eval_state->pos_magic->mg_flags =
9931 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9932 | (eval_state->pos_flags & MGf_BYTES);
9935 PL_curpm = eval_state->curpm;
9938 PL_regmatch_state = aux->old_regmatch_state;
9939 PL_regmatch_slab = aux->old_regmatch_slab;
9941 /* free all slabs above current one - this must be the last action
9942 * of this function, as aux and eval_state are allocated within
9943 * slabs and may be freed here */
9945 s = PL_regmatch_slab->next;
9947 PL_regmatch_slab->next = NULL;
9949 regmatch_slab * const osl = s;
9958 S_to_utf8_substr(pTHX_ regexp *prog)
9960 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9961 * on the converted value */
9965 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9968 if (prog->substrs->data[i].substr
9969 && !prog->substrs->data[i].utf8_substr) {
9970 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9971 prog->substrs->data[i].utf8_substr = sv;
9972 sv_utf8_upgrade(sv);
9973 if (SvVALID(prog->substrs->data[i].substr)) {
9974 if (SvTAIL(prog->substrs->data[i].substr)) {
9975 /* Trim the trailing \n that fbm_compile added last
9977 SvCUR_set(sv, SvCUR(sv) - 1);
9978 /* Whilst this makes the SV technically "invalid" (as its
9979 buffer is no longer followed by "\0") when fbm_compile()
9980 adds the "\n" back, a "\0" is restored. */
9981 fbm_compile(sv, FBMcf_TAIL);
9985 if (prog->substrs->data[i].substr == prog->check_substr)
9986 prog->check_utf8 = sv;
9992 S_to_byte_substr(pTHX_ regexp *prog)
9994 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9995 * on the converted value; returns FALSE if can't be converted. */
9999 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
10002 if (prog->substrs->data[i].utf8_substr
10003 && !prog->substrs->data[i].substr) {
10004 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
10005 if (! sv_utf8_downgrade(sv, TRUE)) {
10008 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
10009 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
10010 /* Trim the trailing \n that fbm_compile added last
10012 SvCUR_set(sv, SvCUR(sv) - 1);
10013 fbm_compile(sv, FBMcf_TAIL);
10015 fbm_compile(sv, 0);
10017 prog->substrs->data[i].substr = sv;
10018 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
10019 prog->check_substr = sv;
10026 #ifndef PERL_IN_XSUB_RE
10029 Perl__is_grapheme(pTHX_ const U8 * strbeg, const U8 * s, const U8 * strend, const UV cp)
10031 /* Temporary helper function for toke.c. Verify that the code point 'cp'
10032 * is a stand-alone grapheme. The UTF-8 for 'cp' begins at position 's' in
10033 * the larger string bounded by 'strbeg' and 'strend'.
10035 * 'cp' needs to be assigned (if not a future version of the Unicode
10036 * Standard could make it something that combines with adjacent characters,
10037 * so code using it would then break), and there has to be a GCB break
10038 * before and after the character. */
10040 GCB_enum cp_gcb_val, prev_cp_gcb_val, next_cp_gcb_val;
10041 const U8 * prev_cp_start;
10043 PERL_ARGS_ASSERT__IS_GRAPHEME;
10045 /* Unassigned code points are forbidden */
10046 if (UNLIKELY(! ELEMENT_RANGE_MATCHES_INVLIST(
10047 _invlist_search(PL_Assigned_invlist, cp))))
10052 cp_gcb_val = getGCB_VAL_CP(cp);
10054 /* Find the GCB value of the previous code point in the input */
10055 prev_cp_start = utf8_hop_back(s, -1, strbeg);
10056 if (UNLIKELY(prev_cp_start == s)) {
10057 prev_cp_gcb_val = GCB_EDGE;
10060 prev_cp_gcb_val = getGCB_VAL_UTF8(prev_cp_start, strend);
10063 /* And check that is a grapheme boundary */
10064 if (! isGCB(prev_cp_gcb_val, cp_gcb_val, strbeg, s,
10065 TRUE /* is UTF-8 encoded */ ))
10070 /* Similarly verify there is a break between the current character and the
10074 next_cp_gcb_val = GCB_EDGE;
10077 next_cp_gcb_val = getGCB_VAL_UTF8(s, strend);
10080 return isGCB(cp_gcb_val, next_cp_gcb_val, strbeg, s, TRUE);
10084 Perl_isSCRIPT_RUN(pTHX_ const U8 * s, const U8 * send, const bool utf8_target)
10086 /* Checks that every character in the sequence from 's' to 'send' is one of
10087 * three scripts: Common, Inherited, and possibly one other. Additionally
10088 * all decimal digits must come from the same consecutive sequence of 10.
10089 * 'utf8_target' is TRUE iff the sequence is encoded in UTF-8.
10091 * Basically, it looks at each character in the sequence to see if the
10092 * above conditions are met; if not it fails. It uses an inversion map to
10093 * find the enum corresponding to the script of each character. But this
10094 * is complicated by the fact that a few code points can be in any of
10095 * several scripts. The data has been constructed so that there are
10096 * additional enum values (all negative) for these situations. The
10097 * absolute value of those is an index into another table which contains
10098 * pointers to auxiliary tables for each such situation. Each aux array
10099 * lists all the scripts for the given situation. There is another,
10100 * parallel, table that gives the number of entries in each aux table.
10101 * These are all defined in charclass_invlists.h */
10103 /* XXX Here are the additional things UTS 39 says could be done:
10104 * Mark Chinese strings as “mixed script” if they contain both simplified
10105 * (S) and traditional (T) Chinese characters, using the Unihan data in the
10106 * Unicode Character Database [UCD]. The criterion can only be applied if
10107 * the language of the string is known to be Chinese. So, for example, the
10108 * string “写真だけの結婚式 ” is Japanese, and should not be marked as
10109 * mixed script because of a mixture of S and T characters. Testing for
10110 * whether a character is S or T needs to be based not on whether the
10111 * character has a S or T variant , but whether the character is an S or T
10112 * variant. khw notes that the sample contains a Hiragana character, and it
10113 * is unclear if absence of any foreign script marks the script as
10116 * Forbid sequences of the same nonspacing mark
10118 * Check to see that all the characters are in the sets of exemplar
10119 * characters for at least one language in the Unicode Common Locale Data
10120 * Repository [CLDR]. */
10123 /* Things that match /\d/u */
10124 SV * decimals_invlist = PL_XPosix_ptrs[_CC_DIGIT];
10125 UV * decimals_array = invlist_array(decimals_invlist);
10127 /* What code point is the digit '0' of the script run? */
10128 UV zero_of_run = 0;
10129 SCX_enum script_of_run = SCX_INVALID; /* Illegal value */
10130 SCX_enum script_of_char = SCX_INVALID;
10132 /* If the script remains not fully determined from iteration to iteration,
10133 * this is the current intersection of the possiblities. */
10134 SCX_enum * intersection = NULL;
10135 PERL_UINT_FAST8_T intersection_len = 0;
10137 bool retval = TRUE;
10141 PERL_ARGS_ASSERT_ISSCRIPT_RUN;
10143 /* Look at each character in the sequence */
10147 /* The code allows all scripts to use the ASCII digits. This is
10148 * because they are used in commerce even in scripts that have their
10149 * own set. Hence any ASCII ones found are ok, unless a digit from
10150 * another set has already been encountered. (The other digit ranges
10151 * in Common are not similarly blessed */
10152 if (UNLIKELY(isDIGIT(*s))) {
10153 if (zero_of_run > 0) {
10154 if (zero_of_run != '0') {
10166 /* Here, isn't an ASCII digit. Find the code point of the character */
10167 if (utf8_target && ! UTF8_IS_INVARIANT(*s)) {
10169 cp = valid_utf8_to_uvchr((U8 *) s, &len);
10176 /* If is within the range [+0 .. +9] of the script's zero, it also is a
10177 * digit in that script. We can skip the rest of this code for this
10179 if (UNLIKELY( zero_of_run > 0
10180 && cp >= zero_of_run
10181 && cp - zero_of_run <= 9))
10186 /* Find the character's script. The correct values are hard-coded here
10187 * for small-enough code points. */
10188 if (cp < 0x2B9) { /* From inspection of Unicode db; extremely
10189 unlikely to change */
10191 || ( isALPHA_L1(cp)
10192 && LIKELY(cp != MICRO_SIGN_NATIVE)))
10194 script_of_char = SCX_Latin;
10197 script_of_char = SCX_Common;
10201 script_of_char = _Perl_SCX_invmap[
10202 _invlist_search(PL_SCX_invlist, cp)];
10205 /* We arbitrarily accept a single unassigned character, but not in
10206 * combination with anything else, and not a run of them. */
10207 if ( UNLIKELY(script_of_run == SCX_Unknown)
10208 || UNLIKELY( script_of_run != SCX_INVALID
10209 && script_of_char == SCX_Unknown))
10215 if (UNLIKELY(script_of_char == SCX_Unknown)) {
10216 script_of_run = SCX_Unknown;
10220 /* We accept 'inherited' script characters currently even at the
10221 * beginning. (We know that no characters in Inherited are digits, or
10222 * we'd have to check for that) */
10223 if (UNLIKELY(script_of_char == SCX_Inherited)) {
10227 /* If unknown, the run's script is set to the char's */
10228 if (UNLIKELY(script_of_run == SCX_INVALID)) {
10229 script_of_run = script_of_char;
10232 /* All decimal digits must be from the same sequence of 10. Above, we
10233 * handled any ASCII digits without descending to here. We also
10234 * handled the case where we already knew what digit sequence is the
10235 * one to use, and the character is in that sequence. Now that we know
10236 * the script, we can use script_zeros[] to directly find which
10237 * sequence the script uses, except in a few cases it returns 0 */
10238 if (UNLIKELY(zero_of_run == 0) && script_of_char >= 0) {
10239 zero_of_run = script_zeros[script_of_char];
10242 /* Now we can see if the script of the character is the same as that of
10244 if (LIKELY(script_of_char == script_of_run)) {
10245 /* By far the most common case */
10246 goto scripts_match;
10249 /* Here, the scripts of the run and the current character don't match
10250 * exactly. The run could so far have been entirely characters from
10251 * Common. It's now time to change its script to that of this
10252 * non-Common character */
10253 if (script_of_run == SCX_Common) {
10255 /* But Common contains several sets of digits. Only the '0' set
10256 * can be part of another script. */
10257 if (zero_of_run > 0 && zero_of_run != '0') {
10262 script_of_run = script_of_char;
10263 goto scripts_match;
10266 /* Here, the script of the run isn't Common. But characters in Common
10267 * match any script */
10268 if (script_of_char == SCX_Common) {
10269 goto scripts_match;
10272 #ifndef HAS_SCX_AUX_TABLES
10274 /* Too early a Unicode version to have a code point belonging to more
10275 * than one script, so, if the scripts don't exactly match, fail */
10281 /* Here there is no exact match between the character's script and the
10282 * run's. And we've handled the special cases of scripts Unknown,
10283 * Inherited, and Common.
10285 * Negative script numbers signify that the value may be any of several
10286 * scripts, and we need to look at auxiliary information to make our
10287 * deterimination. But if both are non-negative, we can fail now */
10288 if (LIKELY(script_of_char >= 0)) {
10289 const SCX_enum * search_in;
10290 PERL_UINT_FAST8_T search_in_len;
10291 PERL_UINT_FAST8_T i;
10293 if (LIKELY(script_of_run >= 0)) {
10298 /* Use the previously constructed set of possible scripts, if any.
10300 if (intersection) {
10301 search_in = intersection;
10302 search_in_len = intersection_len;
10305 search_in = SCX_AUX_TABLE_ptrs[-script_of_run];
10306 search_in_len = SCX_AUX_TABLE_lengths[-script_of_run];
10309 for (i = 0; i < search_in_len; i++) {
10310 if (search_in[i] == script_of_char) {
10311 script_of_run = script_of_char;
10312 goto scripts_match;
10319 else if (LIKELY(script_of_run >= 0)) {
10320 /* script of character could be one of several, but run is a single
10322 const SCX_enum * search_in = SCX_AUX_TABLE_ptrs[-script_of_char];
10323 const PERL_UINT_FAST8_T search_in_len
10324 = SCX_AUX_TABLE_lengths[-script_of_char];
10325 PERL_UINT_FAST8_T i;
10327 for (i = 0; i < search_in_len; i++) {
10328 if (search_in[i] == script_of_run) {
10329 script_of_char = script_of_run;
10330 goto scripts_match;
10338 /* Both run and char could be in one of several scripts. If the
10339 * intersection is empty, then this character isn't in this script
10340 * run. Otherwise, we need to calculate the intersection to use
10341 * for future iterations of the loop, unless we are already at the
10342 * final character */
10343 const SCX_enum * search_char = SCX_AUX_TABLE_ptrs[-script_of_char];
10344 const PERL_UINT_FAST8_T char_len
10345 = SCX_AUX_TABLE_lengths[-script_of_char];
10346 const SCX_enum * search_run;
10347 PERL_UINT_FAST8_T run_len;
10349 SCX_enum * new_overlap = NULL;
10350 PERL_UINT_FAST8_T i, j;
10352 if (intersection) {
10353 search_run = intersection;
10354 run_len = intersection_len;
10357 search_run = SCX_AUX_TABLE_ptrs[-script_of_run];
10358 run_len = SCX_AUX_TABLE_lengths[-script_of_run];
10361 intersection_len = 0;
10363 for (i = 0; i < run_len; i++) {
10364 for (j = 0; j < char_len; j++) {
10365 if (search_run[i] == search_char[j]) {
10367 /* Here, the script at i,j matches. That means this
10368 * character is in the run. But continue on to find
10369 * the complete intersection, for the next loop
10370 * iteration, and for the digit check after it.
10372 * On the first found common script, we malloc space
10373 * for the intersection list for the worst case of the
10374 * intersection, which is the minimum of the number of
10375 * scripts remaining in each set. */
10376 if (intersection_len == 0) {
10378 MIN(run_len - i, char_len - j),
10381 new_overlap[intersection_len++] = search_run[i];
10386 /* Here we've looked through everything. If they have no scripts
10387 * in common, not a run */
10388 if (intersection_len == 0) {
10393 /* If there is only a single script in common, set to that.
10394 * Otherwise, use the intersection going forward */
10395 Safefree(intersection);
10396 if (intersection_len == 1) {
10397 script_of_run = script_of_char = new_overlap[0];
10398 Safefree(new_overlap);
10401 intersection = new_overlap;
10409 /* Here, the script of the character is compatible with that of the
10410 * run. Either they match exactly, or one or both can be any of
10411 * several scripts, and the intersection is not empty. If the
10412 * character is not a decimal digit, we are done with it. Otherwise,
10413 * it could still fail if it is from a different set of 10 than seen
10414 * already (or we may not have seen any, and we need to set the
10415 * sequence). If we have determined a single script and that script
10416 * only has one set of digits (almost all scripts are like that), then
10417 * this isn't a problem, as any digit must come from the same sequence.
10418 * The only scripts that have multiple sequences have been constructed
10419 * to be 0 in 'script_zeros[]'.
10421 * Here we check if it is a digit. */
10422 if ( cp >= FIRST_NON_ASCII_DECIMAL_DIGIT
10423 && ( ( zero_of_run == 0
10424 || ( ( script_of_char >= 0
10425 && script_zeros[script_of_char] == 0)
10426 || intersection))))
10428 SSize_t range_zero_index;
10429 range_zero_index = _invlist_search(decimals_invlist, cp);
10430 if ( LIKELY(range_zero_index >= 0)
10431 && ELEMENT_RANGE_MATCHES_INVLIST(range_zero_index))
10433 UV range_zero = decimals_array[range_zero_index];
10435 if (zero_of_run != range_zero) {
10441 zero_of_run = range_zero;
10445 } /* end of looping through CLOSESR text */
10447 Safefree(intersection);
10451 #endif /* ifndef PERL_IN_XSUB_RE */
10454 * ex: set ts=8 sts=4 sw=4 et: