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) \
178 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
179 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
181 /* for use after a quantifier and before an EXACT-like node -- japhy */
182 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
184 * NOTE that *nothing* that affects backtracking should be in here, specifically
185 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
186 * node that is in between two EXACT like nodes when ascertaining what the required
187 * "follow" character is. This should probably be moved to regex compile time
188 * although it may be done at run time beause of the REF possibility - more
189 * investigation required. -- demerphq
191 #define JUMPABLE(rn) ( \
193 (OP(rn) == CLOSE && \
194 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
196 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
197 OP(rn) == PLUS || OP(rn) == MINMOD || \
199 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
201 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
203 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
206 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
207 we don't need this definition. XXX These are now out-of-sync*/
208 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
209 #define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFAA || OP(rn)==EXACTFAA_NO_TRIE || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
210 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
213 /* ... so we use this as its faster. */
214 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
215 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFAA || OP(rn) == EXACTFAA_NO_TRIE)
216 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
217 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
222 Search for mandatory following text node; for lookahead, the text must
223 follow but for lookbehind (rn->flags != 0) we skip to the next step.
225 #define FIND_NEXT_IMPT(rn) STMT_START { \
226 while (JUMPABLE(rn)) { \
227 const OPCODE type = OP(rn); \
228 if (type == SUSPEND || PL_regkind[type] == CURLY) \
229 rn = NEXTOPER(NEXTOPER(rn)); \
230 else if (type == PLUS) \
232 else if (type == IFMATCH) \
233 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
234 else rn += NEXT_OFF(rn); \
238 #define SLAB_FIRST(s) (&(s)->states[0])
239 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
241 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
242 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
243 static regmatch_state * S_push_slab(pTHX);
245 #define REGCP_PAREN_ELEMS 3
246 #define REGCP_OTHER_ELEMS 3
247 #define REGCP_FRAME_ELEMS 1
248 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
249 * are needed for the regexp context stack bookkeeping. */
252 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
254 const int retval = PL_savestack_ix;
255 const int paren_elems_to_push =
256 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
257 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
258 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
260 GET_RE_DEBUG_FLAGS_DECL;
262 PERL_ARGS_ASSERT_REGCPPUSH;
264 if (paren_elems_to_push < 0)
265 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
266 (int)paren_elems_to_push, (int)maxopenparen,
267 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
269 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
270 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
271 " out of range (%lu-%ld)",
273 (unsigned long)maxopenparen,
276 SSGROW(total_elems + REGCP_FRAME_ELEMS);
279 if ((int)maxopenparen > (int)parenfloor)
280 Perl_re_exec_indentf( aTHX_
281 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
287 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
288 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
289 SSPUSHIV(rex->offs[p].end);
290 SSPUSHIV(rex->offs[p].start);
291 SSPUSHINT(rex->offs[p].start_tmp);
292 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
293 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
296 (IV)rex->offs[p].start,
297 (IV)rex->offs[p].start_tmp,
301 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
302 SSPUSHINT(maxopenparen);
303 SSPUSHINT(rex->lastparen);
304 SSPUSHINT(rex->lastcloseparen);
305 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
310 /* These are needed since we do not localize EVAL nodes: */
311 #define REGCP_SET(cp) \
313 Perl_re_exec_indentf( aTHX_ \
314 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
315 depth, (IV)PL_savestack_ix \
320 #define REGCP_UNWIND(cp) \
322 if (cp != PL_savestack_ix) \
323 Perl_re_exec_indentf( aTHX_ \
324 "Clearing an EVAL scope, savestack=%" \
325 IVdf "..%" IVdf "\n", \
326 depth, (IV)(cp), (IV)PL_savestack_ix \
331 #define UNWIND_PAREN(lp, lcp) \
332 for (n = rex->lastparen; n > lp; n--) \
333 rex->offs[n].end = -1; \
334 rex->lastparen = n; \
335 rex->lastcloseparen = lcp;
339 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
343 GET_RE_DEBUG_FLAGS_DECL;
345 PERL_ARGS_ASSERT_REGCPPOP;
347 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
349 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
350 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
351 rex->lastcloseparen = SSPOPINT;
352 rex->lastparen = SSPOPINT;
353 *maxopenparen_p = SSPOPINT;
355 i -= REGCP_OTHER_ELEMS;
356 /* Now restore the parentheses context. */
358 if (i || rex->lastparen + 1 <= rex->nparens)
359 Perl_re_exec_indentf( aTHX_
360 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
366 paren = *maxopenparen_p;
367 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
369 rex->offs[paren].start_tmp = SSPOPINT;
370 rex->offs[paren].start = SSPOPIV;
372 if (paren <= rex->lastparen)
373 rex->offs[paren].end = tmps;
374 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
375 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
378 (IV)rex->offs[paren].start,
379 (IV)rex->offs[paren].start_tmp,
380 (IV)rex->offs[paren].end,
381 (paren > rex->lastparen ? "(skipped)" : ""));
386 /* It would seem that the similar code in regtry()
387 * already takes care of this, and in fact it is in
388 * a better location to since this code can #if 0-ed out
389 * but the code in regtry() is needed or otherwise tests
390 * requiring null fields (pat.t#187 and split.t#{13,14}
391 * (as of patchlevel 7877) will fail. Then again,
392 * this code seems to be necessary or otherwise
393 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
394 * --jhi updated by dapm */
395 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
396 if (i > *maxopenparen_p)
397 rex->offs[i].start = -1;
398 rex->offs[i].end = -1;
399 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
400 " \\%" UVuf ": %s ..-1 undeffing\n",
403 (i > *maxopenparen_p) ? "-1" : " "
409 /* restore the parens and associated vars at savestack position ix,
410 * but without popping the stack */
413 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
415 I32 tmpix = PL_savestack_ix;
416 PERL_ARGS_ASSERT_REGCP_RESTORE;
418 PL_savestack_ix = ix;
419 regcppop(rex, maxopenparen_p);
420 PL_savestack_ix = tmpix;
423 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
425 #ifndef PERL_IN_XSUB_RE
428 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
430 /* Returns a boolean as to whether or not 'character' is a member of the
431 * Posix character class given by 'classnum' that should be equivalent to a
432 * value in the typedef '_char_class_number'.
434 * Ideally this could be replaced by a just an array of function pointers
435 * to the C library functions that implement the macros this calls.
436 * However, to compile, the precise function signatures are required, and
437 * these may vary from platform to to platform. To avoid having to figure
438 * out what those all are on each platform, I (khw) am using this method,
439 * which adds an extra layer of function call overhead (unless the C
440 * optimizer strips it away). But we don't particularly care about
441 * performance with locales anyway. */
443 switch ((_char_class_number) classnum) {
444 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
445 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
446 case _CC_ENUM_ASCII: return isASCII_LC(character);
447 case _CC_ENUM_BLANK: return isBLANK_LC(character);
448 case _CC_ENUM_CASED: return isLOWER_LC(character)
449 || isUPPER_LC(character);
450 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
451 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
452 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
453 case _CC_ENUM_LOWER: return isLOWER_LC(character);
454 case _CC_ENUM_PRINT: return isPRINT_LC(character);
455 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
456 case _CC_ENUM_SPACE: return isSPACE_LC(character);
457 case _CC_ENUM_UPPER: return isUPPER_LC(character);
458 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
459 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
460 default: /* VERTSPACE should never occur in locales */
461 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
464 NOT_REACHED; /* NOTREACHED */
471 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character, const U8* e)
473 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
474 * 'character' is a member of the Posix character class given by 'classnum'
475 * that should be equivalent to a value in the typedef
476 * '_char_class_number'.
478 * This just calls isFOO_lc on the code point for the character if it is in
479 * the range 0-255. Outside that range, all characters use Unicode
480 * rules, ignoring any locale. So use the Unicode function if this class
481 * requires a swash, and use the Unicode macro otherwise. */
483 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
485 if (UTF8_IS_INVARIANT(*character)) {
486 return isFOO_lc(classnum, *character);
488 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
489 return isFOO_lc(classnum,
490 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
493 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, e);
495 switch ((_char_class_number) classnum) {
496 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
497 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
498 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
499 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
501 return _invlist_contains_cp(PL_XPosix_ptrs[classnum],
502 utf8_to_uvchr_buf(character, e, NULL));
505 return FALSE; /* Things like CNTRL are always below 256 */
509 S_find_next_ascii(char * s, const char * send, const bool utf8_target)
511 /* Returns the position of the first ASCII byte in the sequence between 's'
512 * and 'send-1' inclusive; returns 'send' if none found */
514 PERL_ARGS_ASSERT_FIND_NEXT_ASCII;
518 if ((STRLEN) (send - s) >= PERL_WORDSIZE
520 /* This term is wordsize if subword; 0 if not */
521 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
524 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
527 /* Process per-byte until reach word boundary. XXX This loop could be
528 * eliminated if we knew that this platform had fast unaligned reads */
529 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
533 s++; /* khw didn't bother creating a separate loop for
537 /* Here, we know we have at least one full word to process. Process
538 * per-word as long as we have at least a full word left */
540 PERL_UINTMAX_T complemented = ~ * (PERL_UINTMAX_T *) s;
541 if (complemented & PERL_VARIANTS_WORD_MASK) {
543 # if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678 \
544 || BYTEORDER == 0x4321 || BYTEORDER == 0x87654321
546 s += _variant_byte_number(complemented);
549 # else /* If weird byte order, drop into next loop to do byte-at-a-time
558 } while (s + PERL_WORDSIZE <= send);
563 /* Process per-character */
585 S_find_next_non_ascii(char * s, const char * send, const bool utf8_target)
587 /* Returns the position of the first non-ASCII byte in the sequence between
588 * 's' and 'send-1' inclusive; returns 'send' if none found */
592 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
596 if ( ! isASCII(*s)) {
604 if ( ! isASCII(*s)) {
615 const U8 * next_non_ascii = NULL;
617 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
618 PERL_UNUSED_ARG(utf8_target);
620 /* On ASCII platforms invariants and ASCII are identical, so if the string
621 * is entirely invariants, there is no non-ASCII character */
622 return (is_utf8_invariant_string_loc((U8 *) s,
626 : (char *) next_non_ascii;
633 S_find_span_end(U8 * s, const U8 * send, const U8 span_byte)
635 /* Returns the position of the first byte in the sequence between 's' and
636 * 'send-1' inclusive that isn't 'span_byte'; returns 'send' if none found.
639 PERL_ARGS_ASSERT_FIND_SPAN_END;
643 if ((STRLEN) (send - s) >= PERL_WORDSIZE
644 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
645 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
647 PERL_UINTMAX_T span_word;
649 /* Process per-byte until reach word boundary. XXX This loop could be
650 * eliminated if we knew that this platform had fast unaligned reads */
651 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
652 if (*s != span_byte) {
658 /* Create a word filled with the bytes we are spanning */
659 span_word = PERL_COUNT_MULTIPLIER * span_byte;
661 /* Process per-word as long as we have at least a full word left */
664 /* Keep going if the whole word is composed of 'span_byte's */
665 if ((* (PERL_UINTMAX_T *) s) == span_word) {
670 /* Here, at least one byte in the word isn't 'span_byte'. */
678 /* This xor leaves 1 bits only in those non-matching bytes */
679 span_word ^= * (PERL_UINTMAX_T *) s;
681 /* Make sure the upper bit of each non-matching byte is set. This
682 * makes each such byte look like an ASCII platform variant byte */
683 span_word |= span_word << 1;
684 span_word |= span_word << 2;
685 span_word |= span_word << 4;
687 /* That reduces the problem to what this function solves */
688 return s + _variant_byte_number(span_word);
692 } while (s + PERL_WORDSIZE <= send);
695 /* Process the straggler bytes beyond the final word boundary */
697 if (*s != span_byte) {
707 S_find_next_masked(U8 * s, const U8 * send, const U8 byte, const U8 mask)
709 /* Returns the position of the first byte in the sequence between 's'
710 * and 'send-1' inclusive that when ANDed with 'mask' yields 'byte';
711 * returns 'send' if none found. It uses word-level operations instead of
712 * byte to speed up the process */
714 PERL_ARGS_ASSERT_FIND_NEXT_MASKED;
717 assert((byte & mask) == byte);
721 if ((STRLEN) (send - s) >= PERL_WORDSIZE
722 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
723 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
725 PERL_UINTMAX_T word_complemented, mask_word;
727 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
728 if (((*s) & mask) == byte) {
734 word_complemented = ~ (PERL_COUNT_MULTIPLIER * byte);
735 mask_word = PERL_COUNT_MULTIPLIER * mask;
738 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
740 /* If 'masked' contains 'byte' within it, anding with the
741 * complement will leave those 8 bits 0 */
742 masked &= word_complemented;
744 /* This causes the most significant bit to be set to 1 for any
745 * bytes in the word that aren't completely 0 */
746 masked |= masked << 1;
747 masked |= masked << 2;
748 masked |= masked << 4;
750 /* The msbits are the same as what marks a byte as variant, so we
751 * can use this mask. If all msbits are 1, the word doesn't
753 if ((masked & PERL_VARIANTS_WORD_MASK) == PERL_VARIANTS_WORD_MASK) {
758 /* Here, the msbit of bytes in the word that aren't 'byte' are 1,
759 * and any that are, are 0. Complement and re-AND to swap that */
761 masked &= PERL_VARIANTS_WORD_MASK;
763 /* This reduces the problem to that solved by this function */
764 s += _variant_byte_number(masked);
767 } while (s + PERL_WORDSIZE <= send);
773 if (((*s) & mask) == byte) {
783 S_find_span_end_mask(U8 * s, const U8 * send, const U8 span_byte, const U8 mask)
785 /* Returns the position of the first byte in the sequence between 's' and
786 * 'send-1' inclusive that when ANDed with 'mask' isn't 'span_byte'.
787 * 'span_byte' should have been ANDed with 'mask' in the call of this
788 * function. Returns 'send' if none found. Works like find_span_end(),
789 * except for the AND */
791 PERL_ARGS_ASSERT_FIND_SPAN_END_MASK;
794 assert((span_byte & mask) == span_byte);
796 if ((STRLEN) (send - s) >= PERL_WORDSIZE
797 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
798 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
800 PERL_UINTMAX_T span_word, mask_word;
802 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
803 if (((*s) & mask) != span_byte) {
809 span_word = PERL_COUNT_MULTIPLIER * span_byte;
810 mask_word = PERL_COUNT_MULTIPLIER * mask;
813 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
815 if (masked == span_word) {
827 masked |= masked << 1;
828 masked |= masked << 2;
829 masked |= masked << 4;
830 return s + _variant_byte_number(masked);
834 } while (s + PERL_WORDSIZE <= send);
838 if (((*s) & mask) != span_byte) {
848 * pregexec and friends
851 #ifndef PERL_IN_XSUB_RE
853 - pregexec - match a regexp against a string
856 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
857 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
858 /* stringarg: the point in the string at which to begin matching */
859 /* strend: pointer to null at end of string */
860 /* strbeg: real beginning of string */
861 /* minend: end of match must be >= minend bytes after stringarg. */
862 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
863 * itself is accessed via the pointers above */
864 /* nosave: For optimizations. */
866 PERL_ARGS_ASSERT_PREGEXEC;
869 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
870 nosave ? 0 : REXEC_COPY_STR);
876 /* re_intuit_start():
878 * Based on some optimiser hints, try to find the earliest position in the
879 * string where the regex could match.
881 * rx: the regex to match against
882 * sv: the SV being matched: only used for utf8 flag; the string
883 * itself is accessed via the pointers below. Note that on
884 * something like an overloaded SV, SvPOK(sv) may be false
885 * and the string pointers may point to something unrelated to
887 * strbeg: real beginning of string
888 * strpos: the point in the string at which to begin matching
889 * strend: pointer to the byte following the last char of the string
890 * flags currently unused; set to 0
891 * data: currently unused; set to NULL
893 * The basic idea of re_intuit_start() is to use some known information
894 * about the pattern, namely:
896 * a) the longest known anchored substring (i.e. one that's at a
897 * constant offset from the beginning of the pattern; but not
898 * necessarily at a fixed offset from the beginning of the
900 * b) the longest floating substring (i.e. one that's not at a constant
901 * offset from the beginning of the pattern);
902 * c) Whether the pattern is anchored to the string; either
903 * an absolute anchor: /^../, or anchored to \n: /^.../m,
904 * or anchored to pos(): /\G/;
905 * d) A start class: a real or synthetic character class which
906 * represents which characters are legal at the start of the pattern;
908 * to either quickly reject the match, or to find the earliest position
909 * within the string at which the pattern might match, thus avoiding
910 * running the full NFA engine at those earlier locations, only to
911 * eventually fail and retry further along.
913 * Returns NULL if the pattern can't match, or returns the address within
914 * the string which is the earliest place the match could occur.
916 * The longest of the anchored and floating substrings is called 'check'
917 * and is checked first. The other is called 'other' and is checked
918 * second. The 'other' substring may not be present. For example,
920 * /(abc|xyz)ABC\d{0,3}DEFG/
924 * check substr (float) = "DEFG", offset 6..9 chars
925 * other substr (anchored) = "ABC", offset 3..3 chars
928 * Be aware that during the course of this function, sometimes 'anchored'
929 * refers to a substring being anchored relative to the start of the
930 * pattern, and sometimes to the pattern itself being anchored relative to
931 * the string. For example:
933 * /\dabc/: "abc" is anchored to the pattern;
934 * /^\dabc/: "abc" is anchored to the pattern and the string;
935 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
936 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
937 * but the pattern is anchored to the string.
941 Perl_re_intuit_start(pTHX_
944 const char * const strbeg,
948 re_scream_pos_data *data)
950 struct regexp *const prog = ReANY(rx);
951 SSize_t start_shift = prog->check_offset_min;
952 /* Should be nonnegative! */
953 SSize_t end_shift = 0;
954 /* current lowest pos in string where the regex can start matching */
955 char *rx_origin = strpos;
957 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
958 U8 other_ix = 1 - prog->substrs->check_ix;
960 char *other_last = strpos;/* latest pos 'other' substr already checked to */
961 char *check_at = NULL; /* check substr found at this pos */
962 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
963 RXi_GET_DECL(prog,progi);
964 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
965 regmatch_info *const reginfo = ®info_buf;
966 GET_RE_DEBUG_FLAGS_DECL;
968 PERL_ARGS_ASSERT_RE_INTUIT_START;
969 PERL_UNUSED_ARG(flags);
970 PERL_UNUSED_ARG(data);
972 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
973 "Intuit: trying to determine minimum start position...\n"));
975 /* for now, assume that all substr offsets are positive. If at some point
976 * in the future someone wants to do clever things with lookbehind and
977 * -ve offsets, they'll need to fix up any code in this function
978 * which uses these offsets. See the thread beginning
979 * <20140113145929.GF27210@iabyn.com>
981 assert(prog->substrs->data[0].min_offset >= 0);
982 assert(prog->substrs->data[0].max_offset >= 0);
983 assert(prog->substrs->data[1].min_offset >= 0);
984 assert(prog->substrs->data[1].max_offset >= 0);
985 assert(prog->substrs->data[2].min_offset >= 0);
986 assert(prog->substrs->data[2].max_offset >= 0);
988 /* for now, assume that if both present, that the floating substring
989 * doesn't start before the anchored substring.
990 * If you break this assumption (e.g. doing better optimisations
991 * with lookahead/behind), then you'll need to audit the code in this
992 * function carefully first
995 ! ( (prog->anchored_utf8 || prog->anchored_substr)
996 && (prog->float_utf8 || prog->float_substr))
997 || (prog->float_min_offset >= prog->anchored_offset));
999 /* byte rather than char calculation for efficiency. It fails
1000 * to quickly reject some cases that can't match, but will reject
1001 * them later after doing full char arithmetic */
1002 if (prog->minlen > strend - strpos) {
1003 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1004 " String too short...\n"));
1008 RXp_MATCH_UTF8_set(prog, utf8_target);
1009 reginfo->is_utf8_target = cBOOL(utf8_target);
1010 reginfo->info_aux = NULL;
1011 reginfo->strbeg = strbeg;
1012 reginfo->strend = strend;
1013 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
1014 reginfo->intuit = 1;
1015 /* not actually used within intuit, but zero for safety anyway */
1016 reginfo->poscache_maxiter = 0;
1019 if ((!prog->anchored_utf8 && prog->anchored_substr)
1020 || (!prog->float_utf8 && prog->float_substr))
1021 to_utf8_substr(prog);
1022 check = prog->check_utf8;
1024 if (!prog->check_substr && prog->check_utf8) {
1025 if (! to_byte_substr(prog)) {
1026 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
1029 check = prog->check_substr;
1032 /* dump the various substring data */
1033 DEBUG_OPTIMISE_MORE_r({
1035 for (i=0; i<=2; i++) {
1036 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
1037 : prog->substrs->data[i].substr);
1041 Perl_re_printf( aTHX_
1042 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
1043 " useful=%" IVdf " utf8=%d [%s]\n",
1045 (IV)prog->substrs->data[i].min_offset,
1046 (IV)prog->substrs->data[i].max_offset,
1047 (IV)prog->substrs->data[i].end_shift,
1049 utf8_target ? 1 : 0,
1054 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
1056 /* ml_anch: check after \n?
1058 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
1059 * with /.*.../, these flags will have been added by the
1061 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
1062 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
1064 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
1065 && !(prog->intflags & PREGf_IMPLICIT);
1067 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
1068 /* we are only allowed to match at BOS or \G */
1070 /* trivially reject if there's a BOS anchor and we're not at BOS.
1072 * Note that we don't try to do a similar quick reject for
1073 * \G, since generally the caller will have calculated strpos
1074 * based on pos() and gofs, so the string is already correctly
1075 * anchored by definition; and handling the exceptions would
1076 * be too fiddly (e.g. REXEC_IGNOREPOS).
1078 if ( strpos != strbeg
1079 && (prog->intflags & PREGf_ANCH_SBOL))
1081 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1082 " Not at start...\n"));
1086 /* in the presence of an anchor, the anchored (relative to the
1087 * start of the regex) substr must also be anchored relative
1088 * to strpos. So quickly reject if substr isn't found there.
1089 * This works for \G too, because the caller will already have
1090 * subtracted gofs from pos, and gofs is the offset from the
1091 * \G to the start of the regex. For example, in /.abc\Gdef/,
1092 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
1093 * caller will have set strpos=pos()-4; we look for the substr
1094 * at position pos()-4+1, which lines up with the "a" */
1096 if (prog->check_offset_min == prog->check_offset_max) {
1097 /* Substring at constant offset from beg-of-str... */
1098 SSize_t slen = SvCUR(check);
1099 char *s = HOP3c(strpos, prog->check_offset_min, strend);
1101 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1102 " Looking for check substr at fixed offset %" IVdf "...\n",
1103 (IV)prog->check_offset_min));
1105 if (SvTAIL(check)) {
1106 /* In this case, the regex is anchored at the end too.
1107 * Unless it's a multiline match, the lengths must match
1108 * exactly, give or take a \n. NB: slen >= 1 since
1109 * the last char of check is \n */
1111 && ( strend - s > slen
1112 || strend - s < slen - 1
1113 || (strend - s == slen && strend[-1] != '\n')))
1115 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1116 " String too long...\n"));
1119 /* Now should match s[0..slen-2] */
1122 if (slen && (strend - s < slen
1123 || *SvPVX_const(check) != *s
1124 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
1126 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1127 " String not equal...\n"));
1132 goto success_at_start;
1137 end_shift = prog->check_end_shift;
1139 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
1141 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
1142 (IV)end_shift, RX_PRECOMP(rx));
1147 /* This is the (re)entry point of the main loop in this function.
1148 * The goal of this loop is to:
1149 * 1) find the "check" substring in the region rx_origin..strend
1150 * (adjusted by start_shift / end_shift). If not found, reject
1152 * 2) If it exists, look for the "other" substr too if defined; for
1153 * example, if the check substr maps to the anchored substr, then
1154 * check the floating substr, and vice-versa. If not found, go
1155 * back to (1) with rx_origin suitably incremented.
1156 * 3) If we find an rx_origin position that doesn't contradict
1157 * either of the substrings, then check the possible additional
1158 * constraints on rx_origin of /^.../m or a known start class.
1159 * If these fail, then depending on which constraints fail, jump
1160 * back to here, or to various other re-entry points further along
1161 * that skip some of the first steps.
1162 * 4) If we pass all those tests, update the BmUSEFUL() count on the
1163 * substring. If the start position was determined to be at the
1164 * beginning of the string - so, not rejected, but not optimised,
1165 * since we have to run regmatch from position 0 - decrement the
1166 * BmUSEFUL() count. Otherwise increment it.
1170 /* first, look for the 'check' substring */
1176 DEBUG_OPTIMISE_MORE_r({
1177 Perl_re_printf( aTHX_
1178 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
1179 " Start shift: %" IVdf " End shift %" IVdf
1180 " Real end Shift: %" IVdf "\n",
1181 (IV)(rx_origin - strbeg),
1182 (IV)prog->check_offset_min,
1185 (IV)prog->check_end_shift);
1188 end_point = HOPBACK3(strend, end_shift, rx_origin);
1191 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
1196 /* If the regex is absolutely anchored to either the start of the
1197 * string (SBOL) or to pos() (ANCH_GPOS), then
1198 * check_offset_max represents an upper bound on the string where
1199 * the substr could start. For the ANCH_GPOS case, we assume that
1200 * the caller of intuit will have already set strpos to
1201 * pos()-gofs, so in this case strpos + offset_max will still be
1202 * an upper bound on the substr.
1205 && prog->intflags & PREGf_ANCH
1206 && prog->check_offset_max != SSize_t_MAX)
1208 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
1209 const char * const anchor =
1210 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
1211 SSize_t targ_len = (char*)end_point - anchor;
1213 if (check_len > targ_len) {
1214 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1215 "Target string too short to match required substring...\n"));
1219 /* do a bytes rather than chars comparison. It's conservative;
1220 * so it skips doing the HOP if the result can't possibly end
1221 * up earlier than the old value of end_point.
1223 assert(anchor + check_len <= (char *)end_point);
1224 if (prog->check_offset_max + check_len < targ_len) {
1225 end_point = HOP3lim((U8*)anchor,
1226 prog->check_offset_max,
1227 end_point - check_len
1230 if (end_point < start_point)
1235 check_at = fbm_instr( start_point, end_point,
1236 check, multiline ? FBMrf_MULTILINE : 0);
1238 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1239 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1240 (IV)((char*)start_point - strbeg),
1241 (IV)((char*)end_point - strbeg),
1242 (IV)(check_at ? check_at - strbeg : -1)
1245 /* Update the count-of-usability, remove useless subpatterns,
1249 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1250 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
1251 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
1252 (check_at ? "Found" : "Did not find"),
1253 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
1254 ? "anchored" : "floating"),
1257 (check_at ? " at offset " : "...\n") );
1262 /* set rx_origin to the minimum position where the regex could start
1263 * matching, given the constraint of the just-matched check substring.
1264 * But don't set it lower than previously.
1267 if (check_at - rx_origin > prog->check_offset_max)
1268 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
1269 /* Finish the diagnostic message */
1270 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1271 "%ld (rx_origin now %" IVdf ")...\n",
1272 (long)(check_at - strbeg),
1273 (IV)(rx_origin - strbeg)
1278 /* now look for the 'other' substring if defined */
1280 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
1281 : prog->substrs->data[other_ix].substr)
1283 /* Take into account the "other" substring. */
1287 struct reg_substr_datum *other;
1290 other = &prog->substrs->data[other_ix];
1292 /* if "other" is anchored:
1293 * we've previously found a floating substr starting at check_at.
1294 * This means that the regex origin must lie somewhere
1295 * between min (rx_origin): HOP3(check_at, -check_offset_max)
1296 * and max: HOP3(check_at, -check_offset_min)
1297 * (except that min will be >= strpos)
1298 * So the fixed substr must lie somewhere between
1299 * HOP3(min, anchored_offset)
1300 * HOP3(max, anchored_offset) + SvCUR(substr)
1303 /* if "other" is floating
1304 * Calculate last1, the absolute latest point where the
1305 * floating substr could start in the string, ignoring any
1306 * constraints from the earlier fixed match. It is calculated
1309 * strend - prog->minlen (in chars) is the absolute latest
1310 * position within the string where the origin of the regex
1311 * could appear. The latest start point for the floating
1312 * substr is float_min_offset(*) on from the start of the
1313 * regex. last1 simply combines thee two offsets.
1315 * (*) You might think the latest start point should be
1316 * float_max_offset from the regex origin, and technically
1317 * you'd be correct. However, consider
1319 * Here, float min, max are 3,5 and minlen is 7.
1320 * This can match either
1324 * In the first case, the regex matches minlen chars; in the
1325 * second, minlen+1, in the third, minlen+2.
1326 * In the first case, the floating offset is 3 (which equals
1327 * float_min), in the second, 4, and in the third, 5 (which
1328 * equals float_max). In all cases, the floating string bcd
1329 * can never start more than 4 chars from the end of the
1330 * string, which equals minlen - float_min. As the substring
1331 * starts to match more than float_min from the start of the
1332 * regex, it makes the regex match more than minlen chars,
1333 * and the two cancel each other out. So we can always use
1334 * float_min - minlen, rather than float_max - minlen for the
1335 * latest position in the string.
1337 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1338 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1341 assert(prog->minlen >= other->min_offset);
1342 last1 = HOP3c(strend,
1343 other->min_offset - prog->minlen, strbeg);
1345 if (other_ix) {/* i.e. if (other-is-float) */
1346 /* last is the latest point where the floating substr could
1347 * start, *given* any constraints from the earlier fixed
1348 * match. This constraint is that the floating string starts
1349 * <= float_max_offset chars from the regex origin (rx_origin).
1350 * If this value is less than last1, use it instead.
1352 assert(rx_origin <= last1);
1354 /* this condition handles the offset==infinity case, and
1355 * is a short-cut otherwise. Although it's comparing a
1356 * byte offset to a char length, it does so in a safe way,
1357 * since 1 char always occupies 1 or more bytes,
1358 * so if a string range is (last1 - rx_origin) bytes,
1359 * it will be less than or equal to (last1 - rx_origin)
1360 * chars; meaning it errs towards doing the accurate HOP3
1361 * rather than just using last1 as a short-cut */
1362 (last1 - rx_origin) < other->max_offset
1364 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1367 assert(strpos + start_shift <= check_at);
1368 last = HOP4c(check_at, other->min_offset - start_shift,
1372 s = HOP3c(rx_origin, other->min_offset, strend);
1373 if (s < other_last) /* These positions already checked */
1376 must = utf8_target ? other->utf8_substr : other->substr;
1377 assert(SvPOK(must));
1380 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1386 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1387 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1388 (IV)(from - strbeg),
1394 (unsigned char*)from,
1397 multiline ? FBMrf_MULTILINE : 0
1399 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1400 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1401 (IV)(from - strbeg),
1403 (IV)(s ? s - strbeg : -1)
1409 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1410 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1411 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1412 s ? "Found" : "Contradicts",
1413 other_ix ? "floating" : "anchored",
1414 quoted, RE_SV_TAIL(must));
1419 /* last1 is latest possible substr location. If we didn't
1420 * find it before there, we never will */
1421 if (last >= last1) {
1422 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1423 "; giving up...\n"));
1427 /* try to find the check substr again at a later
1428 * position. Maybe next time we'll find the "other" substr
1430 other_last = HOP3c(last, 1, strend) /* highest failure */;
1432 other_ix /* i.e. if other-is-float */
1433 ? HOP3c(rx_origin, 1, strend)
1434 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1435 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1436 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1437 (other_ix ? "floating" : "anchored"),
1438 (long)(HOP3c(check_at, 1, strend) - strbeg),
1439 (IV)(rx_origin - strbeg)
1444 if (other_ix) { /* if (other-is-float) */
1445 /* other_last is set to s, not s+1, since its possible for
1446 * a floating substr to fail first time, then succeed
1447 * second time at the same floating position; e.g.:
1448 * "-AB--AABZ" =~ /\wAB\d*Z/
1449 * The first time round, anchored and float match at
1450 * "-(AB)--AAB(Z)" then fail on the initial \w character
1451 * class. Second time round, they match at "-AB--A(AB)(Z)".
1456 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1457 other_last = HOP3c(s, 1, strend);
1459 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1460 " at offset %ld (rx_origin now %" IVdf ")...\n",
1462 (IV)(rx_origin - strbeg)
1468 DEBUG_OPTIMISE_MORE_r(
1469 Perl_re_printf( aTHX_
1470 " Check-only match: offset min:%" IVdf " max:%" IVdf
1471 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1472 " strend:%" IVdf "\n",
1473 (IV)prog->check_offset_min,
1474 (IV)prog->check_offset_max,
1475 (IV)(check_at-strbeg),
1476 (IV)(rx_origin-strbeg),
1477 (IV)(rx_origin-check_at),
1483 postprocess_substr_matches:
1485 /* handle the extra constraint of /^.../m if present */
1487 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1490 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1491 " looking for /^/m anchor"));
1493 /* we have failed the constraint of a \n before rx_origin.
1494 * Find the next \n, if any, even if it's beyond the current
1495 * anchored and/or floating substrings. Whether we should be
1496 * scanning ahead for the next \n or the next substr is debatable.
1497 * On the one hand you'd expect rare substrings to appear less
1498 * often than \n's. On the other hand, searching for \n means
1499 * we're effectively flipping between check_substr and "\n" on each
1500 * iteration as the current "rarest" string candidate, which
1501 * means for example that we'll quickly reject the whole string if
1502 * hasn't got a \n, rather than trying every substr position
1506 s = HOP3c(strend, - prog->minlen, strpos);
1507 if (s <= rx_origin ||
1508 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1510 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1511 " Did not find /%s^%s/m...\n",
1512 PL_colors[0], PL_colors[1]));
1516 /* earliest possible origin is 1 char after the \n.
1517 * (since *rx_origin == '\n', it's safe to ++ here rather than
1518 * HOP(rx_origin, 1)) */
1521 if (prog->substrs->check_ix == 0 /* check is anchored */
1522 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1524 /* Position contradicts check-string; either because
1525 * check was anchored (and thus has no wiggle room),
1526 * or check was float and rx_origin is above the float range */
1527 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1528 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1529 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1533 /* if we get here, the check substr must have been float,
1534 * is in range, and we may or may not have had an anchored
1535 * "other" substr which still contradicts */
1536 assert(prog->substrs->check_ix); /* check is float */
1538 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1539 /* whoops, the anchored "other" substr exists, so we still
1540 * contradict. On the other hand, the float "check" substr
1541 * didn't contradict, so just retry the anchored "other"
1543 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1544 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1545 PL_colors[0], PL_colors[1],
1546 (IV)(rx_origin - strbeg + prog->anchored_offset),
1547 (IV)(rx_origin - strbeg)
1549 goto do_other_substr;
1552 /* success: we don't contradict the found floating substring
1553 * (and there's no anchored substr). */
1554 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1555 " Found /%s^%s/m with rx_origin %ld...\n",
1556 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1559 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1560 " (multiline anchor test skipped)\n"));
1566 /* if we have a starting character class, then test that extra constraint.
1567 * (trie stclasses are too expensive to use here, we are better off to
1568 * leave it to regmatch itself) */
1570 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1571 const U8* const str = (U8*)STRING(progi->regstclass);
1573 /* XXX this value could be pre-computed */
1574 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1575 ? (reginfo->is_utf8_pat
1576 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1577 : STR_LEN(progi->regstclass))
1581 /* latest pos that a matching float substr constrains rx start to */
1582 char *rx_max_float = NULL;
1584 /* if the current rx_origin is anchored, either by satisfying an
1585 * anchored substring constraint, or a /^.../m constraint, then we
1586 * can reject the current origin if the start class isn't found
1587 * at the current position. If we have a float-only match, then
1588 * rx_origin is constrained to a range; so look for the start class
1589 * in that range. if neither, then look for the start class in the
1590 * whole rest of the string */
1592 /* XXX DAPM it's not clear what the minlen test is for, and why
1593 * it's not used in the floating case. Nothing in the test suite
1594 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1595 * Here are some old comments, which may or may not be correct:
1597 * minlen == 0 is possible if regstclass is \b or \B,
1598 * and the fixed substr is ''$.
1599 * Since minlen is already taken into account, rx_origin+1 is
1600 * before strend; accidentally, minlen >= 1 guaranties no false
1601 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1602 * 0) below assumes that regstclass does not come from lookahead...
1603 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1604 * This leaves EXACTF-ish only, which are dealt with in
1608 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1609 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1610 else if (prog->float_substr || prog->float_utf8) {
1611 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1612 endpos = HOP3clim(rx_max_float, cl_l, strend);
1617 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1618 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1619 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1620 (IV)start_shift, (IV)(check_at - strbeg),
1621 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1623 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1626 if (endpos == strend) {
1627 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1628 " Could not match STCLASS...\n") );
1631 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1632 " This position contradicts STCLASS...\n") );
1633 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1634 && !(prog->intflags & PREGf_IMPLICIT))
1637 /* Contradict one of substrings */
1638 if (prog->anchored_substr || prog->anchored_utf8) {
1639 if (prog->substrs->check_ix == 1) { /* check is float */
1640 /* Have both, check_string is floating */
1641 assert(rx_origin + start_shift <= check_at);
1642 if (rx_origin + start_shift != check_at) {
1643 /* not at latest position float substr could match:
1644 * Recheck anchored substring, but not floating.
1645 * The condition above is in bytes rather than
1646 * chars for efficiency. It's conservative, in
1647 * that it errs on the side of doing 'goto
1648 * do_other_substr'. In this case, at worst,
1649 * an extra anchored search may get done, but in
1650 * practice the extra fbm_instr() is likely to
1651 * get skipped anyway. */
1652 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1653 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1654 (long)(other_last - strbeg),
1655 (IV)(rx_origin - strbeg)
1657 goto do_other_substr;
1665 /* In the presence of ml_anch, we might be able to
1666 * find another \n without breaking the current float
1669 /* strictly speaking this should be HOP3c(..., 1, ...),
1670 * but since we goto a block of code that's going to
1671 * search for the next \n if any, its safe here */
1673 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1674 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1675 PL_colors[0], PL_colors[1],
1676 (long)(rx_origin - strbeg)) );
1677 goto postprocess_substr_matches;
1680 /* strictly speaking this can never be true; but might
1681 * be if we ever allow intuit without substrings */
1682 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1685 rx_origin = rx_max_float;
1688 /* at this point, any matching substrings have been
1689 * contradicted. Start again... */
1691 rx_origin = HOP3c(rx_origin, 1, strend);
1693 /* uses bytes rather than char calculations for efficiency.
1694 * It's conservative: it errs on the side of doing 'goto restart',
1695 * where there is code that does a proper char-based test */
1696 if (rx_origin + start_shift + end_shift > strend) {
1697 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1698 " Could not match STCLASS...\n") );
1701 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1702 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1703 (prog->substrs->check_ix ? "floating" : "anchored"),
1704 (long)(rx_origin + start_shift - strbeg),
1705 (IV)(rx_origin - strbeg)
1712 if (rx_origin != s) {
1713 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1714 " By STCLASS: moving %ld --> %ld\n",
1715 (long)(rx_origin - strbeg), (long)(s - strbeg))
1719 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1720 " Does not contradict STCLASS...\n");
1725 /* Decide whether using the substrings helped */
1727 if (rx_origin != strpos) {
1728 /* Fixed substring is found far enough so that the match
1729 cannot start at strpos. */
1731 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1732 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1735 /* The found rx_origin position does not prohibit matching at
1736 * strpos, so calling intuit didn't gain us anything. Decrement
1737 * the BmUSEFUL() count on the check substring, and if we reach
1739 if (!(prog->intflags & PREGf_NAUGHTY)
1741 prog->check_utf8 /* Could be deleted already */
1742 && --BmUSEFUL(prog->check_utf8) < 0
1743 && (prog->check_utf8 == prog->float_utf8)
1745 prog->check_substr /* Could be deleted already */
1746 && --BmUSEFUL(prog->check_substr) < 0
1747 && (prog->check_substr == prog->float_substr)
1750 /* If flags & SOMETHING - do not do it many times on the same match */
1751 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1752 /* XXX Does the destruction order has to change with utf8_target? */
1753 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1754 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1755 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1756 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1757 check = NULL; /* abort */
1758 /* XXXX This is a remnant of the old implementation. It
1759 looks wasteful, since now INTUIT can use many
1760 other heuristics. */
1761 prog->extflags &= ~RXf_USE_INTUIT;
1765 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1766 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1767 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1771 fail_finish: /* Substring not found */
1772 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1773 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1775 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1776 PL_colors[4], PL_colors[5]));
1781 #define DECL_TRIE_TYPE(scan) \
1782 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1783 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1784 trie_utf8l, trie_flu8, trie_flu8_latin } \
1785 trie_type = ((scan->flags == EXACT) \
1786 ? (utf8_target ? trie_utf8 : trie_plain) \
1787 : (scan->flags == EXACTL) \
1788 ? (utf8_target ? trie_utf8l : trie_plain) \
1789 : (scan->flags == EXACTFAA) \
1791 ? trie_utf8_exactfa_fold \
1792 : trie_latin_utf8_exactfa_fold) \
1793 : (scan->flags == EXACTFLU8 \
1796 : trie_flu8_latin) \
1799 : trie_latin_utf8_fold)))
1801 /* 'uscan' is set to foldbuf, and incremented, so below the end of uscan is
1802 * 'foldbuf+sizeof(foldbuf)' */
1803 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uc_end, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1806 U8 flags = FOLD_FLAGS_FULL; \
1807 switch (trie_type) { \
1809 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1810 if (UTF8_IS_ABOVE_LATIN1(*uc)) { \
1811 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc_end); \
1813 goto do_trie_utf8_fold; \
1814 case trie_utf8_exactfa_fold: \
1815 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1817 case trie_utf8_fold: \
1818 do_trie_utf8_fold: \
1819 if ( foldlen>0 ) { \
1820 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1825 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc_end, foldbuf, &foldlen, \
1827 len = UTF8SKIP(uc); \
1828 skiplen = UVCHR_SKIP( uvc ); \
1829 foldlen -= skiplen; \
1830 uscan = foldbuf + skiplen; \
1833 case trie_flu8_latin: \
1834 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1835 goto do_trie_latin_utf8_fold; \
1836 case trie_latin_utf8_exactfa_fold: \
1837 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1839 case trie_latin_utf8_fold: \
1840 do_trie_latin_utf8_fold: \
1841 if ( foldlen>0 ) { \
1842 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1848 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1849 skiplen = UVCHR_SKIP( uvc ); \
1850 foldlen -= skiplen; \
1851 uscan = foldbuf + skiplen; \
1855 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1856 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1857 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1861 uvc = utf8n_to_uvchr( (const U8*) uc, uc_end - uc, &len, uniflags ); \
1868 charid = trie->charmap[ uvc ]; \
1872 if (widecharmap) { \
1873 SV** const svpp = hv_fetch(widecharmap, \
1874 (char*)&uvc, sizeof(UV), 0); \
1876 charid = (U16)SvIV(*svpp); \
1881 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1882 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1883 startpos, doutf8, depth)
1885 #define REXEC_FBC_SCAN(UTF8, CODE) \
1887 while (s < strend) { \
1889 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1893 #define REXEC_FBC_CLASS_SCAN(UTF8, COND) \
1895 while (s < strend) { \
1896 REXEC_FBC_CLASS_SCAN_GUTS(UTF8, COND) \
1900 #define REXEC_FBC_CLASS_SCAN_GUTS(UTF8, COND) \
1903 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1904 previous_occurrence_end = s; \
1907 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1910 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1911 if (utf8_target) { \
1912 REXEC_FBC_CLASS_SCAN(1, CONDUTF8); \
1915 REXEC_FBC_CLASS_SCAN(0, COND); \
1918 /* We keep track of where the next character should start after an occurrence
1919 * of the one we're looking for. Knowing that, we can see right away if the
1920 * next occurrence is adjacent to the previous. When 'doevery' is FALSE, we
1921 * don't accept the 2nd and succeeding adjacent occurrences */
1922 #define FBC_CHECK_AND_TRY \
1924 || s != previous_occurrence_end) \
1925 && (reginfo->intuit || regtry(reginfo, &s))) \
1931 /* This differs from the above macros in that it calls a function which returns
1932 * the next occurrence of the thing being looked for in 's'; and 'strend' if
1933 * there is no such occurrence. */
1934 #define REXEC_FBC_FIND_NEXT_SCAN(UTF8, f) \
1935 while (s < strend) { \
1937 if (s >= strend) { \
1942 s += (UTF8) ? UTF8SKIP(s) : 1; \
1943 previous_occurrence_end = s; \
1946 /* The three macros below are slightly different versions of the same logic.
1948 * The first is for /a and /aa when the target string is UTF-8. This can only
1949 * match ascii, but it must advance based on UTF-8. The other two handle the
1950 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1951 * for the boundary (or non-boundary) between a word and non-word character.
1952 * The utf8 and non-utf8 cases have the same logic, but the details must be
1953 * different. Find the "wordness" of the character just prior to this one, and
1954 * compare it with the wordness of this one. If they differ, we have a
1955 * boundary. At the beginning of the string, pretend that the previous
1956 * character was a new-line.
1958 * All these macros uncleanly have side-effects with each other and outside
1959 * variables. So far it's been too much trouble to clean-up
1961 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1962 * a word character or not.
1963 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1965 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1967 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1968 * are looking for a boundary or for a non-boundary. If we are looking for a
1969 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1970 * see if this tentative match actually works, and if so, to quit the loop
1971 * here. And vice-versa if we are looking for a non-boundary.
1973 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1974 * REXEC_FBC_SCAN loops is a loop invariant, a bool giving the return of
1975 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1976 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1977 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1978 * complement. But in that branch we complement tmp, meaning that at the
1979 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1980 * which means at the top of the loop in the next iteration, it is
1981 * TEST_NON_UTF8(s-1) */
1982 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1983 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1984 tmp = TEST_NON_UTF8(tmp); \
1985 REXEC_FBC_SCAN(1, /* 1=>is-utf8; advances s while s < strend */ \
1986 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1988 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1995 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1996 * TEST_UTF8 is a macro that for the same input code points returns identically
1997 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1998 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1999 if (s == reginfo->strbeg) { \
2002 else { /* Back-up to the start of the previous character */ \
2003 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
2004 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
2005 0, UTF8_ALLOW_DEFAULT); \
2007 tmp = TEST_UV(tmp); \
2008 REXEC_FBC_SCAN(1, /* 1=>is-utf8; advances s while s < strend */ \
2009 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
2018 /* Like the above two macros. UTF8_CODE is the complete code for handling
2019 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
2021 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
2022 if (utf8_target) { \
2025 else { /* Not utf8 */ \
2026 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
2027 tmp = TEST_NON_UTF8(tmp); \
2028 REXEC_FBC_SCAN(0, /* 0=>not-utf8; advances s while s < strend */ \
2029 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
2038 /* Here, things have been set up by the previous code so that tmp is the \
2039 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
2040 * utf8ness of the target). We also have to check if this matches against \
2041 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
2042 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
2044 if (tmp == ! TEST_NON_UTF8('\n')) { \
2051 /* This is the macro to use when we want to see if something that looks like it
2052 * could match, actually does, and if so exits the loop */
2053 #define REXEC_FBC_TRYIT \
2054 if ((reginfo->intuit || regtry(reginfo, &s))) \
2057 /* The only difference between the BOUND and NBOUND cases is that
2058 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
2059 * NBOUND. This is accomplished by passing it as either the if or else clause,
2060 * with the other one being empty (PLACEHOLDER is defined as empty).
2062 * The TEST_FOO parameters are for operating on different forms of input, but
2063 * all should be ones that return identically for the same underlying code
2065 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2067 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
2068 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2070 #define FBC_BOUND_A(TEST_NON_UTF8) \
2072 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
2073 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2075 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2077 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2078 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2080 #define FBC_NBOUND_A(TEST_NON_UTF8) \
2082 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2083 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2087 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
2088 IV cp_out = Perl__invlist_search(invlist, cp_in);
2089 assert(cp_out >= 0);
2092 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2093 invmap[S_get_break_val_cp_checked(invlist, cp)]
2095 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2096 invmap[_invlist_search(invlist, cp)]
2099 /* Takes a pointer to an inversion list, a pointer to its corresponding
2100 * inversion map, and a code point, and returns the code point's value
2101 * according to the two arrays. It assumes that all code points have a value.
2102 * This is used as the base macro for macros for particular properties */
2103 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
2104 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
2106 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
2107 * of a code point, returning the value for the first code point in the string.
2108 * And it takes the particular macro name that finds the desired value given a
2109 * code point. Merely convert the UTF-8 to code point and call the cp macro */
2110 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
2111 (__ASSERT_(pos < strend) \
2112 /* Note assumes is valid UTF-8 */ \
2113 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
2115 /* Returns the GCB value for the input code point */
2116 #define getGCB_VAL_CP(cp) \
2117 _generic_GET_BREAK_VAL_CP( \
2122 /* Returns the GCB value for the first code point in the UTF-8 encoded string
2123 * bounded by pos and strend */
2124 #define getGCB_VAL_UTF8(pos, strend) \
2125 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
2127 /* Returns the LB value for the input code point */
2128 #define getLB_VAL_CP(cp) \
2129 _generic_GET_BREAK_VAL_CP( \
2134 /* Returns the LB value for the first code point in the UTF-8 encoded string
2135 * bounded by pos and strend */
2136 #define getLB_VAL_UTF8(pos, strend) \
2137 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
2140 /* Returns the SB value for the input code point */
2141 #define getSB_VAL_CP(cp) \
2142 _generic_GET_BREAK_VAL_CP( \
2147 /* Returns the SB value for the first code point in the UTF-8 encoded string
2148 * bounded by pos and strend */
2149 #define getSB_VAL_UTF8(pos, strend) \
2150 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
2152 /* Returns the WB value for the input code point */
2153 #define getWB_VAL_CP(cp) \
2154 _generic_GET_BREAK_VAL_CP( \
2159 /* Returns the WB value for the first code point in the UTF-8 encoded string
2160 * bounded by pos and strend */
2161 #define getWB_VAL_UTF8(pos, strend) \
2162 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
2164 /* We know what class REx starts with. Try to find this position... */
2165 /* if reginfo->intuit, its a dryrun */
2166 /* annoyingly all the vars in this routine have different names from their counterparts
2167 in regmatch. /grrr */
2169 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
2170 const char *strend, regmatch_info *reginfo)
2174 /* TRUE if x+ need not match at just the 1st pos of run of x's */
2175 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
2177 char *pat_string; /* The pattern's exactish string */
2178 char *pat_end; /* ptr to end char of pat_string */
2179 re_fold_t folder; /* Function for computing non-utf8 folds */
2180 const U8 *fold_array; /* array for folding ords < 256 */
2187 /* In some cases we accept only the first occurence of 'x' in a sequence of
2188 * them. This variable points to just beyond the end of the previous
2189 * occurrence of 'x', hence we can tell if we are in a sequence. (Having
2190 * it point to beyond the 'x' allows us to work for UTF-8 without having to
2192 char * previous_occurrence_end = 0;
2194 I32 tmp; /* Scratch variable */
2195 const bool utf8_target = reginfo->is_utf8_target;
2196 UV utf8_fold_flags = 0;
2197 const bool is_utf8_pat = reginfo->is_utf8_pat;
2198 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
2199 with a result inverts that result, as 0^1 =
2201 _char_class_number classnum;
2203 RXi_GET_DECL(prog,progi);
2205 PERL_ARGS_ASSERT_FIND_BYCLASS;
2207 /* We know what class it must start with. */
2210 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2212 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
2213 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
2220 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2221 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
2223 else if (ANYOF_FLAGS(c)) {
2224 REXEC_FBC_CLASS_SCAN(0, reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
2227 REXEC_FBC_CLASS_SCAN(0, ANYOF_BITMAP_TEST(c, *((U8*)s)));
2231 case ANYOFM: /* ARG() is the base byte; FLAGS() the mask byte */
2232 /* UTF-8ness doesn't matter, so use 0 */
2233 REXEC_FBC_FIND_NEXT_SCAN(0,
2234 (char *) find_next_masked((U8 *) s, (U8 *) strend,
2235 (U8) ARG(c), FLAGS(c)));
2238 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8 patterns */
2239 assert(! is_utf8_pat);
2242 if (is_utf8_pat || utf8_target) {
2243 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2244 goto do_exactf_utf8;
2246 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
2247 folder = foldEQ_latin1; /* /a, except the sharp s one which */
2248 goto do_exactf_non_utf8; /* isn't dealt with by these */
2250 case EXACTF: /* This node only generated for non-utf8 patterns */
2251 assert(! is_utf8_pat);
2253 utf8_fold_flags = 0;
2254 goto do_exactf_utf8;
2256 fold_array = PL_fold;
2258 goto do_exactf_non_utf8;
2261 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2262 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
2263 utf8_fold_flags = FOLDEQ_LOCALE;
2264 goto do_exactf_utf8;
2266 fold_array = PL_fold_locale;
2267 folder = foldEQ_locale;
2268 goto do_exactf_non_utf8;
2272 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2274 goto do_exactf_utf8;
2277 if (! utf8_target) { /* All code points in this node require
2278 UTF-8 to express. */
2281 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
2282 | FOLDEQ_S2_FOLDS_SANE;
2283 goto do_exactf_utf8;
2286 if (is_utf8_pat || utf8_target) {
2287 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
2288 goto do_exactf_utf8;
2291 /* Any 'ss' in the pattern should have been replaced by regcomp,
2292 * so we don't have to worry here about this single special case
2293 * in the Latin1 range */
2294 fold_array = PL_fold_latin1;
2295 folder = foldEQ_latin1;
2299 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
2300 are no glitches with fold-length differences
2301 between the target string and pattern */
2303 /* The idea in the non-utf8 EXACTF* cases is to first find the
2304 * first character of the EXACTF* node and then, if necessary,
2305 * case-insensitively compare the full text of the node. c1 is the
2306 * first character. c2 is its fold. This logic will not work for
2307 * Unicode semantics and the german sharp ss, which hence should
2308 * not be compiled into a node that gets here. */
2309 pat_string = STRING(c);
2310 ln = STR_LEN(c); /* length to match in octets/bytes */
2312 /* We know that we have to match at least 'ln' bytes (which is the
2313 * same as characters, since not utf8). If we have to match 3
2314 * characters, and there are only 2 availabe, we know without
2315 * trying that it will fail; so don't start a match past the
2316 * required minimum number from the far end */
2317 e = HOP3c(strend, -((SSize_t)ln), s);
2322 c2 = fold_array[c1];
2323 if (c1 == c2) { /* If char and fold are the same */
2325 s = (char *) memchr(s, c1, e + 1 - s);
2330 /* Check that the rest of the node matches */
2331 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2332 && (reginfo->intuit || regtry(reginfo, &s)) )
2340 U8 bits_differing = c1 ^ c2;
2342 /* If the folds differ in one bit position only, we can mask to
2343 * match either of them, and can use this faster find method. Both
2344 * ASCII and EBCDIC tend to have their case folds differ in only
2345 * one position, so this is very likely */
2346 if (LIKELY(PL_bitcount[bits_differing] == 1)) {
2347 bits_differing = ~ bits_differing;
2349 s = (char *) find_next_masked((U8 *) s, (U8 *) e + 1,
2350 (c1 & bits_differing), bits_differing);
2355 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2356 && (reginfo->intuit || regtry(reginfo, &s)) )
2363 else { /* Otherwise, stuck with looking byte-at-a-time. This
2364 should actually happen only in EXACTFL nodes */
2366 if ( (*(U8*)s == c1 || *(U8*)s == c2)
2367 && (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2368 && (reginfo->intuit || regtry(reginfo, &s)) )
2382 /* If one of the operands is in utf8, we can't use the simpler folding
2383 * above, due to the fact that many different characters can have the
2384 * same fold, or portion of a fold, or different- length fold */
2385 pat_string = STRING(c);
2386 ln = STR_LEN(c); /* length to match in octets/bytes */
2387 pat_end = pat_string + ln;
2388 lnc = is_utf8_pat /* length to match in characters */
2389 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2392 /* We have 'lnc' characters to match in the pattern, but because of
2393 * multi-character folding, each character in the target can match
2394 * up to 3 characters (Unicode guarantees it will never exceed
2395 * this) if it is utf8-encoded; and up to 2 if not (based on the
2396 * fact that the Latin 1 folds are already determined, and the
2397 * only multi-char fold in that range is the sharp-s folding to
2398 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2399 * string character. Adjust lnc accordingly, rounding up, so that
2400 * if we need to match at least 4+1/3 chars, that really is 5. */
2401 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2402 lnc = (lnc + expansion - 1) / expansion;
2404 /* As in the non-UTF8 case, if we have to match 3 characters, and
2405 * only 2 are left, it's guaranteed to fail, so don't start a
2406 * match that would require us to go beyond the end of the string
2408 e = HOP3c(strend, -((SSize_t)lnc), s);
2410 /* XXX Note that we could recalculate e to stop the loop earlier,
2411 * as the worst case expansion above will rarely be met, and as we
2412 * go along we would usually find that e moves further to the left.
2413 * This would happen only after we reached the point in the loop
2414 * where if there were no expansion we should fail. Unclear if
2415 * worth the expense */
2418 char *my_strend= (char *)strend;
2419 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2420 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2421 && (reginfo->intuit || regtry(reginfo, &s)) )
2425 s += (utf8_target) ? UTF8SKIP(s) : 1;
2431 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2432 if (FLAGS(c) != TRADITIONAL_BOUND) {
2433 if (! IN_UTF8_CTYPE_LOCALE) {
2434 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2435 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2440 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2444 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2445 if (FLAGS(c) != TRADITIONAL_BOUND) {
2446 if (! IN_UTF8_CTYPE_LOCALE) {
2447 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2448 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2453 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2456 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2458 assert(FLAGS(c) == TRADITIONAL_BOUND);
2460 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2463 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2465 assert(FLAGS(c) == TRADITIONAL_BOUND);
2467 FBC_BOUND_A(isWORDCHAR_A);
2470 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2472 assert(FLAGS(c) == TRADITIONAL_BOUND);
2474 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2477 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2479 assert(FLAGS(c) == TRADITIONAL_BOUND);
2481 FBC_NBOUND_A(isWORDCHAR_A);
2485 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2486 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2497 switch((bound_type) FLAGS(c)) {
2498 case TRADITIONAL_BOUND:
2499 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2502 if (s == reginfo->strbeg) {
2503 if (reginfo->intuit || regtry(reginfo, &s))
2508 /* Didn't match. Try at the next position (if there is one) */
2509 s += (utf8_target) ? UTF8SKIP(s) : 1;
2510 if (UNLIKELY(s >= reginfo->strend)) {
2516 GCB_enum before = getGCB_VAL_UTF8(
2518 (U8*)(reginfo->strbeg)),
2519 (U8*) reginfo->strend);
2520 while (s < strend) {
2521 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2522 (U8*) reginfo->strend);
2523 if ( (to_complement ^ isGCB(before,
2525 (U8*) reginfo->strbeg,
2528 && (reginfo->intuit || regtry(reginfo, &s)))
2536 else { /* Not utf8. Everything is a GCB except between CR and
2538 while (s < strend) {
2539 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2540 || UCHARAT(s) != '\n'))
2541 && (reginfo->intuit || regtry(reginfo, &s)))
2549 /* And, since this is a bound, it can match after the final
2550 * character in the string */
2551 if ((reginfo->intuit || regtry(reginfo, &s))) {
2557 if (s == reginfo->strbeg) {
2558 if (reginfo->intuit || regtry(reginfo, &s)) {
2561 s += (utf8_target) ? UTF8SKIP(s) : 1;
2562 if (UNLIKELY(s >= reginfo->strend)) {
2568 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2570 (U8*)(reginfo->strbeg)),
2571 (U8*) reginfo->strend);
2572 while (s < strend) {
2573 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2574 if (to_complement ^ isLB(before,
2576 (U8*) reginfo->strbeg,
2578 (U8*) reginfo->strend,
2580 && (reginfo->intuit || regtry(reginfo, &s)))
2588 else { /* Not utf8. */
2589 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2590 while (s < strend) {
2591 LB_enum after = getLB_VAL_CP((U8) *s);
2592 if (to_complement ^ isLB(before,
2594 (U8*) reginfo->strbeg,
2596 (U8*) reginfo->strend,
2598 && (reginfo->intuit || regtry(reginfo, &s)))
2607 if (reginfo->intuit || regtry(reginfo, &s)) {
2614 if (s == reginfo->strbeg) {
2615 if (reginfo->intuit || regtry(reginfo, &s)) {
2618 s += (utf8_target) ? UTF8SKIP(s) : 1;
2619 if (UNLIKELY(s >= reginfo->strend)) {
2625 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2627 (U8*)(reginfo->strbeg)),
2628 (U8*) reginfo->strend);
2629 while (s < strend) {
2630 SB_enum after = getSB_VAL_UTF8((U8*) s,
2631 (U8*) reginfo->strend);
2632 if ((to_complement ^ isSB(before,
2634 (U8*) reginfo->strbeg,
2636 (U8*) reginfo->strend,
2638 && (reginfo->intuit || regtry(reginfo, &s)))
2646 else { /* Not utf8. */
2647 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2648 while (s < strend) {
2649 SB_enum after = getSB_VAL_CP((U8) *s);
2650 if ((to_complement ^ isSB(before,
2652 (U8*) reginfo->strbeg,
2654 (U8*) reginfo->strend,
2656 && (reginfo->intuit || regtry(reginfo, &s)))
2665 /* Here are at the final position in the target string. The SB
2666 * value is always true here, so matches, depending on other
2668 if (reginfo->intuit || regtry(reginfo, &s)) {
2675 if (s == reginfo->strbeg) {
2676 if (reginfo->intuit || regtry(reginfo, &s)) {
2679 s += (utf8_target) ? UTF8SKIP(s) : 1;
2680 if (UNLIKELY(s >= reginfo->strend)) {
2686 /* We are at a boundary between char_sub_0 and char_sub_1.
2687 * We also keep track of the value for char_sub_-1 as we
2688 * loop through the line. Context may be needed to make a
2689 * determination, and if so, this can save having to
2691 WB_enum previous = WB_UNKNOWN;
2692 WB_enum before = getWB_VAL_UTF8(
2695 (U8*)(reginfo->strbeg)),
2696 (U8*) reginfo->strend);
2697 while (s < strend) {
2698 WB_enum after = getWB_VAL_UTF8((U8*) s,
2699 (U8*) reginfo->strend);
2700 if ((to_complement ^ isWB(previous,
2703 (U8*) reginfo->strbeg,
2705 (U8*) reginfo->strend,
2707 && (reginfo->intuit || regtry(reginfo, &s)))
2716 else { /* Not utf8. */
2717 WB_enum previous = WB_UNKNOWN;
2718 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2719 while (s < strend) {
2720 WB_enum after = getWB_VAL_CP((U8) *s);
2721 if ((to_complement ^ isWB(previous,
2724 (U8*) reginfo->strbeg,
2726 (U8*) reginfo->strend,
2728 && (reginfo->intuit || regtry(reginfo, &s)))
2738 if (reginfo->intuit || regtry(reginfo, &s)) {
2745 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2746 is_LNBREAK_latin1_safe(s, strend)
2751 REXEC_FBC_FIND_NEXT_SCAN(0, find_next_ascii(s, strend, utf8_target));
2756 REXEC_FBC_FIND_NEXT_SCAN(1, find_next_non_ascii(s, strend,
2760 REXEC_FBC_FIND_NEXT_SCAN(0, find_next_non_ascii(s, strend,
2766 /* The argument to all the POSIX node types is the class number to pass to
2767 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2774 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2775 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s, (U8 *) strend)),
2776 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2791 /* The complement of something that matches only ASCII matches all
2792 * non-ASCII, plus everything in ASCII that isn't in the class. */
2793 REXEC_FBC_CLASS_SCAN(1, ! isASCII_utf8_safe(s, strend)
2794 || ! _generic_isCC_A(*s, FLAGS(c)));
2802 /* Don't need to worry about utf8, as it can match only a single
2803 * byte invariant character. But we do anyway for performance reasons,
2804 * as otherwise we would have to examine all the continuation
2807 REXEC_FBC_CLASS_SCAN(1, _generic_isCC_A(*s, FLAGS(c)));
2812 REXEC_FBC_CLASS_SCAN(0, /* 0=>not-utf8 */
2813 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2821 if (! utf8_target) {
2822 REXEC_FBC_CLASS_SCAN(0, /* 0=>not-utf8 */
2823 to_complement ^ cBOOL(_generic_isCC(*s,
2829 classnum = (_char_class_number) FLAGS(c);
2832 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2833 to_complement ^ cBOOL(_invlist_contains_cp(
2834 PL_XPosix_ptrs[classnum],
2835 utf8_to_uvchr_buf((U8 *) s,
2839 case _CC_ENUM_SPACE:
2840 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2841 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2844 case _CC_ENUM_BLANK:
2845 REXEC_FBC_CLASS_SCAN(1,
2846 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2849 case _CC_ENUM_XDIGIT:
2850 REXEC_FBC_CLASS_SCAN(1,
2851 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2854 case _CC_ENUM_VERTSPACE:
2855 REXEC_FBC_CLASS_SCAN(1,
2856 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2859 case _CC_ENUM_CNTRL:
2860 REXEC_FBC_CLASS_SCAN(1,
2861 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2871 /* what trie are we using right now */
2872 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2873 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2874 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2876 const char *last_start = strend - trie->minlen;
2878 const char *real_start = s;
2880 STRLEN maxlen = trie->maxlen;
2882 U8 **points; /* map of where we were in the input string
2883 when reading a given char. For ASCII this
2884 is unnecessary overhead as the relationship
2885 is always 1:1, but for Unicode, especially
2886 case folded Unicode this is not true. */
2887 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2891 GET_RE_DEBUG_FLAGS_DECL;
2893 /* We can't just allocate points here. We need to wrap it in
2894 * an SV so it gets freed properly if there is a croak while
2895 * running the match */
2898 sv_points=newSV(maxlen * sizeof(U8 *));
2899 SvCUR_set(sv_points,
2900 maxlen * sizeof(U8 *));
2901 SvPOK_on(sv_points);
2902 sv_2mortal(sv_points);
2903 points=(U8**)SvPV_nolen(sv_points );
2904 if ( trie_type != trie_utf8_fold
2905 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2908 bitmap=(U8*)trie->bitmap;
2910 bitmap=(U8*)ANYOF_BITMAP(c);
2912 /* this is the Aho-Corasick algorithm modified a touch
2913 to include special handling for long "unknown char" sequences.
2914 The basic idea being that we use AC as long as we are dealing
2915 with a possible matching char, when we encounter an unknown char
2916 (and we have not encountered an accepting state) we scan forward
2917 until we find a legal starting char.
2918 AC matching is basically that of trie matching, except that when
2919 we encounter a failing transition, we fall back to the current
2920 states "fail state", and try the current char again, a process
2921 we repeat until we reach the root state, state 1, or a legal
2922 transition. If we fail on the root state then we can either
2923 terminate if we have reached an accepting state previously, or
2924 restart the entire process from the beginning if we have not.
2927 while (s <= last_start) {
2928 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2936 U8 *uscan = (U8*)NULL;
2937 U8 *leftmost = NULL;
2939 U32 accepted_word= 0;
2943 while ( state && uc <= (U8*)strend ) {
2945 U32 word = aho->states[ state ].wordnum;
2949 DEBUG_TRIE_EXECUTE_r(
2950 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2951 dump_exec_pos( (char *)uc, c, strend, real_start,
2952 (char *)uc, utf8_target, 0 );
2953 Perl_re_printf( aTHX_
2954 " Scanning for legal start char...\n");
2958 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2962 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2968 if (uc >(U8*)last_start) break;
2972 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2973 if (!leftmost || lpos < leftmost) {
2974 DEBUG_r(accepted_word=word);
2980 points[pointpos++ % maxlen]= uc;
2981 if (foldlen || uc < (U8*)strend) {
2982 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
2983 (U8 *) strend, uscan, len, uvc,
2984 charid, foldlen, foldbuf,
2986 DEBUG_TRIE_EXECUTE_r({
2987 dump_exec_pos( (char *)uc, c, strend,
2988 real_start, s, utf8_target, 0);
2989 Perl_re_printf( aTHX_
2990 " Charid:%3u CP:%4" UVxf " ",
3002 word = aho->states[ state ].wordnum;
3004 base = aho->states[ state ].trans.base;
3006 DEBUG_TRIE_EXECUTE_r({
3008 dump_exec_pos( (char *)uc, c, strend, real_start,
3009 s, utf8_target, 0 );
3010 Perl_re_printf( aTHX_
3011 "%sState: %4" UVxf ", word=%" UVxf,
3012 failed ? " Fail transition to " : "",
3013 (UV)state, (UV)word);
3019 ( ((offset = base + charid
3020 - 1 - trie->uniquecharcount)) >= 0)
3021 && ((U32)offset < trie->lasttrans)
3022 && trie->trans[offset].check == state
3023 && (tmp=trie->trans[offset].next))
3025 DEBUG_TRIE_EXECUTE_r(
3026 Perl_re_printf( aTHX_ " - legal\n"));
3031 DEBUG_TRIE_EXECUTE_r(
3032 Perl_re_printf( aTHX_ " - fail\n"));
3034 state = aho->fail[state];
3038 /* we must be accepting here */
3039 DEBUG_TRIE_EXECUTE_r(
3040 Perl_re_printf( aTHX_ " - accepting\n"));
3049 if (!state) state = 1;
3052 if ( aho->states[ state ].wordnum ) {
3053 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
3054 if (!leftmost || lpos < leftmost) {
3055 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
3060 s = (char*)leftmost;
3061 DEBUG_TRIE_EXECUTE_r({
3062 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
3063 (UV)accepted_word, (IV)(s - real_start)
3066 if (reginfo->intuit || regtry(reginfo, &s)) {
3072 DEBUG_TRIE_EXECUTE_r({
3073 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
3076 DEBUG_TRIE_EXECUTE_r(
3077 Perl_re_printf( aTHX_ "No match.\n"));
3086 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
3093 /* set RX_SAVED_COPY, RX_SUBBEG etc.
3094 * flags have same meanings as with regexec_flags() */
3097 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
3104 struct regexp *const prog = ReANY(rx);
3106 if (flags & REXEC_COPY_STR) {
3109 DEBUG_C(Perl_re_printf( aTHX_
3110 "Copy on write: regexp capture, type %d\n",
3112 /* Create a new COW SV to share the match string and store
3113 * in saved_copy, unless the current COW SV in saved_copy
3114 * is valid and suitable for our purpose */
3115 if (( prog->saved_copy
3116 && SvIsCOW(prog->saved_copy)
3117 && SvPOKp(prog->saved_copy)
3120 && SvPVX(sv) == SvPVX(prog->saved_copy)))
3122 /* just reuse saved_copy SV */
3123 if (RXp_MATCH_COPIED(prog)) {
3124 Safefree(prog->subbeg);
3125 RXp_MATCH_COPIED_off(prog);
3129 /* create new COW SV to share string */
3130 RXp_MATCH_COPY_FREE(prog);
3131 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
3133 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
3134 assert (SvPOKp(prog->saved_copy));
3135 prog->sublen = strend - strbeg;
3136 prog->suboffset = 0;
3137 prog->subcoffset = 0;
3142 SSize_t max = strend - strbeg;
3145 if ( (flags & REXEC_COPY_SKIP_POST)
3146 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3147 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
3148 ) { /* don't copy $' part of string */
3151 /* calculate the right-most part of the string covered
3152 * by a capture. Due to lookahead, this may be to
3153 * the right of $&, so we have to scan all captures */
3154 while (n <= prog->lastparen) {
3155 if (prog->offs[n].end > max)
3156 max = prog->offs[n].end;
3160 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
3161 ? prog->offs[0].start
3163 assert(max >= 0 && max <= strend - strbeg);
3166 if ( (flags & REXEC_COPY_SKIP_PRE)
3167 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3168 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
3169 ) { /* don't copy $` part of string */
3172 /* calculate the left-most part of the string covered
3173 * by a capture. Due to lookbehind, this may be to
3174 * the left of $&, so we have to scan all captures */
3175 while (min && n <= prog->lastparen) {
3176 if ( prog->offs[n].start != -1
3177 && prog->offs[n].start < min)
3179 min = prog->offs[n].start;
3183 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
3184 && min > prog->offs[0].end
3186 min = prog->offs[0].end;
3190 assert(min >= 0 && min <= max && min <= strend - strbeg);
3193 if (RXp_MATCH_COPIED(prog)) {
3194 if (sublen > prog->sublen)
3196 (char*)saferealloc(prog->subbeg, sublen+1);
3199 prog->subbeg = (char*)safemalloc(sublen+1);
3200 Copy(strbeg + min, prog->subbeg, sublen, char);
3201 prog->subbeg[sublen] = '\0';
3202 prog->suboffset = min;
3203 prog->sublen = sublen;
3204 RXp_MATCH_COPIED_on(prog);
3206 prog->subcoffset = prog->suboffset;
3207 if (prog->suboffset && utf8_target) {
3208 /* Convert byte offset to chars.
3209 * XXX ideally should only compute this if @-/@+
3210 * has been seen, a la PL_sawampersand ??? */
3212 /* If there's a direct correspondence between the
3213 * string which we're matching and the original SV,
3214 * then we can use the utf8 len cache associated with
3215 * the SV. In particular, it means that under //g,
3216 * sv_pos_b2u() will use the previously cached
3217 * position to speed up working out the new length of
3218 * subcoffset, rather than counting from the start of
3219 * the string each time. This stops
3220 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
3221 * from going quadratic */
3222 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
3223 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
3224 SV_GMAGIC|SV_CONST_RETURN);
3226 prog->subcoffset = utf8_length((U8*)strbeg,
3227 (U8*)(strbeg+prog->suboffset));
3231 RXp_MATCH_COPY_FREE(prog);
3232 prog->subbeg = strbeg;
3233 prog->suboffset = 0;
3234 prog->subcoffset = 0;
3235 prog->sublen = strend - strbeg;
3243 - regexec_flags - match a regexp against a string
3246 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
3247 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
3248 /* stringarg: the point in the string at which to begin matching */
3249 /* strend: pointer to null at end of string */
3250 /* strbeg: real beginning of string */
3251 /* minend: end of match must be >= minend bytes after stringarg. */
3252 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
3253 * itself is accessed via the pointers above */
3254 /* data: May be used for some additional optimizations.
3255 Currently unused. */
3256 /* flags: For optimizations. See REXEC_* in regexp.h */
3259 struct regexp *const prog = ReANY(rx);
3263 SSize_t minlen; /* must match at least this many chars */
3264 SSize_t dontbother = 0; /* how many characters not to try at end */
3265 const bool utf8_target = cBOOL(DO_UTF8(sv));
3267 RXi_GET_DECL(prog,progi);
3268 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
3269 regmatch_info *const reginfo = ®info_buf;
3270 regexp_paren_pair *swap = NULL;
3272 GET_RE_DEBUG_FLAGS_DECL;
3274 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
3275 PERL_UNUSED_ARG(data);
3277 /* Be paranoid... */
3279 Perl_croak(aTHX_ "NULL regexp parameter");
3283 debug_start_match(rx, utf8_target, stringarg, strend,
3287 startpos = stringarg;
3289 /* set these early as they may be used by the HOP macros below */
3290 reginfo->strbeg = strbeg;
3291 reginfo->strend = strend;
3292 reginfo->is_utf8_target = cBOOL(utf8_target);
3294 if (prog->intflags & PREGf_GPOS_SEEN) {
3297 /* set reginfo->ganch, the position where \G can match */
3300 (flags & REXEC_IGNOREPOS)
3301 ? stringarg /* use start pos rather than pos() */
3302 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
3303 /* Defined pos(): */
3304 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
3305 : strbeg; /* pos() not defined; use start of string */
3307 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3308 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
3310 /* in the presence of \G, we may need to start looking earlier in
3311 * the string than the suggested start point of stringarg:
3312 * if prog->gofs is set, then that's a known, fixed minimum
3315 * /ab|c\G/: gofs = 1
3316 * or if the minimum offset isn't known, then we have to go back
3317 * to the start of the string, e.g. /w+\G/
3320 if (prog->intflags & PREGf_ANCH_GPOS) {
3322 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
3324 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
3326 DEBUG_r(Perl_re_printf( aTHX_
3327 "fail: ganch-gofs before earliest possible start\n"));
3332 startpos = reginfo->ganch;
3334 else if (prog->gofs) {
3335 startpos = HOPBACKc(startpos, prog->gofs);
3339 else if (prog->intflags & PREGf_GPOS_FLOAT)
3343 minlen = prog->minlen;
3344 if ((startpos + minlen) > strend || startpos < strbeg) {
3345 DEBUG_r(Perl_re_printf( aTHX_
3346 "Regex match can't succeed, so not even tried\n"));
3350 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3351 * which will call destuctors to reset PL_regmatch_state, free higher
3352 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3353 * regmatch_info_aux_eval */
3355 oldsave = PL_savestack_ix;
3359 if ((prog->extflags & RXf_USE_INTUIT)
3360 && !(flags & REXEC_CHECKED))
3362 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3367 if (prog->extflags & RXf_CHECK_ALL) {
3368 /* we can match based purely on the result of INTUIT.
3369 * Set up captures etc just for $& and $-[0]
3370 * (an intuit-only match wont have $1,$2,..) */
3371 assert(!prog->nparens);
3373 /* s/// doesn't like it if $& is earlier than where we asked it to
3374 * start searching (which can happen on something like /.\G/) */
3375 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3378 /* this should only be possible under \G */
3379 assert(prog->intflags & PREGf_GPOS_SEEN);
3380 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3381 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3385 /* match via INTUIT shouldn't have any captures.
3386 * Let @-, @+, $^N know */
3387 prog->lastparen = prog->lastcloseparen = 0;
3388 RXp_MATCH_UTF8_set(prog, utf8_target);
3389 prog->offs[0].start = s - strbeg;
3390 prog->offs[0].end = utf8_target
3391 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3392 : s - strbeg + prog->minlenret;
3393 if ( !(flags & REXEC_NOT_FIRST) )
3394 S_reg_set_capture_string(aTHX_ rx,
3396 sv, flags, utf8_target);
3402 multiline = prog->extflags & RXf_PMf_MULTILINE;
3404 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3405 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3406 "String too short [regexec_flags]...\n"));
3410 /* Check validity of program. */
3411 if (UCHARAT(progi->program) != REG_MAGIC) {
3412 Perl_croak(aTHX_ "corrupted regexp program");
3415 RXp_MATCH_TAINTED_off(prog);
3416 RXp_MATCH_UTF8_set(prog, utf8_target);
3418 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3419 reginfo->intuit = 0;
3420 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3421 reginfo->warned = FALSE;
3423 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3424 /* see how far we have to get to not match where we matched before */
3425 reginfo->till = stringarg + minend;
3427 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3428 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3429 S_cleanup_regmatch_info_aux has executed (registered by
3430 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3431 magic belonging to this SV.
3432 Not newSVsv, either, as it does not COW.
3434 reginfo->sv = newSV(0);
3435 SvSetSV_nosteal(reginfo->sv, sv);
3436 SAVEFREESV(reginfo->sv);
3439 /* reserve next 2 or 3 slots in PL_regmatch_state:
3440 * slot N+0: may currently be in use: skip it
3441 * slot N+1: use for regmatch_info_aux struct
3442 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3443 * slot N+3: ready for use by regmatch()
3447 regmatch_state *old_regmatch_state;
3448 regmatch_slab *old_regmatch_slab;
3449 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3451 /* on first ever match, allocate first slab */
3452 if (!PL_regmatch_slab) {
3453 Newx(PL_regmatch_slab, 1, regmatch_slab);
3454 PL_regmatch_slab->prev = NULL;
3455 PL_regmatch_slab->next = NULL;
3456 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3459 old_regmatch_state = PL_regmatch_state;
3460 old_regmatch_slab = PL_regmatch_slab;
3462 for (i=0; i <= max; i++) {
3464 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3466 reginfo->info_aux_eval =
3467 reginfo->info_aux->info_aux_eval =
3468 &(PL_regmatch_state->u.info_aux_eval);
3470 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3471 PL_regmatch_state = S_push_slab(aTHX);
3474 /* note initial PL_regmatch_state position; at end of match we'll
3475 * pop back to there and free any higher slabs */
3477 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3478 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3479 reginfo->info_aux->poscache = NULL;
3481 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3483 if ((prog->extflags & RXf_EVAL_SEEN))
3484 S_setup_eval_state(aTHX_ reginfo);
3486 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3489 /* If there is a "must appear" string, look for it. */
3491 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3492 /* We have to be careful. If the previous successful match
3493 was from this regex we don't want a subsequent partially
3494 successful match to clobber the old results.
3495 So when we detect this possibility we add a swap buffer
3496 to the re, and switch the buffer each match. If we fail,
3497 we switch it back; otherwise we leave it swapped.
3500 /* do we need a save destructor here for eval dies? */
3501 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3502 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3503 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3511 if (prog->recurse_locinput)
3512 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3514 /* Simplest case: anchored match need be tried only once, or with
3515 * MBOL, only at the beginning of each line.
3517 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3518 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3519 * match at the start of the string then it won't match anywhere else
3520 * either; while with /.*.../, if it doesn't match at the beginning,
3521 * the earliest it could match is at the start of the next line */
3523 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3526 if (regtry(reginfo, &s))
3529 if (!(prog->intflags & PREGf_ANCH_MBOL))
3532 /* didn't match at start, try at other newline positions */
3535 dontbother = minlen - 1;
3536 end = HOP3c(strend, -dontbother, strbeg) - 1;
3538 /* skip to next newline */
3540 while (s <= end) { /* note it could be possible to match at the end of the string */
3541 /* NB: newlines are the same in unicode as they are in latin */
3544 if (prog->check_substr || prog->check_utf8) {
3545 /* note that with PREGf_IMPLICIT, intuit can only fail
3546 * or return the start position, so it's of limited utility.
3547 * Nevertheless, I made the decision that the potential for
3548 * quick fail was still worth it - DAPM */
3549 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3553 if (regtry(reginfo, &s))
3557 } /* end anchored search */
3559 if (prog->intflags & PREGf_ANCH_GPOS)
3561 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3562 assert(prog->intflags & PREGf_GPOS_SEEN);
3563 /* For anchored \G, the only position it can match from is
3564 * (ganch-gofs); we already set startpos to this above; if intuit
3565 * moved us on from there, we can't possibly succeed */
3566 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3567 if (s == startpos && regtry(reginfo, &s))
3572 /* Messy cases: unanchored match. */
3573 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3574 /* we have /x+whatever/ */
3575 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3581 if (! prog->anchored_utf8) {
3582 to_utf8_substr(prog);
3584 ch = SvPVX_const(prog->anchored_utf8)[0];
3585 REXEC_FBC_SCAN(0, /* 0=>not-utf8 */
3587 DEBUG_EXECUTE_r( did_match = 1 );
3588 if (regtry(reginfo, &s)) goto got_it;
3590 while (s < strend && *s == ch)
3597 if (! prog->anchored_substr) {
3598 if (! to_byte_substr(prog)) {
3599 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3602 ch = SvPVX_const(prog->anchored_substr)[0];
3603 REXEC_FBC_SCAN(0, /* 0=>not-utf8 */
3605 DEBUG_EXECUTE_r( did_match = 1 );
3606 if (regtry(reginfo, &s)) goto got_it;
3608 while (s < strend && *s == ch)
3613 DEBUG_EXECUTE_r(if (!did_match)
3614 Perl_re_printf( aTHX_
3615 "Did not find anchored character...\n")
3618 else if (prog->anchored_substr != NULL
3619 || prog->anchored_utf8 != NULL
3620 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3621 && prog->float_max_offset < strend - s)) {
3626 char *last1; /* Last position checked before */
3630 if (prog->anchored_substr || prog->anchored_utf8) {
3632 if (! prog->anchored_utf8) {
3633 to_utf8_substr(prog);
3635 must = prog->anchored_utf8;
3638 if (! prog->anchored_substr) {
3639 if (! to_byte_substr(prog)) {
3640 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3643 must = prog->anchored_substr;
3645 back_max = back_min = prog->anchored_offset;
3648 if (! prog->float_utf8) {
3649 to_utf8_substr(prog);
3651 must = prog->float_utf8;
3654 if (! prog->float_substr) {
3655 if (! to_byte_substr(prog)) {
3656 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3659 must = prog->float_substr;
3661 back_max = prog->float_max_offset;
3662 back_min = prog->float_min_offset;
3668 last = HOP3c(strend, /* Cannot start after this */
3669 -(SSize_t)(CHR_SVLEN(must)
3670 - (SvTAIL(must) != 0) + back_min), strbeg);
3672 if (s > reginfo->strbeg)
3673 last1 = HOPc(s, -1);
3675 last1 = s - 1; /* bogus */
3677 /* XXXX check_substr already used to find "s", can optimize if
3678 check_substr==must. */
3680 strend = HOPc(strend, -dontbother);
3681 while ( (s <= last) &&
3682 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3683 (unsigned char*)strend, must,
3684 multiline ? FBMrf_MULTILINE : 0)) ) {
3685 DEBUG_EXECUTE_r( did_match = 1 );
3686 if (HOPc(s, -back_max) > last1) {
3687 last1 = HOPc(s, -back_min);
3688 s = HOPc(s, -back_max);
3691 char * const t = (last1 >= reginfo->strbeg)
3692 ? HOPc(last1, 1) : last1 + 1;
3694 last1 = HOPc(s, -back_min);
3698 while (s <= last1) {
3699 if (regtry(reginfo, &s))
3702 s++; /* to break out of outer loop */
3709 while (s <= last1) {
3710 if (regtry(reginfo, &s))
3716 DEBUG_EXECUTE_r(if (!did_match) {
3717 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3718 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3719 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3720 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3721 ? "anchored" : "floating"),
3722 quoted, RE_SV_TAIL(must));
3726 else if ( (c = progi->regstclass) ) {
3728 const OPCODE op = OP(progi->regstclass);
3729 /* don't bother with what can't match */
3730 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3731 strend = HOPc(strend, -(minlen - 1));
3734 SV * const prop = sv_newmortal();
3735 regprop(prog, prop, c, reginfo, NULL);
3737 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3738 s,strend-s,PL_dump_re_max_len);
3739 Perl_re_printf( aTHX_
3740 "Matching stclass %.*s against %s (%d bytes)\n",
3741 (int)SvCUR(prop), SvPVX_const(prop),
3742 quoted, (int)(strend - s));
3745 if (find_byclass(prog, c, s, strend, reginfo))
3747 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3751 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3759 if (! prog->float_utf8) {
3760 to_utf8_substr(prog);
3762 float_real = prog->float_utf8;
3765 if (! prog->float_substr) {
3766 if (! to_byte_substr(prog)) {
3767 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3770 float_real = prog->float_substr;
3773 little = SvPV_const(float_real, len);
3774 if (SvTAIL(float_real)) {
3775 /* This means that float_real contains an artificial \n on
3776 * the end due to the presence of something like this:
3777 * /foo$/ where we can match both "foo" and "foo\n" at the
3778 * end of the string. So we have to compare the end of the
3779 * string first against the float_real without the \n and
3780 * then against the full float_real with the string. We
3781 * have to watch out for cases where the string might be
3782 * smaller than the float_real or the float_real without
3784 char *checkpos= strend - len;
3786 Perl_re_printf( aTHX_
3787 "%sChecking for float_real.%s\n",
3788 PL_colors[4], PL_colors[5]));
3789 if (checkpos + 1 < strbeg) {
3790 /* can't match, even if we remove the trailing \n
3791 * string is too short to match */
3793 Perl_re_printf( aTHX_
3794 "%sString shorter than required trailing substring, cannot match.%s\n",
3795 PL_colors[4], PL_colors[5]));
3797 } else if (memEQ(checkpos + 1, little, len - 1)) {
3798 /* can match, the end of the string matches without the
3800 last = checkpos + 1;
3801 } else if (checkpos < strbeg) {
3802 /* cant match, string is too short when the "\n" is
3805 Perl_re_printf( aTHX_
3806 "%sString does not contain required trailing substring, cannot match.%s\n",
3807 PL_colors[4], PL_colors[5]));
3809 } else if (!multiline) {
3810 /* non multiline match, so compare with the "\n" at the
3811 * end of the string */
3812 if (memEQ(checkpos, little, len)) {
3816 Perl_re_printf( aTHX_
3817 "%sString does not contain required trailing substring, cannot match.%s\n",
3818 PL_colors[4], PL_colors[5]));
3822 /* multiline match, so we have to search for a place
3823 * where the full string is located */
3829 last = rninstr(s, strend, little, little + len);
3831 last = strend; /* matching "$" */
3834 /* at one point this block contained a comment which was
3835 * probably incorrect, which said that this was a "should not
3836 * happen" case. Even if it was true when it was written I am
3837 * pretty sure it is not anymore, so I have removed the comment
3838 * and replaced it with this one. Yves */
3840 Perl_re_printf( aTHX_
3841 "%sString does not contain required substring, cannot match.%s\n",
3842 PL_colors[4], PL_colors[5]
3846 dontbother = strend - last + prog->float_min_offset;
3848 if (minlen && (dontbother < minlen))
3849 dontbother = minlen - 1;
3850 strend -= dontbother; /* this one's always in bytes! */
3851 /* We don't know much -- general case. */
3854 if (regtry(reginfo, &s))
3863 if (regtry(reginfo, &s))
3865 } while (s++ < strend);
3873 /* s/// doesn't like it if $& is earlier than where we asked it to
3874 * start searching (which can happen on something like /.\G/) */
3875 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3876 && (prog->offs[0].start < stringarg - strbeg))
3878 /* this should only be possible under \G */
3879 assert(prog->intflags & PREGf_GPOS_SEEN);
3880 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3881 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3887 Perl_re_exec_indentf( aTHX_
3888 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3896 /* clean up; this will trigger destructors that will free all slabs
3897 * above the current one, and cleanup the regmatch_info_aux
3898 * and regmatch_info_aux_eval sructs */
3900 LEAVE_SCOPE(oldsave);
3902 if (RXp_PAREN_NAMES(prog))
3903 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3905 /* make sure $`, $&, $', and $digit will work later */
3906 if ( !(flags & REXEC_NOT_FIRST) )
3907 S_reg_set_capture_string(aTHX_ rx,
3908 strbeg, reginfo->strend,
3909 sv, flags, utf8_target);
3914 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3915 PL_colors[4], PL_colors[5]));
3917 /* clean up; this will trigger destructors that will free all slabs
3918 * above the current one, and cleanup the regmatch_info_aux
3919 * and regmatch_info_aux_eval sructs */
3921 LEAVE_SCOPE(oldsave);
3924 /* we failed :-( roll it back */
3925 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3926 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3932 Safefree(prog->offs);
3939 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3940 * Do inc before dec, in case old and new rex are the same */
3941 #define SET_reg_curpm(Re2) \
3942 if (reginfo->info_aux_eval) { \
3943 (void)ReREFCNT_inc(Re2); \
3944 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3945 PM_SETRE((PL_reg_curpm), (Re2)); \
3950 - regtry - try match at specific point
3952 STATIC bool /* 0 failure, 1 success */
3953 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3956 REGEXP *const rx = reginfo->prog;
3957 regexp *const prog = ReANY(rx);
3960 U32 depth = 0; /* used by REGCP_SET */
3962 RXi_GET_DECL(prog,progi);
3963 GET_RE_DEBUG_FLAGS_DECL;
3965 PERL_ARGS_ASSERT_REGTRY;
3967 reginfo->cutpoint=NULL;
3969 prog->offs[0].start = *startposp - reginfo->strbeg;
3970 prog->lastparen = 0;
3971 prog->lastcloseparen = 0;
3973 /* XXXX What this code is doing here?!!! There should be no need
3974 to do this again and again, prog->lastparen should take care of
3977 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3978 * Actually, the code in regcppop() (which Ilya may be meaning by
3979 * prog->lastparen), is not needed at all by the test suite
3980 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3981 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3982 * Meanwhile, this code *is* needed for the
3983 * above-mentioned test suite tests to succeed. The common theme
3984 * on those tests seems to be returning null fields from matches.
3985 * --jhi updated by dapm */
3987 /* After encountering a variant of the issue mentioned above I think
3988 * the point Ilya was making is that if we properly unwind whenever
3989 * we set lastparen to a smaller value then we should not need to do
3990 * this every time, only when needed. So if we have tests that fail if
3991 * we remove this, then it suggests somewhere else we are improperly
3992 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3993 * places it is called, and related regcp() routines. - Yves */
3995 if (prog->nparens) {
3996 regexp_paren_pair *pp = prog->offs;
3998 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
4006 result = regmatch(reginfo, *startposp, progi->program + 1);
4008 prog->offs[0].end = result;
4011 if (reginfo->cutpoint)
4012 *startposp= reginfo->cutpoint;
4013 REGCP_UNWIND(lastcp);
4018 #define sayYES goto yes
4019 #define sayNO goto no
4020 #define sayNO_SILENT goto no_silent
4022 /* we dont use STMT_START/END here because it leads to
4023 "unreachable code" warnings, which are bogus, but distracting. */
4024 #define CACHEsayNO \
4025 if (ST.cache_mask) \
4026 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
4029 /* this is used to determine how far from the left messages like
4030 'failed...' are printed in regexec.c. It should be set such that
4031 messages are inline with the regop output that created them.
4033 #define REPORT_CODE_OFF 29
4034 #define INDENT_CHARS(depth) ((int)(depth) % 20)
4037 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
4041 PerlIO *f= Perl_debug_log;
4042 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
4043 va_start(ap, depth);
4044 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
4045 result = PerlIO_vprintf(f, fmt, ap);
4049 #endif /* DEBUGGING */
4052 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
4053 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
4054 #define CHRTEST_NOT_A_CP_1 -999
4055 #define CHRTEST_NOT_A_CP_2 -998
4057 /* grab a new slab and return the first slot in it */
4059 STATIC regmatch_state *
4062 regmatch_slab *s = PL_regmatch_slab->next;
4064 Newx(s, 1, regmatch_slab);
4065 s->prev = PL_regmatch_slab;
4067 PL_regmatch_slab->next = s;
4069 PL_regmatch_slab = s;
4070 return SLAB_FIRST(s);
4074 /* push a new state then goto it */
4076 #define PUSH_STATE_GOTO(state, node, input) \
4077 pushinput = input; \
4079 st->resume_state = state; \
4082 /* push a new state with success backtracking, then goto it */
4084 #define PUSH_YES_STATE_GOTO(state, node, input) \
4085 pushinput = input; \
4087 st->resume_state = state; \
4088 goto push_yes_state;
4095 regmatch() - main matching routine
4097 This is basically one big switch statement in a loop. We execute an op,
4098 set 'next' to point the next op, and continue. If we come to a point which
4099 we may need to backtrack to on failure such as (A|B|C), we push a
4100 backtrack state onto the backtrack stack. On failure, we pop the top
4101 state, and re-enter the loop at the state indicated. If there are no more
4102 states to pop, we return failure.
4104 Sometimes we also need to backtrack on success; for example /A+/, where
4105 after successfully matching one A, we need to go back and try to
4106 match another one; similarly for lookahead assertions: if the assertion
4107 completes successfully, we backtrack to the state just before the assertion
4108 and then carry on. In these cases, the pushed state is marked as
4109 'backtrack on success too'. This marking is in fact done by a chain of
4110 pointers, each pointing to the previous 'yes' state. On success, we pop to
4111 the nearest yes state, discarding any intermediate failure-only states.
4112 Sometimes a yes state is pushed just to force some cleanup code to be
4113 called at the end of a successful match or submatch; e.g. (??{$re}) uses
4114 it to free the inner regex.
4116 Note that failure backtracking rewinds the cursor position, while
4117 success backtracking leaves it alone.
4119 A pattern is complete when the END op is executed, while a subpattern
4120 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
4121 ops trigger the "pop to last yes state if any, otherwise return true"
4124 A common convention in this function is to use A and B to refer to the two
4125 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
4126 the subpattern to be matched possibly multiple times, while B is the entire
4127 rest of the pattern. Variable and state names reflect this convention.
4129 The states in the main switch are the union of ops and failure/success of
4130 substates associated with with that op. For example, IFMATCH is the op
4131 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
4132 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
4133 successfully matched A and IFMATCH_A_fail is a state saying that we have
4134 just failed to match A. Resume states always come in pairs. The backtrack
4135 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
4136 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
4137 on success or failure.
4139 The struct that holds a backtracking state is actually a big union, with
4140 one variant for each major type of op. The variable st points to the
4141 top-most backtrack struct. To make the code clearer, within each
4142 block of code we #define ST to alias the relevant union.
4144 Here's a concrete example of a (vastly oversimplified) IFMATCH
4150 #define ST st->u.ifmatch
4152 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
4153 ST.foo = ...; // some state we wish to save
4155 // push a yes backtrack state with a resume value of
4156 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
4158 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
4161 case IFMATCH_A: // we have successfully executed A; now continue with B
4163 bar = ST.foo; // do something with the preserved value
4166 case IFMATCH_A_fail: // A failed, so the assertion failed
4167 ...; // do some housekeeping, then ...
4168 sayNO; // propagate the failure
4175 For any old-timers reading this who are familiar with the old recursive
4176 approach, the code above is equivalent to:
4178 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
4187 ...; // do some housekeeping, then ...
4188 sayNO; // propagate the failure
4191 The topmost backtrack state, pointed to by st, is usually free. If you
4192 want to claim it, populate any ST.foo fields in it with values you wish to
4193 save, then do one of
4195 PUSH_STATE_GOTO(resume_state, node, newinput);
4196 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
4198 which sets that backtrack state's resume value to 'resume_state', pushes a
4199 new free entry to the top of the backtrack stack, then goes to 'node'.
4200 On backtracking, the free slot is popped, and the saved state becomes the
4201 new free state. An ST.foo field in this new top state can be temporarily
4202 accessed to retrieve values, but once the main loop is re-entered, it
4203 becomes available for reuse.
4205 Note that the depth of the backtrack stack constantly increases during the
4206 left-to-right execution of the pattern, rather than going up and down with
4207 the pattern nesting. For example the stack is at its maximum at Z at the
4208 end of the pattern, rather than at X in the following:
4210 /(((X)+)+)+....(Y)+....Z/
4212 The only exceptions to this are lookahead/behind assertions and the cut,
4213 (?>A), which pop all the backtrack states associated with A before
4216 Backtrack state structs are allocated in slabs of about 4K in size.
4217 PL_regmatch_state and st always point to the currently active state,
4218 and PL_regmatch_slab points to the slab currently containing
4219 PL_regmatch_state. The first time regmatch() is called, the first slab is
4220 allocated, and is never freed until interpreter destruction. When the slab
4221 is full, a new one is allocated and chained to the end. At exit from
4222 regmatch(), slabs allocated since entry are freed.
4227 #define DEBUG_STATE_pp(pp) \
4229 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
4230 Perl_re_printf( aTHX_ \
4231 "%*s" pp " %s%s%s%s%s\n", \
4232 INDENT_CHARS(depth), "", \
4233 PL_reg_name[st->resume_state], \
4234 ((st==yes_state||st==mark_state) ? "[" : ""), \
4235 ((st==yes_state) ? "Y" : ""), \
4236 ((st==mark_state) ? "M" : ""), \
4237 ((st==yes_state||st==mark_state) ? "]" : "") \
4242 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
4247 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
4248 const char *start, const char *end, const char *blurb)
4250 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
4252 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
4257 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
4258 RX_PRECOMP_const(prog), RX_PRELEN(prog), PL_dump_re_max_len);
4260 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
4261 start, end - start, PL_dump_re_max_len);
4263 Perl_re_printf( aTHX_
4264 "%s%s REx%s %s against %s\n",
4265 PL_colors[4], blurb, PL_colors[5], s0, s1);
4267 if (utf8_target||utf8_pat)
4268 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
4269 utf8_pat ? "pattern" : "",
4270 utf8_pat && utf8_target ? " and " : "",
4271 utf8_target ? "string" : ""
4277 S_dump_exec_pos(pTHX_ const char *locinput,
4278 const regnode *scan,
4279 const char *loc_regeol,
4280 const char *loc_bostr,
4281 const char *loc_reg_starttry,
4282 const bool utf8_target,
4286 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
4287 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
4288 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
4289 /* The part of the string before starttry has one color
4290 (pref0_len chars), between starttry and current
4291 position another one (pref_len - pref0_len chars),
4292 after the current position the third one.
4293 We assume that pref0_len <= pref_len, otherwise we
4294 decrease pref0_len. */
4295 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
4296 ? (5 + taill) - l : locinput - loc_bostr;
4299 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
4301 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
4303 pref0_len = pref_len - (locinput - loc_reg_starttry);
4304 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
4305 l = ( loc_regeol - locinput > (5 + taill) - pref_len
4306 ? (5 + taill) - pref_len : loc_regeol - locinput);
4307 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
4311 if (pref0_len > pref_len)
4312 pref0_len = pref_len;
4314 const int is_uni = utf8_target ? 1 : 0;
4316 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
4317 (locinput - pref_len),pref0_len, PL_dump_re_max_len, 4, 5);
4319 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
4320 (locinput - pref_len + pref0_len),
4321 pref_len - pref0_len, PL_dump_re_max_len, 2, 3);
4323 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
4324 locinput, loc_regeol - locinput, 10, 0, 1);
4326 const STRLEN tlen=len0+len1+len2;
4327 Perl_re_printf( aTHX_
4328 "%4" IVdf " <%.*s%.*s%s%.*s>%*s|%4u| ",
4329 (IV)(locinput - loc_bostr),
4332 (docolor ? "" : "> <"),
4334 (int)(tlen > 19 ? 0 : 19 - tlen),
4342 /* reg_check_named_buff_matched()
4343 * Checks to see if a named buffer has matched. The data array of
4344 * buffer numbers corresponding to the buffer is expected to reside
4345 * in the regexp->data->data array in the slot stored in the ARG() of
4346 * node involved. Note that this routine doesn't actually care about the
4347 * name, that information is not preserved from compilation to execution.
4348 * Returns the index of the leftmost defined buffer with the given name
4349 * or 0 if non of the buffers matched.
4352 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
4355 RXi_GET_DECL(rex,rexi);
4356 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4357 I32 *nums=(I32*)SvPVX(sv_dat);
4359 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
4361 for ( n=0; n<SvIVX(sv_dat); n++ ) {
4362 if ((I32)rex->lastparen >= nums[n] &&
4363 rex->offs[nums[n]].end != -1)
4373 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
4374 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
4376 /* This function determines if there are one or two characters that match
4377 * the first character of the passed-in EXACTish node <text_node>, and if
4378 * so, returns them in the passed-in pointers.
4380 * If it determines that no possible character in the target string can
4381 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4382 * the first character in <text_node> requires UTF-8 to represent, and the
4383 * target string isn't in UTF-8.)
4385 * If there are more than two characters that could match the beginning of
4386 * <text_node>, or if more context is required to determine a match or not,
4387 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4389 * The motiviation behind this function is to allow the caller to set up
4390 * tight loops for matching. If <text_node> is of type EXACT, there is
4391 * only one possible character that can match its first character, and so
4392 * the situation is quite simple. But things get much more complicated if
4393 * folding is involved. It may be that the first character of an EXACTFish
4394 * node doesn't participate in any possible fold, e.g., punctuation, so it
4395 * can be matched only by itself. The vast majority of characters that are
4396 * in folds match just two things, their lower and upper-case equivalents.
4397 * But not all are like that; some have multiple possible matches, or match
4398 * sequences of more than one character. This function sorts all that out.
4400 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4401 * loop of trying to match A*, we know we can't exit where the thing
4402 * following it isn't a B. And something can't be a B unless it is the
4403 * beginning of B. By putting a quick test for that beginning in a tight
4404 * loop, we can rule out things that can't possibly be B without having to
4405 * break out of the loop, thus avoiding work. Similarly, if A is a single
4406 * character, we can make a tight loop matching A*, using the outputs of
4409 * If the target string to match isn't in UTF-8, and there aren't
4410 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4411 * the one or two possible octets (which are characters in this situation)
4412 * that can match. In all cases, if there is only one character that can
4413 * match, *<c1p> and *<c2p> will be identical.
4415 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4416 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4417 * can match the beginning of <text_node>. They should be declared with at
4418 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4419 * undefined what these contain.) If one or both of the buffers are
4420 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4421 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4422 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4423 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4424 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4426 const bool utf8_target = reginfo->is_utf8_target;
4428 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4429 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4430 bool use_chrtest_void = FALSE;
4431 const bool is_utf8_pat = reginfo->is_utf8_pat;
4433 /* Used when we have both utf8 input and utf8 output, to avoid converting
4434 * to/from code points */
4435 bool utf8_has_been_setup = FALSE;
4439 U8 *pat = (U8*)STRING(text_node);
4440 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4442 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4444 /* In an exact node, only one thing can be matched, that first
4445 * character. If both the pat and the target are UTF-8, we can just
4446 * copy the input to the output, avoiding finding the code point of
4451 else if (utf8_target) {
4452 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4453 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4454 utf8_has_been_setup = TRUE;
4457 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4460 else { /* an EXACTFish node */
4461 U8 *pat_end = pat + STR_LEN(text_node);
4463 /* An EXACTFL node has at least some characters unfolded, because what
4464 * they match is not known until now. So, now is the time to fold
4465 * the first few of them, as many as are needed to determine 'c1' and
4466 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4467 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4468 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4469 * need to fold as many characters as a single character can fold to,
4470 * so that later we can check if the first ones are such a multi-char
4471 * fold. But, in such a pattern only locale-problematic characters
4472 * aren't folded, so we can skip this completely if the first character
4473 * in the node isn't one of the tricky ones */
4474 if (OP(text_node) == EXACTFL) {
4476 if (! is_utf8_pat) {
4477 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4479 folded[0] = folded[1] = 's';
4481 pat_end = folded + 2;
4484 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4489 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4491 *(d++) = (U8) toFOLD_LC(*s);
4496 _toFOLD_utf8_flags(s,
4500 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4511 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4512 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4514 /* Multi-character folds require more context to sort out. Also
4515 * PL_utf8_foldclosures used below doesn't handle them, so have to
4516 * be handled outside this routine */
4517 use_chrtest_void = TRUE;
4519 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4520 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4522 const unsigned int * remaining_folds_to_list;
4523 unsigned int first_folds_to;
4525 /* Look up what code points (besides c1) fold to c1; e.g.,
4526 * [ 'K', KELVIN_SIGN ] both fold to 'k'. */
4527 Size_t folds_to_count = _inverse_folds(c1,
4529 &remaining_folds_to_list);
4530 if (folds_to_count == 0) {
4531 c2 = c1; /* there is only a single character that could
4534 else if (folds_to_count != 1) {
4535 /* If there aren't exactly two folds to this (itself and
4536 * another), it is outside the scope of this function */
4537 use_chrtest_void = TRUE;
4539 else { /* There are two. We already have one, get the other */
4540 c2 = first_folds_to;
4542 /* Folds that cross the 255/256 boundary are forbidden if
4543 * EXACTFL (and isnt a UTF8 locale), or EXACTFAA and one is
4544 * ASCIII. The only other match to c1 is c2, and since c1
4545 * is above 255, c2 better be as well under these
4546 * circumstances. If it isn't, it means the only legal
4547 * match of c1 is itself. */
4549 && ( ( OP(text_node) == EXACTFL
4550 && ! IN_UTF8_CTYPE_LOCALE)
4551 || (( OP(text_node) == EXACTFAA
4552 || OP(text_node) == EXACTFAA_NO_TRIE)
4553 && (isASCII(c1) || isASCII(c2)))))
4559 else /* Here, c1 is <= 255 */
4561 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4562 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4563 && ((OP(text_node) != EXACTFAA
4564 && OP(text_node) != EXACTFAA_NO_TRIE)
4567 /* Here, there could be something above Latin1 in the target
4568 * which folds to this character in the pattern. All such
4569 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4570 * than two characters involved in their folds, so are outside
4571 * the scope of this function */
4572 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4573 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4576 use_chrtest_void = TRUE;
4579 else { /* Here nothing above Latin1 can fold to the pattern
4581 switch (OP(text_node)) {
4583 case EXACTFL: /* /l rules */
4584 c2 = PL_fold_locale[c1];
4587 case EXACTF: /* This node only generated for non-utf8
4589 assert(! is_utf8_pat);
4590 if (! utf8_target) { /* /d rules */
4595 /* /u rules for all these. This happens to work for
4596 * EXACTFAA as nothing in Latin1 folds to ASCII */
4597 case EXACTFAA_NO_TRIE: /* This node only generated for
4598 non-utf8 patterns */
4599 assert(! is_utf8_pat);
4604 c2 = PL_fold_latin1[c1];
4608 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4609 NOT_REACHED; /* NOTREACHED */
4615 /* Here have figured things out. Set up the returns */
4616 if (use_chrtest_void) {
4617 *c2p = *c1p = CHRTEST_VOID;
4619 else if (utf8_target) {
4620 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4621 uvchr_to_utf8(c1_utf8, c1);
4622 uvchr_to_utf8(c2_utf8, c2);
4625 /* Invariants are stored in both the utf8 and byte outputs; Use
4626 * negative numbers otherwise for the byte ones. Make sure that the
4627 * byte ones are the same iff the utf8 ones are the same */
4628 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4629 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4632 ? CHRTEST_NOT_A_CP_1
4633 : CHRTEST_NOT_A_CP_2;
4635 else if (c1 > 255) {
4636 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4641 *c1p = *c2p = c2; /* c2 is the only representable value */
4643 else { /* c1 is representable; see about c2 */
4645 *c2p = (c2 < 256) ? c2 : c1;
4652 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4654 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4655 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4657 PERL_ARGS_ASSERT_ISGCB;
4659 switch (GCB_table[before][after]) {
4666 case GCB_RI_then_RI:
4669 U8 * temp_pos = (U8 *) curpos;
4671 /* Do not break within emoji flag sequences. That is, do not
4672 * break between regional indicator (RI) symbols if there is an
4673 * odd number of RI characters before the break point.
4674 * GB12 sot (RI RI)* RI × RI
4675 * GB13 [^RI] (RI RI)* RI × RI */
4677 while (backup_one_GCB(strbeg,
4679 utf8_target) == GCB_Regional_Indicator)
4684 return RI_count % 2 != 1;
4687 case GCB_EX_then_EM:
4689 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4691 U8 * temp_pos = (U8 *) curpos;
4695 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4697 while (prev == GCB_Extend);
4699 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4707 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4708 before, after, GCB_table[before][after]);
4715 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4719 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4721 if (*curpos < strbeg) {
4726 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4727 U8 * prev_prev_char_pos;
4729 if (! prev_char_pos) {
4733 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4734 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4735 *curpos = prev_char_pos;
4736 prev_char_pos = prev_prev_char_pos;
4739 *curpos = (U8 *) strbeg;
4744 if (*curpos - 2 < strbeg) {
4745 *curpos = (U8 *) strbeg;
4749 gcb = getGCB_VAL_CP(*(*curpos - 1));
4755 /* Combining marks attach to most classes that precede them, but this defines
4756 * the exceptions (from TR14) */
4757 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4758 || prev == LB_Mandatory_Break \
4759 || prev == LB_Carriage_Return \
4760 || prev == LB_Line_Feed \
4761 || prev == LB_Next_Line \
4762 || prev == LB_Space \
4763 || prev == LB_ZWSpace))
4766 S_isLB(pTHX_ LB_enum before,
4768 const U8 * const strbeg,
4769 const U8 * const curpos,
4770 const U8 * const strend,
4771 const bool utf8_target)
4773 U8 * temp_pos = (U8 *) curpos;
4774 LB_enum prev = before;
4776 /* Is the boundary between 'before' and 'after' line-breakable?
4777 * Most of this is just a table lookup of a generated table from Unicode
4778 * rules. But some rules require context to decide, and so have to be
4779 * implemented in code */
4781 PERL_ARGS_ASSERT_ISLB;
4783 /* Rule numbers in the comments below are as of Unicode 9.0 */
4787 switch (LB_table[before][after]) {
4792 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4795 case LB_SP_foo + LB_BREAKABLE:
4796 case LB_SP_foo + LB_NOBREAK:
4797 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4799 /* When we have something following a SP, we have to look at the
4800 * context in order to know what to do.
4802 * SP SP should not reach here because LB7: Do not break before
4803 * spaces. (For two spaces in a row there is nothing that
4804 * overrides that) */
4805 assert(after != LB_Space);
4807 /* Here we have a space followed by a non-space. Mostly this is a
4808 * case of LB18: "Break after spaces". But there are complications
4809 * as the handling of spaces is somewhat tricky. They are in a
4810 * number of rules, which have to be applied in priority order, but
4811 * something earlier in the string can cause a rule to be skipped
4812 * and a lower priority rule invoked. A prime example is LB7 which
4813 * says don't break before a space. But rule LB8 (lower priority)
4814 * says that the first break opportunity after a ZW is after any
4815 * span of spaces immediately after it. If a ZW comes before a SP
4816 * in the input, rule LB8 applies, and not LB7. Other such rules
4817 * involve combining marks which are rules 9 and 10, but they may
4818 * override higher priority rules if they come earlier in the
4819 * string. Since we're doing random access into the middle of the
4820 * string, we have to look for rules that should get applied based
4821 * on both string position and priority. Combining marks do not
4822 * attach to either ZW nor SP, so we don't have to consider them
4825 * To check for LB8, we have to find the first non-space character
4826 * before this span of spaces */
4828 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4830 while (prev == LB_Space);
4832 /* LB8 Break before any character following a zero-width space,
4833 * even if one or more spaces intervene.
4835 * So if we have a ZW just before this span, and to get here this
4836 * is the final space in the span. */
4837 if (prev == LB_ZWSpace) {
4841 /* Here, not ZW SP+. There are several rules that have higher
4842 * priority than LB18 and can be resolved now, as they don't depend
4843 * on anything earlier in the string (except ZW, which we have
4844 * already handled). One of these rules is LB11 Do not break
4845 * before Word joiner, but we have specially encoded that in the
4846 * lookup table so it is caught by the single test below which
4847 * catches the other ones. */
4848 if (LB_table[LB_Space][after] - LB_SP_foo
4849 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4854 /* If we get here, we have to XXX consider combining marks. */
4855 if (prev == LB_Combining_Mark) {
4857 /* What happens with these depends on the character they
4860 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4862 while (prev == LB_Combining_Mark);
4864 /* Most times these attach to and inherit the characteristics
4865 * of that character, but not always, and when not, they are to
4866 * be treated as AL by rule LB10. */
4867 if (! LB_CM_ATTACHES_TO(prev)) {
4868 prev = LB_Alphabetic;
4872 /* Here, we have the character preceding the span of spaces all set
4873 * up. We follow LB18: "Break after spaces" unless the table shows
4874 * that is overriden */
4875 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4879 /* We don't know how to treat the CM except by looking at the first
4880 * non-CM character preceding it. ZWJ is treated as CM */
4882 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4884 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4886 /* Here, 'prev' is that first earlier non-CM character. If the CM
4887 * attatches to it, then it inherits the behavior of 'prev'. If it
4888 * doesn't attach, it is to be treated as an AL */
4889 if (! LB_CM_ATTACHES_TO(prev)) {
4890 prev = LB_Alphabetic;
4895 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4896 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4898 /* LB21a Don't break after Hebrew + Hyphen.
4901 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4902 == LB_Hebrew_Letter)
4907 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4909 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4910 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4912 /* LB25a (PR | PO) × ( OP | HY )? NU */
4913 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4917 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4920 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4921 case LB_SY_or_IS_then_various + LB_NOBREAK:
4923 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4925 LB_enum temp = prev;
4927 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4929 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4930 if (temp == LB_Numeric) {
4934 return LB_table[prev][after] - LB_SY_or_IS_then_various
4938 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4939 case LB_various_then_PO_or_PR + LB_NOBREAK:
4941 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4943 LB_enum temp = prev;
4944 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4946 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4948 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4949 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4951 if (temp == LB_Numeric) {
4954 return LB_various_then_PO_or_PR;
4957 case LB_RI_then_RI + LB_NOBREAK:
4958 case LB_RI_then_RI + LB_BREAKABLE:
4962 /* LB30a Break between two regional indicator symbols if and
4963 * only if there are an even number of regional indicators
4964 * preceding the position of the break.
4966 * sot (RI RI)* RI × RI
4967 * [^RI] (RI RI)* RI × RI */
4969 while (backup_one_LB(strbeg,
4971 utf8_target) == LB_Regional_Indicator)
4976 return RI_count % 2 == 0;
4984 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4985 before, after, LB_table[before][after]);
4992 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4996 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4998 if (*curpos >= strend) {
5003 *curpos += UTF8SKIP(*curpos);
5004 if (*curpos >= strend) {
5007 lb = getLB_VAL_UTF8(*curpos, strend);
5011 if (*curpos >= strend) {
5014 lb = getLB_VAL_CP(**curpos);
5021 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5025 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
5027 if (*curpos < strbeg) {
5032 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5033 U8 * prev_prev_char_pos;
5035 if (! prev_char_pos) {
5039 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
5040 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5041 *curpos = prev_char_pos;
5042 prev_char_pos = prev_prev_char_pos;
5045 *curpos = (U8 *) strbeg;
5050 if (*curpos - 2 < strbeg) {
5051 *curpos = (U8 *) strbeg;
5055 lb = getLB_VAL_CP(*(*curpos - 1));
5062 S_isSB(pTHX_ SB_enum before,
5064 const U8 * const strbeg,
5065 const U8 * const curpos,
5066 const U8 * const strend,
5067 const bool utf8_target)
5069 /* returns a boolean indicating if there is a Sentence Boundary Break
5070 * between the inputs. See http://www.unicode.org/reports/tr29/ */
5072 U8 * lpos = (U8 *) curpos;
5073 bool has_para_sep = FALSE;
5074 bool has_sp = FALSE;
5076 PERL_ARGS_ASSERT_ISSB;
5078 /* Break at the start and end of text.
5081 But unstated in Unicode is don't break if the text is empty */
5082 if (before == SB_EDGE || after == SB_EDGE) {
5083 return before != after;
5086 /* SB 3: Do not break within CRLF. */
5087 if (before == SB_CR && after == SB_LF) {
5091 /* Break after paragraph separators. CR and LF are considered
5092 * so because Unicode views text as like word processing text where there
5093 * are no newlines except between paragraphs, and the word processor takes
5094 * care of wrapping without there being hard line-breaks in the text *./
5095 SB4. Sep | CR | LF ÷ */
5096 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
5100 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
5101 * (See Section 6.2, Replacing Ignore Rules.)
5102 SB5. X (Extend | Format)* → X */
5103 if (after == SB_Extend || after == SB_Format) {
5105 /* Implied is that the these characters attach to everything
5106 * immediately prior to them except for those separator-type
5107 * characters. And the rules earlier have already handled the case
5108 * when one of those immediately precedes the extend char */
5112 if (before == SB_Extend || before == SB_Format) {
5113 U8 * temp_pos = lpos;
5114 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
5115 if ( backup != SB_EDGE
5124 /* Here, both 'before' and 'backup' are these types; implied is that we
5125 * don't break between them */
5126 if (backup == SB_Extend || backup == SB_Format) {
5131 /* Do not break after ambiguous terminators like period, if they are
5132 * immediately followed by a number or lowercase letter, if they are
5133 * between uppercase letters, if the first following letter (optionally
5134 * after certain punctuation) is lowercase, or if they are followed by
5135 * "continuation" punctuation such as comma, colon, or semicolon. For
5136 * example, a period may be an abbreviation or numeric period, and thus may
5137 * not mark the end of a sentence.
5139 * SB6. ATerm × Numeric */
5140 if (before == SB_ATerm && after == SB_Numeric) {
5144 /* SB7. (Upper | Lower) ATerm × Upper */
5145 if (before == SB_ATerm && after == SB_Upper) {
5146 U8 * temp_pos = lpos;
5147 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
5148 if (backup == SB_Upper || backup == SB_Lower) {
5153 /* The remaining rules that aren't the final one, all require an STerm or
5154 * an ATerm after having backed up over some Close* Sp*, and in one case an
5155 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
5156 * So do that backup now, setting flags if either Sp or a paragraph
5157 * separator are found */
5159 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
5160 has_para_sep = TRUE;
5161 before = backup_one_SB(strbeg, &lpos, utf8_target);
5164 if (before == SB_Sp) {
5167 before = backup_one_SB(strbeg, &lpos, utf8_target);
5169 while (before == SB_Sp);
5172 while (before == SB_Close) {
5173 before = backup_one_SB(strbeg, &lpos, utf8_target);
5176 /* The next few rules apply only when the backed-up-to is an ATerm, and in
5177 * most cases an STerm */
5178 if (before == SB_STerm || before == SB_ATerm) {
5180 /* So, here the lhs matches
5181 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
5182 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
5183 * The rules that apply here are:
5185 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
5186 | LF | STerm | ATerm) )* Lower
5187 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
5188 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
5189 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
5190 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
5193 /* And all but SB11 forbid having seen a paragraph separator */
5194 if (! has_para_sep) {
5195 if (before == SB_ATerm) { /* SB8 */
5196 U8 * rpos = (U8 *) curpos;
5197 SB_enum later = after;
5199 while ( later != SB_OLetter
5200 && later != SB_Upper
5201 && later != SB_Lower
5205 && later != SB_STerm
5206 && later != SB_ATerm
5207 && later != SB_EDGE)
5209 later = advance_one_SB(&rpos, strend, utf8_target);
5211 if (later == SB_Lower) {
5216 if ( after == SB_SContinue /* SB8a */
5217 || after == SB_STerm
5218 || after == SB_ATerm)
5223 if (! has_sp) { /* SB9 applies only if there was no Sp* */
5224 if ( after == SB_Close
5234 /* SB10. This and SB9 could probably be combined some way, but khw
5235 * has decided to follow the Unicode rule book precisely for
5236 * simplified maintenance */
5250 /* Otherwise, do not break.
5257 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
5261 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
5263 if (*curpos >= strend) {
5269 *curpos += UTF8SKIP(*curpos);
5270 if (*curpos >= strend) {
5273 sb = getSB_VAL_UTF8(*curpos, strend);
5274 } while (sb == SB_Extend || sb == SB_Format);
5279 if (*curpos >= strend) {
5282 sb = getSB_VAL_CP(**curpos);
5283 } while (sb == SB_Extend || sb == SB_Format);
5290 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5294 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
5296 if (*curpos < strbeg) {
5301 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5302 if (! prev_char_pos) {
5306 /* Back up over Extend and Format. curpos is always just to the right
5307 * of the characater whose value we are getting */
5309 U8 * prev_prev_char_pos;
5310 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
5313 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5314 *curpos = prev_char_pos;
5315 prev_char_pos = prev_prev_char_pos;
5318 *curpos = (U8 *) strbeg;
5321 } while (sb == SB_Extend || sb == SB_Format);
5325 if (*curpos - 2 < strbeg) {
5326 *curpos = (U8 *) strbeg;
5330 sb = getSB_VAL_CP(*(*curpos - 1));
5331 } while (sb == SB_Extend || sb == SB_Format);
5338 S_isWB(pTHX_ WB_enum previous,
5341 const U8 * const strbeg,
5342 const U8 * const curpos,
5343 const U8 * const strend,
5344 const bool utf8_target)
5346 /* Return a boolean as to if the boundary between 'before' and 'after' is
5347 * a Unicode word break, using their published algorithm, but tailored for
5348 * Perl by treating spans of white space as one unit. Context may be
5349 * needed to make this determination. If the value for the character
5350 * before 'before' is known, it is passed as 'previous'; otherwise that
5351 * should be set to WB_UNKNOWN. The other input parameters give the
5352 * boundaries and current position in the matching of the string. That
5353 * is, 'curpos' marks the position where the character whose wb value is
5354 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5356 U8 * before_pos = (U8 *) curpos;
5357 U8 * after_pos = (U8 *) curpos;
5358 WB_enum prev = before;
5361 PERL_ARGS_ASSERT_ISWB;
5363 /* Rule numbers in the comments below are as of Unicode 9.0 */
5367 switch (WB_table[before][after]) {
5374 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5375 next = advance_one_WB(&after_pos, strend, utf8_target,
5376 FALSE /* Don't skip Extend nor Format */ );
5377 /* A space immediately preceeding an Extend or Format is attached
5378 * to by them, and hence gets separated from previous spaces.
5379 * Otherwise don't break between horizontal white space */
5380 return next == WB_Extend || next == WB_Format;
5382 /* WB4 Ignore Format and Extend characters, except when they appear at
5383 * the beginning of a region of text. This code currently isn't
5384 * general purpose, but it works as the rules are currently and likely
5385 * to be laid out. The reason it works is that when 'they appear at
5386 * the beginning of a region of text', the rule is to break before
5387 * them, just like any other character. Therefore, the default rule
5388 * applies and we don't have to look in more depth. Should this ever
5389 * change, we would have to have 2 'case' statements, like in the rules
5390 * below, and backup a single character (not spacing over the extend
5391 * ones) and then see if that is one of the region-end characters and
5393 case WB_Ex_or_FO_or_ZWJ_then_foo:
5394 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5397 case WB_DQ_then_HL + WB_BREAKABLE:
5398 case WB_DQ_then_HL + WB_NOBREAK:
5400 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5402 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5403 == WB_Hebrew_Letter)
5408 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5410 case WB_HL_then_DQ + WB_BREAKABLE:
5411 case WB_HL_then_DQ + WB_NOBREAK:
5413 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5415 if (advance_one_WB(&after_pos, strend, utf8_target,
5416 TRUE /* Do skip Extend and Format */ )
5417 == WB_Hebrew_Letter)
5422 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5424 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5425 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5427 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5428 * | Single_Quote) (ALetter | Hebrew_Letter) */
5430 next = advance_one_WB(&after_pos, strend, utf8_target,
5431 TRUE /* Do skip Extend and Format */ );
5433 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5438 return WB_table[before][after]
5439 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5441 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5442 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5444 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5445 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5447 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5448 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5453 return WB_table[before][after]
5454 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5456 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5457 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5459 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5462 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5468 return WB_table[before][after]
5469 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5471 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5472 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5474 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5476 if (advance_one_WB(&after_pos, strend, utf8_target,
5477 TRUE /* Do skip Extend and Format */ )
5483 return WB_table[before][after]
5484 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5486 case WB_RI_then_RI + WB_NOBREAK:
5487 case WB_RI_then_RI + WB_BREAKABLE:
5491 /* Do not break within emoji flag sequences. That is, do not
5492 * break between regional indicator (RI) symbols if there is an
5493 * odd number of RI characters before the potential break
5496 * WB15 sot (RI RI)* RI × RI
5497 * WB16 [^RI] (RI RI)* RI × RI */
5499 while (backup_one_WB(&previous,
5502 utf8_target) == WB_Regional_Indicator)
5507 return RI_count % 2 != 1;
5515 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5516 before, after, WB_table[before][after]);
5523 S_advance_one_WB(pTHX_ U8 ** curpos,
5524 const U8 * const strend,
5525 const bool utf8_target,
5526 const bool skip_Extend_Format)
5530 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5532 if (*curpos >= strend) {
5538 /* Advance over Extend and Format */
5540 *curpos += UTF8SKIP(*curpos);
5541 if (*curpos >= strend) {
5544 wb = getWB_VAL_UTF8(*curpos, strend);
5545 } while ( skip_Extend_Format
5546 && (wb == WB_Extend || wb == WB_Format));
5551 if (*curpos >= strend) {
5554 wb = getWB_VAL_CP(**curpos);
5555 } while ( skip_Extend_Format
5556 && (wb == WB_Extend || wb == WB_Format));
5563 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5567 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5569 /* If we know what the previous character's break value is, don't have
5571 if (*previous != WB_UNKNOWN) {
5574 /* But we need to move backwards by one */
5576 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5578 *previous = WB_EDGE;
5579 *curpos = (U8 *) strbeg;
5582 *previous = WB_UNKNOWN;
5587 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5590 /* And we always back up over these three types */
5591 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5596 if (*curpos < strbeg) {
5601 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5602 if (! prev_char_pos) {
5606 /* Back up over Extend and Format. curpos is always just to the right
5607 * of the characater whose value we are getting */
5609 U8 * prev_prev_char_pos;
5610 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5614 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5615 *curpos = prev_char_pos;
5616 prev_char_pos = prev_prev_char_pos;
5619 *curpos = (U8 *) strbeg;
5622 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5626 if (*curpos - 2 < strbeg) {
5627 *curpos = (U8 *) strbeg;
5631 wb = getWB_VAL_CP(*(*curpos - 1));
5632 } while (wb == WB_Extend || wb == WB_Format);
5638 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5641 ( ( st )->u.eval.close_paren ) && \
5642 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5645 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5648 ( ( st )->u.eval.close_paren ) && \
5650 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5654 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5655 (st)->u.eval.close_paren = ( (expr) + 1 )
5657 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5658 (st)->u.eval.close_paren = 0
5660 /* returns -1 on failure, $+[0] on success */
5662 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5665 const bool utf8_target = reginfo->is_utf8_target;
5666 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5667 REGEXP *rex_sv = reginfo->prog;
5668 regexp *rex = ReANY(rex_sv);
5669 RXi_GET_DECL(rex,rexi);
5670 /* the current state. This is a cached copy of PL_regmatch_state */
5672 /* cache heavy used fields of st in registers */
5675 U32 n = 0; /* general value; init to avoid compiler warning */
5676 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5677 SSize_t endref = 0; /* offset of end of backref when ln is start */
5678 char *locinput = startpos;
5679 char *pushinput; /* where to continue after a PUSH */
5680 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5682 bool result = 0; /* return value of S_regmatch */
5683 U32 depth = 0; /* depth of backtrack stack */
5684 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5685 const U32 max_nochange_depth =
5686 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5687 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5688 regmatch_state *yes_state = NULL; /* state to pop to on success of
5690 /* mark_state piggy backs on the yes_state logic so that when we unwind
5691 the stack on success we can update the mark_state as we go */
5692 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5693 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5694 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5696 bool no_final = 0; /* prevent failure from backtracking? */
5697 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5698 char *startpoint = locinput;
5699 SV *popmark = NULL; /* are we looking for a mark? */
5700 SV *sv_commit = NULL; /* last mark name seen in failure */
5701 SV *sv_yes_mark = NULL; /* last mark name we have seen
5702 during a successful match */
5703 U32 lastopen = 0; /* last open we saw */
5704 bool has_cutgroup = RXp_HAS_CUTGROUP(rex) ? 1 : 0;
5705 SV* const oreplsv = GvSVn(PL_replgv);
5706 /* these three flags are set by various ops to signal information to
5707 * the very next op. They have a useful lifetime of exactly one loop
5708 * iteration, and are not preserved or restored by state pushes/pops
5710 bool sw = 0; /* the condition value in (?(cond)a|b) */
5711 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5712 int logical = 0; /* the following EVAL is:
5716 or the following IFMATCH/UNLESSM is:
5717 false: plain (?=foo)
5718 true: used as a condition: (?(?=foo))
5720 PAD* last_pad = NULL;
5722 U8 gimme = G_SCALAR;
5723 CV *caller_cv = NULL; /* who called us */
5724 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5725 U32 maxopenparen = 0; /* max '(' index seen so far */
5726 int to_complement; /* Invert the result? */
5727 _char_class_number classnum;
5728 bool is_utf8_pat = reginfo->is_utf8_pat;
5730 I32 orig_savestack_ix = PL_savestack_ix;
5731 U8 * script_run_begin = NULL;
5733 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5734 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5735 # define SOLARIS_BAD_OPTIMIZER
5736 const U32 *pl_charclass_dup = PL_charclass;
5737 # define PL_charclass pl_charclass_dup
5741 GET_RE_DEBUG_FLAGS_DECL;
5744 /* protect against undef(*^R) */
5745 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5747 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5748 multicall_oldcatch = 0;
5749 PERL_UNUSED_VAR(multicall_cop);
5751 PERL_ARGS_ASSERT_REGMATCH;
5753 st = PL_regmatch_state;
5755 /* Note that nextchr is a byte even in UTF */
5759 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5760 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5761 Perl_re_printf( aTHX_ "regmatch start\n" );
5764 while (scan != NULL) {
5765 next = scan + NEXT_OFF(scan);
5768 state_num = OP(scan);
5772 if (state_num <= REGNODE_MAX) {
5773 SV * const prop = sv_newmortal();
5774 regnode *rnext = regnext(scan);
5776 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5777 regprop(rex, prop, scan, reginfo, NULL);
5778 Perl_re_printf( aTHX_
5779 "%*s%" IVdf ":%s(%" IVdf ")\n",
5780 INDENT_CHARS(depth), "",
5781 (IV)(scan - rexi->program),
5783 (PL_regkind[OP(scan)] == END || !rnext) ?
5784 0 : (IV)(rnext - rexi->program));
5791 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5793 switch (state_num) {
5794 case SBOL: /* /^../ and /\A../ */
5795 if (locinput == reginfo->strbeg)
5799 case MBOL: /* /^../m */
5800 if (locinput == reginfo->strbeg ||
5801 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5808 if (locinput == reginfo->ganch)
5812 case KEEPS: /* \K */
5813 /* update the startpoint */
5814 st->u.keeper.val = rex->offs[0].start;
5815 rex->offs[0].start = locinput - reginfo->strbeg;
5816 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5817 NOT_REACHED; /* NOTREACHED */
5819 case KEEPS_next_fail:
5820 /* rollback the start point change */
5821 rex->offs[0].start = st->u.keeper.val;
5823 NOT_REACHED; /* NOTREACHED */
5825 case MEOL: /* /..$/m */
5826 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5830 case SEOL: /* /..$/ */
5831 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5833 if (reginfo->strend - locinput > 1)
5838 if (!NEXTCHR_IS_EOS)
5842 case SANY: /* /./s */
5845 goto increment_locinput;
5847 case REG_ANY: /* /./ */
5848 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5850 goto increment_locinput;
5854 #define ST st->u.trie
5855 case TRIEC: /* (ab|cd) with known charclass */
5856 /* In this case the charclass data is available inline so
5857 we can fail fast without a lot of extra overhead.
5859 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5861 Perl_re_exec_indentf( aTHX_ "%sTRIE: failed to match trie start class...%s\n",
5862 depth, PL_colors[4], PL_colors[5])
5865 NOT_REACHED; /* NOTREACHED */
5868 case TRIE: /* (ab|cd) */
5869 /* the basic plan of execution of the trie is:
5870 * At the beginning, run though all the states, and
5871 * find the longest-matching word. Also remember the position
5872 * of the shortest matching word. For example, this pattern:
5875 * when matched against the string "abcde", will generate
5876 * accept states for all words except 3, with the longest
5877 * matching word being 4, and the shortest being 2 (with
5878 * the position being after char 1 of the string).
5880 * Then for each matching word, in word order (i.e. 1,2,4,5),
5881 * we run the remainder of the pattern; on each try setting
5882 * the current position to the character following the word,
5883 * returning to try the next word on failure.
5885 * We avoid having to build a list of words at runtime by
5886 * using a compile-time structure, wordinfo[].prev, which
5887 * gives, for each word, the previous accepting word (if any).
5888 * In the case above it would contain the mappings 1->2, 2->0,
5889 * 3->0, 4->5, 5->1. We can use this table to generate, from
5890 * the longest word (4 above), a list of all words, by
5891 * following the list of prev pointers; this gives us the
5892 * unordered list 4,5,1,2. Then given the current word we have
5893 * just tried, we can go through the list and find the
5894 * next-biggest word to try (so if we just failed on word 2,
5895 * the next in the list is 4).
5897 * Since at runtime we don't record the matching position in
5898 * the string for each word, we have to work that out for
5899 * each word we're about to process. The wordinfo table holds
5900 * the character length of each word; given that we recorded
5901 * at the start: the position of the shortest word and its
5902 * length in chars, we just need to move the pointer the
5903 * difference between the two char lengths. Depending on
5904 * Unicode status and folding, that's cheap or expensive.
5906 * This algorithm is optimised for the case where are only a
5907 * small number of accept states, i.e. 0,1, or maybe 2.
5908 * With lots of accepts states, and having to try all of them,
5909 * it becomes quadratic on number of accept states to find all
5914 /* what type of TRIE am I? (utf8 makes this contextual) */
5915 DECL_TRIE_TYPE(scan);
5917 /* what trie are we using right now */
5918 reg_trie_data * const trie
5919 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5920 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5921 U32 state = trie->startstate;
5923 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5924 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5927 && UTF8_IS_ABOVE_LATIN1(nextchr)
5928 && scan->flags == EXACTL)
5930 /* We only output for EXACTL, as we let the folder
5931 * output this message for EXACTFLU8 to avoid
5933 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5938 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5940 if (trie->states[ state ].wordnum) {
5942 Perl_re_exec_indentf( aTHX_ "%sTRIE: matched empty string...%s\n",
5943 depth, PL_colors[4], PL_colors[5])
5949 Perl_re_exec_indentf( aTHX_ "%sTRIE: failed to match trie start class...%s\n",
5950 depth, PL_colors[4], PL_colors[5])
5957 U8 *uc = ( U8* )locinput;
5961 U8 *uscan = (U8*)NULL;
5962 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5963 U32 charcount = 0; /* how many input chars we have matched */
5964 U32 accepted = 0; /* have we seen any accepting states? */
5966 ST.jump = trie->jump;
5969 ST.longfold = FALSE; /* char longer if folded => it's harder */
5972 /* fully traverse the TRIE; note the position of the
5973 shortest accept state and the wordnum of the longest
5976 while ( state && uc <= (U8*)(reginfo->strend) ) {
5977 U32 base = trie->states[ state ].trans.base;
5981 wordnum = trie->states[ state ].wordnum;
5983 if (wordnum) { /* it's an accept state */
5986 /* record first match position */
5988 ST.firstpos = (U8*)locinput;
5993 ST.firstchars = charcount;
5996 if (!ST.nextword || wordnum < ST.nextword)
5997 ST.nextword = wordnum;
5998 ST.topword = wordnum;
6001 DEBUG_TRIE_EXECUTE_r({
6002 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
6004 PerlIO_printf( Perl_debug_log,
6005 "%*s%sTRIE: State: %4" UVxf " Accepted: %c ",
6006 INDENT_CHARS(depth), "", PL_colors[4],
6007 (UV)state, (accepted ? 'Y' : 'N'));
6010 /* read a char and goto next state */
6011 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
6013 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
6014 (U8 *) reginfo->strend, uscan,
6015 len, uvc, charid, foldlen,
6022 base + charid - 1 - trie->uniquecharcount)) >= 0)
6024 && ((U32)offset < trie->lasttrans)
6025 && trie->trans[offset].check == state)
6027 state = trie->trans[offset].next;
6038 DEBUG_TRIE_EXECUTE_r(
6039 Perl_re_printf( aTHX_
6040 "TRIE: Charid:%3x CP:%4" UVxf " After State: %4" UVxf "%s\n",
6041 charid, uvc, (UV)state, PL_colors[5] );
6047 /* calculate total number of accept states */
6052 w = trie->wordinfo[w].prev;
6055 ST.accepted = accepted;
6059 Perl_re_exec_indentf( aTHX_ "%sTRIE: got %" IVdf " possible matches%s\n",
6061 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
6063 goto trie_first_try; /* jump into the fail handler */
6065 NOT_REACHED; /* NOTREACHED */
6067 case TRIE_next_fail: /* we failed - try next alternative */
6071 /* undo any captures done in the tail part of a branch,
6073 * /(?:X(.)(.)|Y(.)).../
6074 * where the trie just matches X then calls out to do the
6075 * rest of the branch */
6076 REGCP_UNWIND(ST.cp);
6077 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6079 if (!--ST.accepted) {
6081 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
6089 /* Find next-highest word to process. Note that this code
6090 * is O(N^2) per trie run (O(N) per branch), so keep tight */
6093 U16 const nextword = ST.nextword;
6094 reg_trie_wordinfo * const wordinfo
6095 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
6096 for (word=ST.topword; word; word=wordinfo[word].prev) {
6097 if (word > nextword && (!min || word < min))
6110 ST.lastparen = rex->lastparen;
6111 ST.lastcloseparen = rex->lastcloseparen;
6115 /* find start char of end of current word */
6117 U32 chars; /* how many chars to skip */
6118 reg_trie_data * const trie
6119 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
6121 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
6123 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
6128 /* the hard option - fold each char in turn and find
6129 * its folded length (which may be different */
6130 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
6138 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
6146 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
6151 uvc = utf8n_to_uvchr(uscan, foldlen, &len,
6167 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
6168 ? ST.jump[ST.nextword]
6172 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
6180 if ( ST.accepted > 1 || has_cutgroup || ST.jump ) {
6181 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
6182 NOT_REACHED; /* NOTREACHED */
6184 /* only one choice left - just continue */
6186 AV *const trie_words
6187 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
6188 SV ** const tmp = trie_words
6189 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
6190 SV *sv= tmp ? sv_newmortal() : NULL;
6192 Perl_re_exec_indentf( aTHX_ "%sTRIE: only one match left, short-circuiting: #%d <%s>%s\n",
6193 depth, PL_colors[4],
6195 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
6196 PL_colors[0], PL_colors[1],
6197 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
6199 : "not compiled under -Dr",
6203 locinput = (char*)uc;
6204 continue; /* execute rest of RE */
6209 case EXACTL: /* /abc/l */
6210 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6212 /* Complete checking would involve going through every character
6213 * matched by the string to see if any is above latin1. But the
6214 * comparision otherwise might very well be a fast assembly
6215 * language routine, and I (khw) don't think slowing things down
6216 * just to check for this warning is worth it. So this just checks
6217 * the first character */
6218 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
6219 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6222 case EXACT: { /* /abc/ */
6223 char *s = STRING(scan);
6225 if (utf8_target != is_utf8_pat) {
6226 /* The target and the pattern have differing utf8ness. */
6228 const char * const e = s + ln;
6231 /* The target is utf8, the pattern is not utf8.
6232 * Above-Latin1 code points can't match the pattern;
6233 * invariants match exactly, and the other Latin1 ones need
6234 * to be downgraded to a single byte in order to do the
6235 * comparison. (If we could be confident that the target
6236 * is not malformed, this could be refactored to have fewer
6237 * tests by just assuming that if the first bytes match, it
6238 * is an invariant, but there are tests in the test suite
6239 * dealing with (??{...}) which violate this) */
6241 if (l >= reginfo->strend
6242 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
6246 if (UTF8_IS_INVARIANT(*(U8*)l)) {
6253 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
6263 /* The target is not utf8, the pattern is utf8. */
6265 if (l >= reginfo->strend
6266 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
6270 if (UTF8_IS_INVARIANT(*(U8*)s)) {
6277 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
6289 /* The target and the pattern have the same utf8ness. */
6290 /* Inline the first character, for speed. */
6291 if (reginfo->strend - locinput < ln
6292 || UCHARAT(s) != nextchr
6293 || (ln > 1 && memNE(s, locinput, ln)))
6302 case EXACTFL: { /* /abc/il */
6304 const U8 * fold_array;
6306 U32 fold_utf8_flags;
6308 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6309 folder = foldEQ_locale;
6310 fold_array = PL_fold_locale;
6311 fold_utf8_flags = FOLDEQ_LOCALE;
6314 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
6315 is effectively /u; hence to match, target
6317 if (! utf8_target) {
6320 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
6321 | FOLDEQ_S1_FOLDS_SANE;
6322 folder = foldEQ_latin1;
6323 fold_array = PL_fold_latin1;
6326 case EXACTFU_SS: /* /\x{df}/iu */
6327 case EXACTFU: /* /abc/iu */
6328 folder = foldEQ_latin1;
6329 fold_array = PL_fold_latin1;
6330 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
6333 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8
6335 assert(! is_utf8_pat);
6337 case EXACTFAA: /* /abc/iaa */
6338 folder = foldEQ_latin1;
6339 fold_array = PL_fold_latin1;
6340 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6343 case EXACTF: /* /abc/i This node only generated for
6344 non-utf8 patterns */
6345 assert(! is_utf8_pat);
6347 fold_array = PL_fold;
6348 fold_utf8_flags = 0;
6356 || state_num == EXACTFU_SS
6357 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6359 /* Either target or the pattern are utf8, or has the issue where
6360 * the fold lengths may differ. */
6361 const char * const l = locinput;
6362 char *e = reginfo->strend;
6364 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6365 l, &e, 0, utf8_target, fold_utf8_flags))
6373 /* Neither the target nor the pattern are utf8 */
6374 if (UCHARAT(s) != nextchr
6376 && UCHARAT(s) != fold_array[nextchr])
6380 if (reginfo->strend - locinput < ln)
6382 if (ln > 1 && ! folder(s, locinput, ln))
6388 case NBOUNDL: /* /\B/l */
6392 case BOUNDL: /* /\b/l */
6395 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6397 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6398 if (! IN_UTF8_CTYPE_LOCALE) {
6399 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6400 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6406 if (locinput == reginfo->strbeg)
6407 b1 = isWORDCHAR_LC('\n');
6409 b1 = isWORDCHAR_LC_utf8_safe(reghop3((U8*)locinput, -1,
6410 (U8*)(reginfo->strbeg)),
6411 (U8*)(reginfo->strend));
6413 b2 = (NEXTCHR_IS_EOS)
6414 ? isWORDCHAR_LC('\n')
6415 : isWORDCHAR_LC_utf8_safe((U8*) locinput,
6416 (U8*) reginfo->strend);
6418 else { /* Here the string isn't utf8 */
6419 b1 = (locinput == reginfo->strbeg)
6420 ? isWORDCHAR_LC('\n')
6421 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6422 b2 = (NEXTCHR_IS_EOS)
6423 ? isWORDCHAR_LC('\n')
6424 : isWORDCHAR_LC(nextchr);
6426 if (to_complement ^ (b1 == b2)) {
6432 case NBOUND: /* /\B/ */
6436 case BOUND: /* /\b/ */
6440 goto bound_ascii_match_only;
6442 case NBOUNDA: /* /\B/a */
6446 case BOUNDA: /* /\b/a */
6450 bound_ascii_match_only:
6451 /* Here the string isn't utf8, or is utf8 and only ascii characters
6452 * are to match \w. In the latter case looking at the byte just
6453 * prior to the current one may be just the final byte of a
6454 * multi-byte character. This is ok. There are two cases:
6455 * 1) it is a single byte character, and then the test is doing
6456 * just what it's supposed to.
6457 * 2) it is a multi-byte character, in which case the final byte is
6458 * never mistakable for ASCII, and so the test will say it is
6459 * not a word character, which is the correct answer. */
6460 b1 = (locinput == reginfo->strbeg)
6461 ? isWORDCHAR_A('\n')
6462 : isWORDCHAR_A(UCHARAT(locinput - 1));
6463 b2 = (NEXTCHR_IS_EOS)
6464 ? isWORDCHAR_A('\n')
6465 : isWORDCHAR_A(nextchr);
6466 if (to_complement ^ (b1 == b2)) {
6472 case NBOUNDU: /* /\B/u */
6476 case BOUNDU: /* /\b/u */
6479 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6482 else if (utf8_target) {
6484 switch((bound_type) FLAGS(scan)) {
6485 case TRADITIONAL_BOUND:
6488 b1 = (locinput == reginfo->strbeg)
6489 ? 0 /* isWORDCHAR_L1('\n') */
6490 : isWORDCHAR_utf8_safe(
6491 reghop3((U8*)locinput,
6493 (U8*)(reginfo->strbeg)),
6494 (U8*) reginfo->strend);
6495 b2 = (NEXTCHR_IS_EOS)
6496 ? 0 /* isWORDCHAR_L1('\n') */
6497 : isWORDCHAR_utf8_safe((U8*)locinput,
6498 (U8*) reginfo->strend);
6499 match = cBOOL(b1 != b2);
6503 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6504 match = TRUE; /* GCB always matches at begin and
6508 /* Find the gcb values of previous and current
6509 * chars, then see if is a break point */
6510 match = isGCB(getGCB_VAL_UTF8(
6511 reghop3((U8*)locinput,
6513 (U8*)(reginfo->strbeg)),
6514 (U8*) reginfo->strend),
6515 getGCB_VAL_UTF8((U8*) locinput,
6516 (U8*) reginfo->strend),
6517 (U8*) reginfo->strbeg,
6524 if (locinput == reginfo->strbeg) {
6527 else if (NEXTCHR_IS_EOS) {
6531 match = isLB(getLB_VAL_UTF8(
6532 reghop3((U8*)locinput,
6534 (U8*)(reginfo->strbeg)),
6535 (U8*) reginfo->strend),
6536 getLB_VAL_UTF8((U8*) locinput,
6537 (U8*) reginfo->strend),
6538 (U8*) reginfo->strbeg,
6540 (U8*) reginfo->strend,
6545 case SB_BOUND: /* Always matches at begin and end */
6546 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6550 match = isSB(getSB_VAL_UTF8(
6551 reghop3((U8*)locinput,
6553 (U8*)(reginfo->strbeg)),
6554 (U8*) reginfo->strend),
6555 getSB_VAL_UTF8((U8*) locinput,
6556 (U8*) reginfo->strend),
6557 (U8*) reginfo->strbeg,
6559 (U8*) reginfo->strend,
6565 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6569 match = isWB(WB_UNKNOWN,
6571 reghop3((U8*)locinput,
6573 (U8*)(reginfo->strbeg)),
6574 (U8*) reginfo->strend),
6575 getWB_VAL_UTF8((U8*) locinput,
6576 (U8*) reginfo->strend),
6577 (U8*) reginfo->strbeg,
6579 (U8*) reginfo->strend,
6585 else { /* Not utf8 target */
6586 switch((bound_type) FLAGS(scan)) {
6587 case TRADITIONAL_BOUND:
6590 b1 = (locinput == reginfo->strbeg)
6591 ? 0 /* isWORDCHAR_L1('\n') */
6592 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6593 b2 = (NEXTCHR_IS_EOS)
6594 ? 0 /* isWORDCHAR_L1('\n') */
6595 : isWORDCHAR_L1(nextchr);
6596 match = cBOOL(b1 != b2);
6601 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6602 match = TRUE; /* GCB always matches at begin and
6605 else { /* Only CR-LF combo isn't a GCB in 0-255
6607 match = UCHARAT(locinput - 1) != '\r'
6608 || UCHARAT(locinput) != '\n';
6613 if (locinput == reginfo->strbeg) {
6616 else if (NEXTCHR_IS_EOS) {
6620 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6621 getLB_VAL_CP(UCHARAT(locinput)),
6622 (U8*) reginfo->strbeg,
6624 (U8*) reginfo->strend,
6629 case SB_BOUND: /* Always matches at begin and end */
6630 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6634 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6635 getSB_VAL_CP(UCHARAT(locinput)),
6636 (U8*) reginfo->strbeg,
6638 (U8*) reginfo->strend,
6644 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6648 match = isWB(WB_UNKNOWN,
6649 getWB_VAL_CP(UCHARAT(locinput -1)),
6650 getWB_VAL_CP(UCHARAT(locinput)),
6651 (U8*) reginfo->strbeg,
6653 (U8*) reginfo->strend,
6660 if (to_complement ^ ! match) {
6665 case ANYOFL: /* /[abc]/l */
6666 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6668 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6670 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6673 case ANYOFD: /* /[abc]/d */
6674 case ANYOF: /* /[abc]/ */
6677 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6678 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6681 locinput += UTF8SKIP(locinput);
6684 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6691 if (NEXTCHR_IS_EOS || (UCHARAT(locinput) & FLAGS(scan)) != ARG(scan)) {
6698 if (NEXTCHR_IS_EOS || ! isASCII(UCHARAT(locinput))) {
6702 locinput++; /* ASCII is always single byte */
6706 if (NEXTCHR_IS_EOS || isASCII(UCHARAT(locinput))) {
6710 goto increment_locinput;
6713 /* The argument (FLAGS) to all the POSIX node types is the class number
6716 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6720 case POSIXL: /* \w or [:punct:] etc. under /l */
6721 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6725 /* Use isFOO_lc() for characters within Latin1. (Note that
6726 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6727 * wouldn't be invariant) */
6728 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6729 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6737 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6738 /* An above Latin-1 code point, or malformed */
6739 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
6741 goto utf8_posix_above_latin1;
6744 /* Here is a UTF-8 variant code point below 256 and the target is
6746 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6747 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6748 *(locinput + 1))))))
6753 goto increment_locinput;
6755 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6759 case POSIXD: /* \w or [:punct:] etc. under /d */
6765 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6767 if (NEXTCHR_IS_EOS) {
6771 /* All UTF-8 variants match */
6772 if (! UTF8_IS_INVARIANT(nextchr)) {
6773 goto increment_locinput;
6779 case POSIXA: /* \w or [:punct:] etc. under /a */
6782 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6783 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6784 * character is a single byte */
6786 if (NEXTCHR_IS_EOS) {
6792 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6798 /* Here we are either not in utf8, or we matched a utf8-invariant,
6799 * so the next char is the next byte */
6803 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6807 case POSIXU: /* \w or [:punct:] etc. under /u */
6809 if (NEXTCHR_IS_EOS) {
6813 /* Use _generic_isCC() for characters within Latin1. (Note that
6814 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6815 * wouldn't be invariant) */
6816 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6817 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6824 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6825 if (! (to_complement
6826 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6834 else { /* Handle above Latin-1 code points */
6835 utf8_posix_above_latin1:
6836 classnum = (_char_class_number) FLAGS(scan);
6839 if (! (to_complement
6840 ^ cBOOL(_invlist_contains_cp(
6841 PL_XPosix_ptrs[classnum],
6842 utf8_to_uvchr_buf((U8 *) locinput,
6843 (U8 *) reginfo->strend,
6849 case _CC_ENUM_SPACE:
6850 if (! (to_complement
6851 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6856 case _CC_ENUM_BLANK:
6857 if (! (to_complement
6858 ^ cBOOL(is_HORIZWS_high(locinput))))
6863 case _CC_ENUM_XDIGIT:
6864 if (! (to_complement
6865 ^ cBOOL(is_XDIGIT_high(locinput))))
6870 case _CC_ENUM_VERTSPACE:
6871 if (! (to_complement
6872 ^ cBOOL(is_VERTWS_high(locinput))))
6877 case _CC_ENUM_CNTRL: /* These can't match above Latin1 */
6878 case _CC_ENUM_ASCII:
6879 if (! to_complement) {
6884 locinput += UTF8SKIP(locinput);
6888 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6889 a Unicode extended Grapheme Cluster */
6892 if (! utf8_target) {
6894 /* Match either CR LF or '.', as all the other possibilities
6896 locinput++; /* Match the . or CR */
6897 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6899 && locinput < reginfo->strend
6900 && UCHARAT(locinput) == '\n')
6907 /* Get the gcb type for the current character */
6908 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6909 (U8*) reginfo->strend);
6911 /* Then scan through the input until we get to the first
6912 * character whose type is supposed to be a gcb with the
6913 * current character. (There is always a break at the
6915 locinput += UTF8SKIP(locinput);
6916 while (locinput < reginfo->strend) {
6917 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6918 (U8*) reginfo->strend);
6919 if (isGCB(prev_gcb, cur_gcb,
6920 (U8*) reginfo->strbeg, (U8*) locinput,
6927 locinput += UTF8SKIP(locinput);
6934 case NREFFL: /* /\g{name}/il */
6935 { /* The capture buffer cases. The ones beginning with N for the
6936 named buffers just convert to the equivalent numbered and
6937 pretend they were called as the corresponding numbered buffer
6939 /* don't initialize these in the declaration, it makes C++
6944 const U8 *fold_array;
6947 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6948 folder = foldEQ_locale;
6949 fold_array = PL_fold_locale;
6951 utf8_fold_flags = FOLDEQ_LOCALE;
6954 case NREFFA: /* /\g{name}/iaa */
6955 folder = foldEQ_latin1;
6956 fold_array = PL_fold_latin1;
6958 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6961 case NREFFU: /* /\g{name}/iu */
6962 folder = foldEQ_latin1;
6963 fold_array = PL_fold_latin1;
6965 utf8_fold_flags = 0;
6968 case NREFF: /* /\g{name}/i */
6970 fold_array = PL_fold;
6972 utf8_fold_flags = 0;
6975 case NREF: /* /\g{name}/ */
6979 utf8_fold_flags = 0;
6982 /* For the named back references, find the corresponding buffer
6984 n = reg_check_named_buff_matched(rex,scan);
6989 goto do_nref_ref_common;
6991 case REFFL: /* /\1/il */
6992 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6993 folder = foldEQ_locale;
6994 fold_array = PL_fold_locale;
6995 utf8_fold_flags = FOLDEQ_LOCALE;
6998 case REFFA: /* /\1/iaa */
6999 folder = foldEQ_latin1;
7000 fold_array = PL_fold_latin1;
7001 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7004 case REFFU: /* /\1/iu */
7005 folder = foldEQ_latin1;
7006 fold_array = PL_fold_latin1;
7007 utf8_fold_flags = 0;
7010 case REFF: /* /\1/i */
7012 fold_array = PL_fold;
7013 utf8_fold_flags = 0;
7016 case REF: /* /\1/ */
7019 utf8_fold_flags = 0;
7023 n = ARG(scan); /* which paren pair */
7026 ln = rex->offs[n].start;
7027 endref = rex->offs[n].end;
7028 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7029 if (rex->lastparen < n || ln == -1 || endref == -1)
7030 sayNO; /* Do not match unless seen CLOSEn. */
7034 s = reginfo->strbeg + ln;
7035 if (type != REF /* REF can do byte comparison */
7036 && (utf8_target || type == REFFU || type == REFFL))
7038 char * limit = reginfo->strend;
7040 /* This call case insensitively compares the entire buffer
7041 * at s, with the current input starting at locinput, but
7042 * not going off the end given by reginfo->strend, and
7043 * returns in <limit> upon success, how much of the
7044 * current input was matched */
7045 if (! foldEQ_utf8_flags(s, NULL, endref - ln, utf8_target,
7046 locinput, &limit, 0, utf8_target, utf8_fold_flags))
7054 /* Not utf8: Inline the first character, for speed. */
7055 if (!NEXTCHR_IS_EOS &&
7056 UCHARAT(s) != nextchr &&
7058 UCHARAT(s) != fold_array[nextchr]))
7061 if (locinput + ln > reginfo->strend)
7063 if (ln > 1 && (type == REF
7064 ? memNE(s, locinput, ln)
7065 : ! folder(s, locinput, ln)))
7071 case NOTHING: /* null op; e.g. the 'nothing' following
7072 * the '*' in m{(a+|b)*}' */
7074 case TAIL: /* placeholder while compiling (A|B|C) */
7078 #define ST st->u.eval
7079 #define CUR_EVAL cur_eval->u.eval
7085 regexp_internal *rei;
7086 regnode *startpoint;
7089 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
7090 arg= (U32)ARG(scan);
7091 if (cur_eval && cur_eval->locinput == locinput) {
7092 if ( ++nochange_depth > max_nochange_depth )
7094 "Pattern subroutine nesting without pos change"
7095 " exceeded limit in regex");
7102 startpoint = scan + ARG2L(scan);
7103 EVAL_CLOSE_PAREN_SET( st, arg );
7104 /* Detect infinite recursion
7106 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
7107 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
7108 * So we track the position in the string we are at each time
7109 * we recurse and if we try to enter the same routine twice from
7110 * the same position we throw an error.
7112 if ( rex->recurse_locinput[arg] == locinput ) {
7113 /* FIXME: we should show the regop that is failing as part
7114 * of the error message. */
7115 Perl_croak(aTHX_ "Infinite recursion in regex");
7117 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
7118 rex->recurse_locinput[arg]= locinput;
7121 GET_RE_DEBUG_FLAGS_DECL;
7123 Perl_re_exec_indentf( aTHX_
7124 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
7125 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
7131 /* Save all the positions seen so far. */
7132 ST.cp = regcppush(rex, 0, maxopenparen);
7133 REGCP_SET(ST.lastcp);
7135 /* and then jump to the code we share with EVAL */
7136 goto eval_recurse_doit;
7139 case EVAL: /* /(?{...})B/ /(??{A})B/ and /(?(?{...})X|Y)B/ */
7140 if (cur_eval && cur_eval->locinput==locinput) {
7141 if ( ++nochange_depth > max_nochange_depth )
7142 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
7147 /* execute the code in the {...} */
7151 OP * const oop = PL_op;
7152 COP * const ocurcop = PL_curcop;
7156 /* save *all* paren positions */
7157 regcppush(rex, 0, maxopenparen);
7158 REGCP_SET(ST.lastcp);
7161 caller_cv = find_runcv(NULL);
7165 if (rexi->data->what[n] == 'r') { /* code from an external qr */
7167 (REGEXP*)(rexi->data->data[n])
7169 nop = (OP*)rexi->data->data[n+1];
7171 else if (rexi->data->what[n] == 'l') { /* literal code */
7173 nop = (OP*)rexi->data->data[n];
7174 assert(CvDEPTH(newcv));
7177 /* literal with own CV */
7178 assert(rexi->data->what[n] == 'L');
7179 newcv = rex->qr_anoncv;
7180 nop = (OP*)rexi->data->data[n];
7183 /* Some notes about MULTICALL and the context and save stacks.
7186 * /...(?{ my $x)}...(?{ my $y)}...(?{ my $z)}.../
7187 * since codeblocks don't introduce a new scope (so that
7188 * local() etc accumulate), at the end of a successful
7189 * match there will be a SAVEt_CLEARSV on the savestack
7190 * for each of $x, $y, $z. If the three code blocks above
7191 * happen to have come from different CVs (e.g. via
7192 * embedded qr//s), then we must ensure that during any
7193 * savestack unwinding, PL_comppad always points to the
7194 * right pad at each moment. We achieve this by
7195 * interleaving SAVEt_COMPPAD's on the savestack whenever
7196 * there is a change of pad.
7197 * In theory whenever we call a code block, we should
7198 * push a CXt_SUB context, then pop it on return from
7199 * that code block. This causes a bit of an issue in that
7200 * normally popping a context also clears the savestack
7201 * back to cx->blk_oldsaveix, but here we specifically
7202 * don't want to clear the save stack on exit from the
7204 * Also for efficiency we don't want to keep pushing and
7205 * popping the single SUB context as we backtrack etc.
7206 * So instead, we push a single context the first time
7207 * we need, it, then hang onto it until the end of this
7208 * function. Whenever we encounter a new code block, we
7209 * update the CV etc if that's changed. During the times
7210 * in this function where we're not executing a code
7211 * block, having the SUB context still there is a bit
7212 * naughty - but we hope that no-one notices.
7213 * When the SUB context is initially pushed, we fake up
7214 * cx->blk_oldsaveix to be as if we'd pushed this context
7215 * on first entry to S_regmatch rather than at some random
7216 * point during the regexe execution. That way if we
7217 * croak, popping the context stack will ensure that
7218 * *everything* SAVEd by this function is undone and then
7219 * the context popped, rather than e.g., popping the
7220 * context (and restoring the original PL_comppad) then
7221 * popping more of the savestack and restoring a bad
7225 /* If this is the first EVAL, push a MULTICALL. On
7226 * subsequent calls, if we're executing a different CV, or
7227 * if PL_comppad has got messed up from backtracking
7228 * through SAVECOMPPADs, then refresh the context.
7230 if (newcv != last_pushed_cv || PL_comppad != last_pad)
7232 U8 flags = (CXp_SUB_RE |
7233 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
7235 if (last_pushed_cv) {
7236 CHANGE_MULTICALL_FLAGS(newcv, flags);
7239 PUSH_MULTICALL_FLAGS(newcv, flags);
7241 /* see notes above */
7242 CX_CUR()->blk_oldsaveix = orig_savestack_ix;
7244 last_pushed_cv = newcv;
7247 /* these assignments are just to silence compiler
7249 multicall_cop = NULL;
7251 last_pad = PL_comppad;
7253 /* the initial nextstate you would normally execute
7254 * at the start of an eval (which would cause error
7255 * messages to come from the eval), may be optimised
7256 * away from the execution path in the regex code blocks;
7257 * so manually set PL_curcop to it initially */
7259 OP *o = cUNOPx(nop)->op_first;
7260 assert(o->op_type == OP_NULL);
7261 if (o->op_targ == OP_SCOPE) {
7262 o = cUNOPo->op_first;
7265 assert(o->op_targ == OP_LEAVE);
7266 o = cUNOPo->op_first;
7267 assert(o->op_type == OP_ENTER);
7271 if (o->op_type != OP_STUB) {
7272 assert( o->op_type == OP_NEXTSTATE
7273 || o->op_type == OP_DBSTATE
7274 || (o->op_type == OP_NULL
7275 && ( o->op_targ == OP_NEXTSTATE
7276 || o->op_targ == OP_DBSTATE
7280 PL_curcop = (COP*)o;
7285 DEBUG_STATE_r( Perl_re_printf( aTHX_
7286 " re EVAL PL_op=0x%" UVxf "\n", PTR2UV(nop)) );
7288 rex->offs[0].end = locinput - reginfo->strbeg;
7289 if (reginfo->info_aux_eval->pos_magic)
7290 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
7291 reginfo->sv, reginfo->strbeg,
7292 locinput - reginfo->strbeg);
7295 SV *sv_mrk = get_sv("REGMARK", 1);
7296 sv_setsv(sv_mrk, sv_yes_mark);
7299 /* we don't use MULTICALL here as we want to call the
7300 * first op of the block of interest, rather than the
7301 * first op of the sub. Also, we don't want to free
7302 * the savestack frame */
7303 before = (IV)(SP-PL_stack_base);
7305 CALLRUNOPS(aTHX); /* Scalar context. */
7307 if ((IV)(SP-PL_stack_base) == before)
7308 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
7314 /* before restoring everything, evaluate the returned
7315 * value, so that 'uninit' warnings don't use the wrong
7316 * PL_op or pad. Also need to process any magic vars
7317 * (e.g. $1) *before* parentheses are restored */
7322 if (logical == 0) /* (?{})/ */
7323 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
7324 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
7325 sw = cBOOL(SvTRUE_NN(ret));
7328 else { /* /(??{}) */
7329 /* if its overloaded, let the regex compiler handle
7330 * it; otherwise extract regex, or stringify */
7331 if (SvGMAGICAL(ret))
7332 ret = sv_mortalcopy(ret);
7333 if (!SvAMAGIC(ret)) {
7337 if (SvTYPE(sv) == SVt_REGEXP)
7338 re_sv = (REGEXP*) sv;
7339 else if (SvSMAGICAL(ret)) {
7340 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
7342 re_sv = (REGEXP *) mg->mg_obj;
7345 /* force any undef warnings here */
7346 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
7347 ret = sv_mortalcopy(ret);
7348 (void) SvPV_force_nolen(ret);
7354 /* *** Note that at this point we don't restore
7355 * PL_comppad, (or pop the CxSUB) on the assumption it may
7356 * be used again soon. This is safe as long as nothing
7357 * in the regexp code uses the pad ! */
7359 PL_curcop = ocurcop;
7360 regcp_restore(rex, ST.lastcp, &maxopenparen);
7361 PL_curpm_under = PL_curpm;
7362 PL_curpm = PL_reg_curpm;
7365 PUSH_STATE_GOTO(EVAL_B, next, locinput);
7370 /* only /(??{})/ from now on */
7373 /* extract RE object from returned value; compiling if
7377 re_sv = reg_temp_copy(NULL, re_sv);
7382 if (SvUTF8(ret) && IN_BYTES) {
7383 /* In use 'bytes': make a copy of the octet
7384 * sequence, but without the flag on */
7386 const char *const p = SvPV(ret, len);
7387 ret = newSVpvn_flags(p, len, SVs_TEMP);
7389 if (rex->intflags & PREGf_USE_RE_EVAL)
7390 pm_flags |= PMf_USE_RE_EVAL;
7392 /* if we got here, it should be an engine which
7393 * supports compiling code blocks and stuff */
7394 assert(rex->engine && rex->engine->op_comp);
7395 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
7396 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
7397 rex->engine, NULL, NULL,
7398 /* copy /msixn etc to inner pattern */
7403 & (SVs_TEMP | SVs_GMG | SVf_ROK))
7404 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
7405 /* This isn't a first class regexp. Instead, it's
7406 caching a regexp onto an existing, Perl visible
7408 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
7414 RXp_MATCH_COPIED_off(re);
7415 re->subbeg = rex->subbeg;
7416 re->sublen = rex->sublen;
7417 re->suboffset = rex->suboffset;
7418 re->subcoffset = rex->subcoffset;
7420 re->lastcloseparen = 0;
7423 debug_start_match(re_sv, utf8_target, locinput,
7424 reginfo->strend, "EVAL/GOSUB: Matching embedded");
7426 startpoint = rei->program + 1;
7427 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7428 * close_paren only for GOSUB */
7429 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7430 /* Save all the seen positions so far. */
7431 ST.cp = regcppush(rex, 0, maxopenparen);
7432 REGCP_SET(ST.lastcp);
7433 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7435 /* run the pattern returned from (??{...}) */
7437 eval_recurse_doit: /* Share code with GOSUB below this line
7438 * At this point we expect the stack context to be
7439 * set up correctly */
7441 /* invalidate the S-L poscache. We're now executing a
7442 * different set of WHILEM ops (and their associated
7443 * indexes) against the same string, so the bits in the
7444 * cache are meaningless. Setting maxiter to zero forces
7445 * the cache to be invalidated and zeroed before reuse.
7446 * XXX This is too dramatic a measure. Ideally we should
7447 * save the old cache and restore when running the outer
7449 reginfo->poscache_maxiter = 0;
7451 /* the new regexp might have a different is_utf8_pat than we do */
7452 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7454 ST.prev_rex = rex_sv;
7455 ST.prev_curlyx = cur_curlyx;
7457 SET_reg_curpm(rex_sv);
7462 ST.prev_eval = cur_eval;
7464 /* now continue from first node in postoned RE */
7465 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, startpoint, locinput);
7466 NOT_REACHED; /* NOTREACHED */
7469 case EVAL_postponed_AB: /* cleanup after a successful (??{A})B */
7470 /* note: this is called twice; first after popping B, then A */
7472 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7473 depth, cur_eval, ST.prev_eval);
7476 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7477 if ( cur_eval && CUR_EVAL.close_paren ) {\
7479 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7481 CUR_EVAL.close_paren - 1,\
7485 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7488 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7490 rex_sv = ST.prev_rex;
7491 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7492 SET_reg_curpm(rex_sv);
7493 rex = ReANY(rex_sv);
7494 rexi = RXi_GET(rex);
7496 /* preserve $^R across LEAVE's. See Bug 121070. */
7497 SV *save_sv= GvSV(PL_replgv);
7498 SvREFCNT_inc(save_sv);
7499 regcpblow(ST.cp); /* LEAVE in disguise */
7500 sv_setsv(GvSV(PL_replgv), save_sv);
7501 SvREFCNT_dec(save_sv);
7503 cur_eval = ST.prev_eval;
7504 cur_curlyx = ST.prev_curlyx;
7506 /* Invalidate cache. See "invalidate" comment above. */
7507 reginfo->poscache_maxiter = 0;
7508 if ( nochange_depth )
7511 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7515 case EVAL_B_fail: /* unsuccessful B in (?{...})B */
7516 REGCP_UNWIND(ST.lastcp);
7519 case EVAL_postponed_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7520 /* note: this is called twice; first after popping B, then A */
7522 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7523 depth, cur_eval, ST.prev_eval);
7526 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7528 rex_sv = ST.prev_rex;
7529 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7530 SET_reg_curpm(rex_sv);
7531 rex = ReANY(rex_sv);
7532 rexi = RXi_GET(rex);
7534 REGCP_UNWIND(ST.lastcp);
7535 regcppop(rex, &maxopenparen);
7536 cur_eval = ST.prev_eval;
7537 cur_curlyx = ST.prev_curlyx;
7539 /* Invalidate cache. See "invalidate" comment above. */
7540 reginfo->poscache_maxiter = 0;
7541 if ( nochange_depth )
7544 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7549 n = ARG(scan); /* which paren pair */
7550 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7551 if (n > maxopenparen)
7553 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
7554 "OPEN: rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf " tmp; maxopenparen=%" UVuf "\n",
7559 (IV)rex->offs[n].start_tmp,
7565 case SROPEN: /* (*SCRIPT_RUN: */
7566 script_run_begin = (U8 *) locinput;
7569 /* XXX really need to log other places start/end are set too */
7570 #define CLOSE_CAPTURE \
7571 rex->offs[n].start = rex->offs[n].start_tmp; \
7572 rex->offs[n].end = locinput - reginfo->strbeg; \
7573 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
7574 "CLOSE: rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf "\n", \
7577 PTR2UV(rex->offs), \
7579 (IV)rex->offs[n].start, \
7580 (IV)rex->offs[n].end \
7584 n = ARG(scan); /* which paren pair */
7586 if (n > rex->lastparen)
7588 rex->lastcloseparen = n;
7589 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7594 case SRCLOSE: /* (*SCRIPT_RUN: ... ) */
7596 if (! isSCRIPT_RUN(script_run_begin, (U8 *) locinput, utf8_target))
7604 case ACCEPT: /* (*ACCEPT) */
7606 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7610 cursor && OP(cursor)!=END;
7611 cursor=regnext(cursor))
7613 if ( OP(cursor)==CLOSE ){
7615 if ( n <= lastopen ) {
7617 if (n > rex->lastparen)
7619 rex->lastcloseparen = n;
7620 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7629 case GROUPP: /* (?(1)) */
7630 n = ARG(scan); /* which paren pair */
7631 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7634 case NGROUPP: /* (?(<name>)) */
7635 /* reg_check_named_buff_matched returns 0 for no match */
7636 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7639 case INSUBP: /* (?(R)) */
7641 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7642 * of SCAN is already set up as matches a eval.close_paren */
7643 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7646 case DEFINEP: /* (?(DEFINE)) */
7650 case IFTHEN: /* (?(cond)A|B) */
7651 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7653 next = NEXTOPER(NEXTOPER(scan));
7655 next = scan + ARG(scan);
7656 if (OP(next) == IFTHEN) /* Fake one. */
7657 next = NEXTOPER(NEXTOPER(next));
7661 case LOGICAL: /* modifier for EVAL and IFMATCH */
7662 logical = scan->flags;
7665 /*******************************************************************
7667 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7668 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7669 STAR/PLUS/CURLY/CURLYN are used instead.)
7671 A*B is compiled as <CURLYX><A><WHILEM><B>
7673 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7674 state, which contains the current count, initialised to -1. It also sets
7675 cur_curlyx to point to this state, with any previous value saved in the
7678 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7679 since the pattern may possibly match zero times (i.e. it's a while {} loop
7680 rather than a do {} while loop).
7682 Each entry to WHILEM represents a successful match of A. The count in the
7683 CURLYX block is incremented, another WHILEM state is pushed, and execution
7684 passes to A or B depending on greediness and the current count.
7686 For example, if matching against the string a1a2a3b (where the aN are
7687 substrings that match /A/), then the match progresses as follows: (the
7688 pushed states are interspersed with the bits of strings matched so far):
7691 <CURLYX cnt=0><WHILEM>
7692 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7693 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7694 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7695 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7697 (Contrast this with something like CURLYM, which maintains only a single
7701 a1 <CURLYM cnt=1> a2
7702 a1 a2 <CURLYM cnt=2> a3
7703 a1 a2 a3 <CURLYM cnt=3> b
7706 Each WHILEM state block marks a point to backtrack to upon partial failure
7707 of A or B, and also contains some minor state data related to that
7708 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7709 overall state, such as the count, and pointers to the A and B ops.
7711 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7712 must always point to the *current* CURLYX block, the rules are:
7714 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7715 and set cur_curlyx to point the new block.
7717 When popping the CURLYX block after a successful or unsuccessful match,
7718 restore the previous cur_curlyx.
7720 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7721 to the outer one saved in the CURLYX block.
7723 When popping the WHILEM block after a successful or unsuccessful B match,
7724 restore the previous cur_curlyx.
7726 Here's an example for the pattern (AI* BI)*BO
7727 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7730 curlyx backtrack stack
7731 ------ ---------------
7733 CO <CO prev=NULL> <WO>
7734 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7735 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7736 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7738 At this point the pattern succeeds, and we work back down the stack to
7739 clean up, restoring as we go:
7741 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7742 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7743 CO <CO prev=NULL> <WO>
7746 *******************************************************************/
7748 #define ST st->u.curlyx
7750 case CURLYX: /* start of /A*B/ (for complex A) */
7752 /* No need to save/restore up to this paren */
7753 I32 parenfloor = scan->flags;
7755 assert(next); /* keep Coverity happy */
7756 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7759 /* XXXX Probably it is better to teach regpush to support
7760 parenfloor > maxopenparen ... */
7761 if (parenfloor > (I32)rex->lastparen)
7762 parenfloor = rex->lastparen; /* Pessimization... */
7764 ST.prev_curlyx= cur_curlyx;
7766 ST.cp = PL_savestack_ix;
7768 /* these fields contain the state of the current curly.
7769 * they are accessed by subsequent WHILEMs */
7770 ST.parenfloor = parenfloor;
7775 ST.count = -1; /* this will be updated by WHILEM */
7776 ST.lastloc = NULL; /* this will be updated by WHILEM */
7778 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7779 NOT_REACHED; /* NOTREACHED */
7782 case CURLYX_end: /* just finished matching all of A*B */
7783 cur_curlyx = ST.prev_curlyx;
7785 NOT_REACHED; /* NOTREACHED */
7787 case CURLYX_end_fail: /* just failed to match all of A*B */
7789 cur_curlyx = ST.prev_curlyx;
7791 NOT_REACHED; /* NOTREACHED */
7795 #define ST st->u.whilem
7797 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7799 /* see the discussion above about CURLYX/WHILEM */
7804 assert(cur_curlyx); /* keep Coverity happy */
7806 min = ARG1(cur_curlyx->u.curlyx.me);
7807 max = ARG2(cur_curlyx->u.curlyx.me);
7808 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7809 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7810 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7811 ST.cache_offset = 0;
7815 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "WHILEM: matched %ld out of %d..%d\n",
7816 depth, (long)n, min, max)
7819 /* First just match a string of min A's. */
7822 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor, maxopenparen);
7823 cur_curlyx->u.curlyx.lastloc = locinput;
7824 REGCP_SET(ST.lastcp);
7826 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7827 NOT_REACHED; /* NOTREACHED */
7830 /* If degenerate A matches "", assume A done. */
7832 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7833 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "WHILEM: empty match detected, trying continuation...\n",
7836 goto do_whilem_B_max;
7839 /* super-linear cache processing.
7841 * The idea here is that for certain types of CURLYX/WHILEM -
7842 * principally those whose upper bound is infinity (and
7843 * excluding regexes that have things like \1 and other very
7844 * non-regular expresssiony things), then if a pattern like
7845 * /....A*.../ fails and we backtrack to the WHILEM, then we
7846 * make a note that this particular WHILEM op was at string
7847 * position 47 (say) when the rest of pattern failed. Then, if
7848 * we ever find ourselves back at that WHILEM, and at string
7849 * position 47 again, we can just fail immediately rather than
7850 * running the rest of the pattern again.
7852 * This is very handy when patterns start to go
7853 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7854 * with a combinatorial explosion of backtracking.
7856 * The cache is implemented as a bit array, with one bit per
7857 * string byte position per WHILEM op (up to 16) - so its
7858 * between 0.25 and 2x the string size.
7860 * To avoid allocating a poscache buffer every time, we do an
7861 * initially countdown; only after we have executed a WHILEM
7862 * op (string-length x #WHILEMs) times do we allocate the
7865 * The top 4 bits of scan->flags byte say how many different
7866 * relevant CURLLYX/WHILEM op pairs there are, while the
7867 * bottom 4-bits is the identifying index number of this
7873 if (!reginfo->poscache_maxiter) {
7874 /* start the countdown: Postpone detection until we
7875 * know the match is not *that* much linear. */
7876 reginfo->poscache_maxiter
7877 = (reginfo->strend - reginfo->strbeg + 1)
7879 /* possible overflow for long strings and many CURLYX's */
7880 if (reginfo->poscache_maxiter < 0)
7881 reginfo->poscache_maxiter = I32_MAX;
7882 reginfo->poscache_iter = reginfo->poscache_maxiter;
7885 if (reginfo->poscache_iter-- == 0) {
7886 /* initialise cache */
7887 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7888 regmatch_info_aux *const aux = reginfo->info_aux;
7889 if (aux->poscache) {
7890 if ((SSize_t)reginfo->poscache_size < size) {
7891 Renew(aux->poscache, size, char);
7892 reginfo->poscache_size = size;
7894 Zero(aux->poscache, size, char);
7897 reginfo->poscache_size = size;
7898 Newxz(aux->poscache, size, char);
7900 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7901 "%sWHILEM: Detected a super-linear match, switching on caching%s...\n",
7902 PL_colors[4], PL_colors[5])
7906 if (reginfo->poscache_iter < 0) {
7907 /* have we already failed at this position? */
7908 SSize_t offset, mask;
7910 reginfo->poscache_iter = -1; /* stop eventual underflow */
7911 offset = (scan->flags & 0xf) - 1
7912 + (locinput - reginfo->strbeg)
7914 mask = 1 << (offset % 8);
7916 if (reginfo->info_aux->poscache[offset] & mask) {
7917 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "WHILEM: (cache) already tried at this position...\n",
7920 cur_curlyx->u.curlyx.count--;
7921 sayNO; /* cache records failure */
7923 ST.cache_offset = offset;
7924 ST.cache_mask = mask;
7928 /* Prefer B over A for minimal matching. */
7930 if (cur_curlyx->u.curlyx.minmod) {
7931 ST.save_curlyx = cur_curlyx;
7932 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7933 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7935 NOT_REACHED; /* NOTREACHED */
7938 /* Prefer A over B for maximal matching. */
7940 if (n < max) { /* More greed allowed? */
7941 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7943 cur_curlyx->u.curlyx.lastloc = locinput;
7944 REGCP_SET(ST.lastcp);
7945 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7946 NOT_REACHED; /* NOTREACHED */
7948 goto do_whilem_B_max;
7950 NOT_REACHED; /* NOTREACHED */
7952 case WHILEM_B_min: /* just matched B in a minimal match */
7953 case WHILEM_B_max: /* just matched B in a maximal match */
7954 cur_curlyx = ST.save_curlyx;
7956 NOT_REACHED; /* NOTREACHED */
7958 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7959 cur_curlyx = ST.save_curlyx;
7960 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7961 cur_curlyx->u.curlyx.count--;
7963 NOT_REACHED; /* NOTREACHED */
7965 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7967 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7968 REGCP_UNWIND(ST.lastcp);
7969 regcppop(rex, &maxopenparen);
7970 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7971 cur_curlyx->u.curlyx.count--;
7973 NOT_REACHED; /* NOTREACHED */
7975 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7976 REGCP_UNWIND(ST.lastcp);
7977 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7978 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "WHILEM: failed, trying continuation...\n",
7982 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7983 && ckWARN(WARN_REGEXP)
7984 && !reginfo->warned)
7986 reginfo->warned = TRUE;
7987 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7988 "Complex regular subexpression recursion limit (%d) "
7994 ST.save_curlyx = cur_curlyx;
7995 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7996 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7998 NOT_REACHED; /* NOTREACHED */
8000 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
8001 cur_curlyx = ST.save_curlyx;
8003 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
8004 /* Maximum greed exceeded */
8005 if (cur_curlyx->u.curlyx.count >= REG_INFTY
8006 && ckWARN(WARN_REGEXP)
8007 && !reginfo->warned)
8009 reginfo->warned = TRUE;
8010 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
8011 "Complex regular subexpression recursion "
8012 "limit (%d) exceeded",
8015 cur_curlyx->u.curlyx.count--;
8019 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "WHILEM: B min fail: trying longer...\n", depth)
8021 /* Try grabbing another A and see if it helps. */
8022 cur_curlyx->u.curlyx.lastloc = locinput;
8023 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
8025 REGCP_SET(ST.lastcp);
8026 PUSH_STATE_GOTO(WHILEM_A_min,
8027 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
8029 NOT_REACHED; /* NOTREACHED */
8032 #define ST st->u.branch
8034 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
8035 next = scan + ARG(scan);
8038 scan = NEXTOPER(scan);
8041 case BRANCH: /* /(...|A|...)/ */
8042 scan = NEXTOPER(scan); /* scan now points to inner node */
8043 ST.lastparen = rex->lastparen;
8044 ST.lastcloseparen = rex->lastcloseparen;
8045 ST.next_branch = next;
8048 /* Now go into the branch */
8050 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
8052 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
8054 NOT_REACHED; /* NOTREACHED */
8056 case CUTGROUP: /* /(*THEN)/ */
8057 sv_yes_mark = st->u.mark.mark_name = scan->flags
8058 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
8060 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
8061 NOT_REACHED; /* NOTREACHED */
8063 case CUTGROUP_next_fail:
8066 if (st->u.mark.mark_name)
8067 sv_commit = st->u.mark.mark_name;
8069 NOT_REACHED; /* NOTREACHED */
8073 NOT_REACHED; /* NOTREACHED */
8075 case BRANCH_next_fail: /* that branch failed; try the next, if any */
8080 REGCP_UNWIND(ST.cp);
8081 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8082 scan = ST.next_branch;
8083 /* no more branches? */
8084 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
8086 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
8093 continue; /* execute next BRANCH[J] op */
8096 case MINMOD: /* next op will be non-greedy, e.g. A*? */
8101 #define ST st->u.curlym
8103 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
8105 /* This is an optimisation of CURLYX that enables us to push
8106 * only a single backtracking state, no matter how many matches
8107 * there are in {m,n}. It relies on the pattern being constant
8108 * length, with no parens to influence future backrefs
8112 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
8114 ST.lastparen = rex->lastparen;
8115 ST.lastcloseparen = rex->lastcloseparen;
8117 /* if paren positive, emulate an OPEN/CLOSE around A */
8119 U32 paren = ST.me->flags;
8120 if (paren > maxopenparen)
8121 maxopenparen = paren;
8122 scan += NEXT_OFF(scan); /* Skip former OPEN. */
8130 ST.c1 = CHRTEST_UNINIT;
8133 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
8136 curlym_do_A: /* execute the A in /A{m,n}B/ */
8137 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
8138 NOT_REACHED; /* NOTREACHED */
8140 case CURLYM_A: /* we've just matched an A */
8142 /* after first match, determine A's length: u.curlym.alen */
8143 if (ST.count == 1) {
8144 if (reginfo->is_utf8_target) {
8145 char *s = st->locinput;
8146 while (s < locinput) {
8152 ST.alen = locinput - st->locinput;
8155 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
8158 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %" IVdf " times, len=%" IVdf "...\n",
8159 depth, (IV) ST.count, (IV)ST.alen)
8162 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8166 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
8167 if ( max == REG_INFTY || ST.count < max )
8168 goto curlym_do_A; /* try to match another A */
8170 goto curlym_do_B; /* try to match B */
8172 case CURLYM_A_fail: /* just failed to match an A */
8173 REGCP_UNWIND(ST.cp);
8176 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
8177 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8180 curlym_do_B: /* execute the B in /A{m,n}B/ */
8181 if (ST.c1 == CHRTEST_UNINIT) {
8182 /* calculate c1 and c2 for possible match of 1st char
8183 * following curly */
8184 ST.c1 = ST.c2 = CHRTEST_VOID;
8186 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
8187 regnode *text_node = ST.B;
8188 if (! HAS_TEXT(text_node))
8189 FIND_NEXT_IMPT(text_node);
8192 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
8194 But the former is redundant in light of the latter.
8196 if this changes back then the macro for
8197 IS_TEXT and friends need to change.
8199 if (PL_regkind[OP(text_node)] == EXACT) {
8200 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8201 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8211 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%" IVdf "...\n",
8212 depth, (IV)ST.count)
8214 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
8215 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
8216 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8217 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8219 /* simulate B failing */
8221 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%" UVXf " c1=0x%" UVXf " c2=0x%" UVXf "\n",
8223 valid_utf8_to_uvchr((U8 *) locinput, NULL),
8224 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
8225 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
8227 state_num = CURLYM_B_fail;
8228 goto reenter_switch;
8231 else if (nextchr != ST.c1 && nextchr != ST.c2) {
8232 /* simulate B failing */
8234 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
8236 (int) nextchr, ST.c1, ST.c2)
8238 state_num = CURLYM_B_fail;
8239 goto reenter_switch;
8244 /* emulate CLOSE: mark current A as captured */
8245 I32 paren = ST.me->flags;
8247 rex->offs[paren].start
8248 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
8249 rex->offs[paren].end = locinput - reginfo->strbeg;
8250 if ((U32)paren > rex->lastparen)
8251 rex->lastparen = paren;
8252 rex->lastcloseparen = paren;
8255 rex->offs[paren].end = -1;
8257 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8266 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
8267 NOT_REACHED; /* NOTREACHED */
8269 case CURLYM_B_fail: /* just failed to match a B */
8270 REGCP_UNWIND(ST.cp);
8271 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8273 I32 max = ARG2(ST.me);
8274 if (max != REG_INFTY && ST.count == max)
8276 goto curlym_do_A; /* try to match a further A */
8278 /* backtrack one A */
8279 if (ST.count == ARG1(ST.me) /* min */)
8282 SET_locinput(HOPc(locinput, -ST.alen));
8283 goto curlym_do_B; /* try to match B */
8286 #define ST st->u.curly
8288 #define CURLY_SETPAREN(paren, success) \
8291 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
8292 rex->offs[paren].end = locinput - reginfo->strbeg; \
8293 if (paren > rex->lastparen) \
8294 rex->lastparen = paren; \
8295 rex->lastcloseparen = paren; \
8298 rex->offs[paren].end = -1; \
8299 rex->lastparen = ST.lastparen; \
8300 rex->lastcloseparen = ST.lastcloseparen; \
8304 case STAR: /* /A*B/ where A is width 1 char */
8308 scan = NEXTOPER(scan);
8311 case PLUS: /* /A+B/ where A is width 1 char */
8315 scan = NEXTOPER(scan);
8318 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
8319 ST.paren = scan->flags; /* Which paren to set */
8320 ST.lastparen = rex->lastparen;
8321 ST.lastcloseparen = rex->lastcloseparen;
8322 if (ST.paren > maxopenparen)
8323 maxopenparen = ST.paren;
8324 ST.min = ARG1(scan); /* min to match */
8325 ST.max = ARG2(scan); /* max to match */
8326 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8331 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
8334 case CURLY: /* /A{m,n}B/ where A is width 1 char */
8336 ST.min = ARG1(scan); /* min to match */
8337 ST.max = ARG2(scan); /* max to match */
8338 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
8341 * Lookahead to avoid useless match attempts
8342 * when we know what character comes next.
8344 * Used to only do .*x and .*?x, but now it allows
8345 * for )'s, ('s and (?{ ... })'s to be in the way
8346 * of the quantifier and the EXACT-like node. -- japhy
8349 assert(ST.min <= ST.max);
8350 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
8351 ST.c1 = ST.c2 = CHRTEST_VOID;
8354 regnode *text_node = next;
8356 if (! HAS_TEXT(text_node))
8357 FIND_NEXT_IMPT(text_node);
8359 if (! HAS_TEXT(text_node))
8360 ST.c1 = ST.c2 = CHRTEST_VOID;
8362 if ( PL_regkind[OP(text_node)] != EXACT ) {
8363 ST.c1 = ST.c2 = CHRTEST_VOID;
8367 /* Currently we only get here when
8369 PL_rekind[OP(text_node)] == EXACT
8371 if this changes back then the macro for IS_TEXT and
8372 friends need to change. */
8373 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8374 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8386 char *li = locinput;
8389 regrepeat(rex, &li, ST.A, reginfo, ST.min)
8395 if (ST.c1 == CHRTEST_VOID)
8396 goto curly_try_B_min;
8398 ST.oldloc = locinput;
8400 /* set ST.maxpos to the furthest point along the
8401 * string that could possibly match */
8402 if (ST.max == REG_INFTY) {
8403 ST.maxpos = reginfo->strend - 1;
8405 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
8408 else if (utf8_target) {
8409 int m = ST.max - ST.min;
8410 for (ST.maxpos = locinput;
8411 m >0 && ST.maxpos < reginfo->strend; m--)
8412 ST.maxpos += UTF8SKIP(ST.maxpos);
8415 ST.maxpos = locinput + ST.max - ST.min;
8416 if (ST.maxpos >= reginfo->strend)
8417 ST.maxpos = reginfo->strend - 1;
8419 goto curly_try_B_min_known;
8423 /* avoid taking address of locinput, so it can remain
8425 char *li = locinput;
8426 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max);
8427 if (ST.count < ST.min)
8430 if ((ST.count > ST.min)
8431 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
8433 /* A{m,n} must come at the end of the string, there's
8434 * no point in backing off ... */
8436 /* ...except that $ and \Z can match before *and* after
8437 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8438 We may back off by one in this case. */
8439 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8443 goto curly_try_B_max;
8445 NOT_REACHED; /* NOTREACHED */
8447 case CURLY_B_min_known_fail:
8448 /* failed to find B in a non-greedy match where c1,c2 valid */
8450 REGCP_UNWIND(ST.cp);
8452 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8454 /* Couldn't or didn't -- move forward. */
8455 ST.oldloc = locinput;
8457 locinput += UTF8SKIP(locinput);
8461 curly_try_B_min_known:
8462 /* find the next place where 'B' could work, then call B */
8466 n = (ST.oldloc == locinput) ? 0 : 1;
8467 if (ST.c1 == ST.c2) {
8468 /* set n to utf8_distance(oldloc, locinput) */
8469 while (locinput <= ST.maxpos
8470 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8472 locinput += UTF8SKIP(locinput);
8477 /* set n to utf8_distance(oldloc, locinput) */
8478 while (locinput <= ST.maxpos
8479 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8480 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8482 locinput += UTF8SKIP(locinput);
8487 else { /* Not utf8_target */
8488 if (ST.c1 == ST.c2) {
8489 locinput = (char *) memchr(locinput,
8491 ST.maxpos + 1 - locinput);
8493 locinput = ST.maxpos + 1;
8497 U8 c1_c2_bits_differing = ST.c1 ^ ST.c2;
8499 if (! isPOWER_OF_2(c1_c2_bits_differing)) {
8500 while ( locinput <= ST.maxpos
8501 && UCHARAT(locinput) != ST.c1
8502 && UCHARAT(locinput) != ST.c2)
8508 /* If c1 and c2 only differ by a single bit, we can
8509 * avoid a conditional each time through the loop,
8510 * at the expense of a little preliminary setup and
8511 * an extra mask each iteration. By masking out
8512 * that bit, we match exactly two characters, c1
8513 * and c2, and so we don't have to test for both.
8514 * On both ASCII and EBCDIC platforms, most of the
8515 * ASCII-range and Latin1-range folded equivalents
8516 * differ only in a single bit, so this is actually
8517 * the most common case. (e.g. 'A' 0x41 vs 'a'
8519 U8 c1_masked = ST.c1 &~ c1_c2_bits_differing;
8520 U8 c1_c2_mask = ~ c1_c2_bits_differing;
8521 while ( locinput <= ST.maxpos
8522 && (UCHARAT(locinput) & c1_c2_mask)
8529 n = locinput - ST.oldloc;
8531 if (locinput > ST.maxpos)
8534 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8535 * at b; check that everything between oldloc and
8536 * locinput matches */
8537 char *li = ST.oldloc;
8539 if (regrepeat(rex, &li, ST.A, reginfo, n) < n)
8541 assert(n == REG_INFTY || locinput == li);
8543 CURLY_SETPAREN(ST.paren, ST.count);
8544 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8546 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8548 NOT_REACHED; /* NOTREACHED */
8550 case CURLY_B_min_fail:
8551 /* failed to find B in a non-greedy match where c1,c2 invalid */
8553 REGCP_UNWIND(ST.cp);
8555 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8557 /* failed -- move forward one */
8559 char *li = locinput;
8560 if (!regrepeat(rex, &li, ST.A, reginfo, 1)) {
8567 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8568 ST.count > 0)) /* count overflow ? */
8571 CURLY_SETPAREN(ST.paren, ST.count);
8572 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8574 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8578 NOT_REACHED; /* NOTREACHED */
8581 /* a successful greedy match: now try to match B */
8582 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8585 bool could_match = locinput < reginfo->strend;
8587 /* If it could work, try it. */
8588 if (ST.c1 != CHRTEST_VOID && could_match) {
8589 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8591 could_match = memEQ(locinput,
8596 UTF8SKIP(locinput));
8599 could_match = UCHARAT(locinput) == ST.c1
8600 || UCHARAT(locinput) == ST.c2;
8603 if (ST.c1 == CHRTEST_VOID || could_match) {
8604 CURLY_SETPAREN(ST.paren, ST.count);
8605 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8606 NOT_REACHED; /* NOTREACHED */
8611 case CURLY_B_max_fail:
8612 /* failed to find B in a greedy match */
8614 REGCP_UNWIND(ST.cp);
8616 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8619 if (--ST.count < ST.min)
8621 locinput = HOPc(locinput, -1);
8622 goto curly_try_B_max;
8626 case END: /* last op of main pattern */
8629 /* we've just finished A in /(??{A})B/; now continue with B */
8630 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8631 st->u.eval.prev_rex = rex_sv; /* inner */
8633 /* Save *all* the positions. */
8634 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8635 rex_sv = CUR_EVAL.prev_rex;
8636 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8637 SET_reg_curpm(rex_sv);
8638 rex = ReANY(rex_sv);
8639 rexi = RXi_GET(rex);
8641 st->u.eval.prev_curlyx = cur_curlyx;
8642 cur_curlyx = CUR_EVAL.prev_curlyx;
8644 REGCP_SET(st->u.eval.lastcp);
8646 /* Restore parens of the outer rex without popping the
8648 regcp_restore(rex, CUR_EVAL.lastcp, &maxopenparen);
8650 st->u.eval.prev_eval = cur_eval;
8651 cur_eval = CUR_EVAL.prev_eval;
8653 Perl_re_exec_indentf( aTHX_ "END: EVAL trying tail ... (cur_eval=%p)\n",
8655 if ( nochange_depth )
8658 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8660 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, st->u.eval.prev_eval->u.eval.B,
8661 locinput); /* match B */
8664 if (locinput < reginfo->till) {
8665 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8666 "%sEND: Match possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8668 (long)(locinput - startpos),
8669 (long)(reginfo->till - startpos),
8672 sayNO_SILENT; /* Cannot match: too short. */
8674 sayYES; /* Success! */
8676 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8678 Perl_re_exec_indentf( aTHX_ "%sSUCCEED: subpattern success...%s\n",
8679 depth, PL_colors[4], PL_colors[5]));
8680 sayYES; /* Success! */
8683 #define ST st->u.ifmatch
8688 case SUSPEND: /* (?>A) */
8690 newstart = locinput;
8693 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8695 goto ifmatch_trivial_fail_test;
8697 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8699 ifmatch_trivial_fail_test:
8701 char * const s = HOPBACKc(locinput, scan->flags);
8706 sw = 1 - cBOOL(ST.wanted);
8710 next = scan + ARG(scan);
8718 newstart = locinput;
8722 ST.logical = logical;
8723 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8725 /* execute body of (?...A) */
8726 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8727 NOT_REACHED; /* NOTREACHED */
8730 case IFMATCH_A_fail: /* body of (?...A) failed */
8731 ST.wanted = !ST.wanted;
8734 case IFMATCH_A: /* body of (?...A) succeeded */
8736 sw = cBOOL(ST.wanted);
8738 else if (!ST.wanted)
8741 if (OP(ST.me) != SUSPEND) {
8742 /* restore old position except for (?>...) */
8743 locinput = st->locinput;
8745 scan = ST.me + ARG(ST.me);
8748 continue; /* execute B */
8752 case LONGJMP: /* alternative with many branches compiles to
8753 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8754 next = scan + ARG(scan);
8759 case COMMIT: /* (*COMMIT) */
8760 reginfo->cutpoint = reginfo->strend;
8763 case PRUNE: /* (*PRUNE) */
8765 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8766 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8767 NOT_REACHED; /* NOTREACHED */
8769 case COMMIT_next_fail:
8773 NOT_REACHED; /* NOTREACHED */
8775 case OPFAIL: /* (*FAIL) */
8777 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8779 /* deal with (?(?!)X|Y) properly,
8780 * make sure we trigger the no branch
8781 * of the trailing IFTHEN structure*/
8787 NOT_REACHED; /* NOTREACHED */
8789 #define ST st->u.mark
8790 case MARKPOINT: /* (*MARK:foo) */
8791 ST.prev_mark = mark_state;
8792 ST.mark_name = sv_commit = sv_yes_mark
8793 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8795 ST.mark_loc = locinput;
8796 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8797 NOT_REACHED; /* NOTREACHED */
8799 case MARKPOINT_next:
8800 mark_state = ST.prev_mark;
8802 NOT_REACHED; /* NOTREACHED */
8804 case MARKPOINT_next_fail:
8805 if (popmark && sv_eq(ST.mark_name,popmark))
8807 if (ST.mark_loc > startpoint)
8808 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8809 popmark = NULL; /* we found our mark */
8810 sv_commit = ST.mark_name;
8813 Perl_re_exec_indentf( aTHX_ "%sMARKPOINT: next fail: setting cutpoint to mark:%" SVf "...%s\n",
8815 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8818 mark_state = ST.prev_mark;
8819 sv_yes_mark = mark_state ?
8820 mark_state->u.mark.mark_name : NULL;
8822 NOT_REACHED; /* NOTREACHED */
8824 case SKIP: /* (*SKIP) */
8826 /* (*SKIP) : if we fail we cut here*/
8827 ST.mark_name = NULL;
8828 ST.mark_loc = locinput;
8829 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8831 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8832 otherwise do nothing. Meaning we need to scan
8834 regmatch_state *cur = mark_state;
8835 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8838 if ( sv_eq( cur->u.mark.mark_name,
8841 ST.mark_name = find;
8842 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8844 cur = cur->u.mark.prev_mark;
8847 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8850 case SKIP_next_fail:
8852 /* (*CUT:NAME) - Set up to search for the name as we
8853 collapse the stack*/
8854 popmark = ST.mark_name;
8856 /* (*CUT) - No name, we cut here.*/
8857 if (ST.mark_loc > startpoint)
8858 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8859 /* but we set sv_commit to latest mark_name if there
8860 is one so they can test to see how things lead to this
8863 sv_commit=mark_state->u.mark.mark_name;
8867 NOT_REACHED; /* NOTREACHED */
8870 case LNBREAK: /* \R */
8871 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8878 PerlIO_printf(Perl_error_log, "%" UVxf " %d\n",
8879 PTR2UV(scan), OP(scan));
8880 Perl_croak(aTHX_ "regexp memory corruption");
8882 /* this is a point to jump to in order to increment
8883 * locinput by one character */
8885 assert(!NEXTCHR_IS_EOS);
8887 locinput += PL_utf8skip[nextchr];
8888 /* locinput is allowed to go 1 char off the end (signifying
8889 * EOS), but not 2+ */
8890 if (locinput > reginfo->strend)
8899 /* switch break jumps here */
8900 scan = next; /* prepare to execute the next op and ... */
8901 continue; /* ... jump back to the top, reusing st */
8905 /* push a state that backtracks on success */
8906 st->u.yes.prev_yes_state = yes_state;
8910 /* push a new regex state, then continue at scan */
8912 regmatch_state *newst;
8915 regmatch_state *cur = st;
8916 regmatch_state *curyes = yes_state;
8918 regmatch_slab *slab = PL_regmatch_slab;
8919 for (i = 0; i < 3 && i <= depth; cur--,i++) {
8920 if (cur < SLAB_FIRST(slab)) {
8922 cur = SLAB_LAST(slab);
8924 Perl_re_exec_indentf( aTHX_ "%4s #%-3d %-10s %s\n",
8927 depth - i, PL_reg_name[cur->resume_state],
8928 (curyes == cur) ? "yes" : ""
8931 curyes = cur->u.yes.prev_yes_state;
8934 DEBUG_STATE_pp("push")
8937 st->locinput = locinput;
8939 if (newst > SLAB_LAST(PL_regmatch_slab))
8940 newst = S_push_slab(aTHX);
8941 PL_regmatch_state = newst;
8943 locinput = pushinput;
8949 #ifdef SOLARIS_BAD_OPTIMIZER
8950 # undef PL_charclass
8954 * We get here only if there's trouble -- normally "case END" is
8955 * the terminating point.
8957 Perl_croak(aTHX_ "corrupted regexp pointers");
8958 NOT_REACHED; /* NOTREACHED */
8962 /* we have successfully completed a subexpression, but we must now
8963 * pop to the state marked by yes_state and continue from there */
8964 assert(st != yes_state);
8966 while (st != yes_state) {
8968 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8969 PL_regmatch_slab = PL_regmatch_slab->prev;
8970 st = SLAB_LAST(PL_regmatch_slab);
8974 DEBUG_STATE_pp("pop (no final)");
8976 DEBUG_STATE_pp("pop (yes)");
8982 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8983 || yes_state > SLAB_LAST(PL_regmatch_slab))
8985 /* not in this slab, pop slab */
8986 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8987 PL_regmatch_slab = PL_regmatch_slab->prev;
8988 st = SLAB_LAST(PL_regmatch_slab);
8990 depth -= (st - yes_state);
8993 yes_state = st->u.yes.prev_yes_state;
8994 PL_regmatch_state = st;
8997 locinput= st->locinput;
8998 state_num = st->resume_state + no_final;
8999 goto reenter_switch;
9002 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
9003 PL_colors[4], PL_colors[5]));
9005 if (reginfo->info_aux_eval) {
9006 /* each successfully executed (?{...}) block does the equivalent of
9007 * local $^R = do {...}
9008 * When popping the save stack, all these locals would be undone;
9009 * bypass this by setting the outermost saved $^R to the latest
9011 /* I dont know if this is needed or works properly now.
9012 * see code related to PL_replgv elsewhere in this file.
9015 if (oreplsv != GvSV(PL_replgv))
9016 sv_setsv(oreplsv, GvSV(PL_replgv));
9023 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
9025 PL_colors[4], PL_colors[5])
9037 /* there's a previous state to backtrack to */
9039 if (st < SLAB_FIRST(PL_regmatch_slab)) {
9040 PL_regmatch_slab = PL_regmatch_slab->prev;
9041 st = SLAB_LAST(PL_regmatch_slab);
9043 PL_regmatch_state = st;
9044 locinput= st->locinput;
9046 DEBUG_STATE_pp("pop");
9048 if (yes_state == st)
9049 yes_state = st->u.yes.prev_yes_state;
9051 state_num = st->resume_state + 1; /* failure = success + 1 */
9053 goto reenter_switch;
9058 if (rex->intflags & PREGf_VERBARG_SEEN) {
9059 SV *sv_err = get_sv("REGERROR", 1);
9060 SV *sv_mrk = get_sv("REGMARK", 1);
9062 sv_commit = &PL_sv_no;
9064 sv_yes_mark = &PL_sv_yes;
9067 sv_commit = &PL_sv_yes;
9068 sv_yes_mark = &PL_sv_no;
9072 sv_setsv(sv_err, sv_commit);
9073 sv_setsv(sv_mrk, sv_yes_mark);
9077 if (last_pushed_cv) {
9079 /* see "Some notes about MULTICALL" above */
9081 PERL_UNUSED_VAR(SP);
9084 LEAVE_SCOPE(orig_savestack_ix);
9086 assert(!result || locinput - reginfo->strbeg >= 0);
9087 return result ? locinput - reginfo->strbeg : -1;
9091 - regrepeat - repeatedly match something simple, report how many
9093 * What 'simple' means is a node which can be the operand of a quantifier like
9096 * startposp - pointer a pointer to the start position. This is updated
9097 * to point to the byte following the highest successful
9099 * p - the regnode to be repeatedly matched against.
9100 * reginfo - struct holding match state, such as strend
9101 * max - maximum number of things to match.
9102 * depth - (for debugging) backtracking depth.
9105 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
9106 regmatch_info *const reginfo, I32 max _pDEPTH)
9108 char *scan; /* Pointer to current position in target string */
9110 char *loceol = reginfo->strend; /* local version */
9111 I32 hardcount = 0; /* How many matches so far */
9112 bool utf8_target = reginfo->is_utf8_target;
9113 unsigned int to_complement = 0; /* Invert the result? */
9115 _char_class_number classnum;
9117 PERL_ARGS_ASSERT_REGREPEAT;
9120 if (max == REG_INFTY)
9122 else if (! utf8_target && loceol - scan > max)
9123 loceol = scan + max;
9125 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
9126 * to the maximum of how far we should go in it (leaving it set to the real
9127 * end, if the maximum permissible would take us beyond that). This allows
9128 * us to make the loop exit condition that we haven't gone past <loceol> to
9129 * also mean that we haven't exceeded the max permissible count, saving a
9130 * test each time through the loop. But it assumes that the OP matches a
9131 * single byte, which is true for most of the OPs below when applied to a
9132 * non-UTF-8 target. Those relatively few OPs that don't have this
9133 * characteristic will have to compensate.
9135 * There is no adjustment for UTF-8 targets, as the number of bytes per
9136 * character varies. OPs will have to test both that the count is less
9137 * than the max permissible (using <hardcount> to keep track), and that we
9138 * are still within the bounds of the string (using <loceol>. A few OPs
9139 * match a single byte no matter what the encoding. They can omit the max
9140 * test if, for the UTF-8 case, they do the adjustment that was skipped
9143 * Thus, the code above sets things up for the common case; and exceptional
9144 * cases need extra work; the common case is to make sure <scan> doesn't
9145 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
9146 * count doesn't exceed the maximum permissible */
9151 while (scan < loceol && hardcount < max && *scan != '\n') {
9152 scan += UTF8SKIP(scan);
9156 scan = (char *) memchr(scan, '\n', loceol - scan);
9164 while (scan < loceol && hardcount < max) {
9165 scan += UTF8SKIP(scan);
9173 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9174 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
9175 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
9179 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
9183 /* Can use a simple find if the pattern char to match on is invariant
9184 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
9185 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
9186 * true iff it doesn't matter if the argument is in UTF-8 or not */
9187 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
9188 if (utf8_target && loceol - scan > max) {
9189 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
9190 * since here, to match at all, 1 char == 1 byte */
9191 loceol = scan + max;
9193 scan = (char *) find_span_end((U8 *) scan, (U8 *) loceol, (U8) c);
9195 else if (reginfo->is_utf8_pat) {
9197 STRLEN scan_char_len;
9199 /* When both target and pattern are UTF-8, we have to do
9201 while (hardcount < max
9203 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
9204 && memEQ(scan, STRING(p), scan_char_len))
9206 scan += scan_char_len;
9210 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
9212 /* Target isn't utf8; convert the character in the UTF-8
9213 * pattern to non-UTF8, and do a simple find */
9214 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
9215 scan = (char *) find_span_end((U8 *) scan, (U8 *) loceol, (U8) c);
9216 } /* else pattern char is above Latin1, can't possibly match the
9221 /* Here, the string must be utf8; pattern isn't, and <c> is
9222 * different in utf8 than not, so can't compare them directly.
9223 * Outside the loop, find the two utf8 bytes that represent c, and
9224 * then look for those in sequence in the utf8 string */
9225 U8 high = UTF8_TWO_BYTE_HI(c);
9226 U8 low = UTF8_TWO_BYTE_LO(c);
9228 while (hardcount < max
9229 && scan + 1 < loceol
9230 && UCHARAT(scan) == high
9231 && UCHARAT(scan + 1) == low)
9239 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8 patterns */
9240 assert(! reginfo->is_utf8_pat);
9243 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
9247 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9248 utf8_flags = FOLDEQ_LOCALE;
9251 case EXACTF: /* This node only generated for non-utf8 patterns */
9252 assert(! reginfo->is_utf8_pat);
9257 if (! utf8_target) {
9260 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
9261 | FOLDEQ_S2_FOLDS_SANE;
9266 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
9270 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
9272 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
9274 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
9277 if (c1 == CHRTEST_VOID) {
9278 /* Use full Unicode fold matching */
9279 char *tmpeol = reginfo->strend;
9280 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
9281 while (hardcount < max
9282 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
9283 STRING(p), NULL, pat_len,
9284 reginfo->is_utf8_pat, utf8_flags))
9287 tmpeol = reginfo->strend;
9291 else if (utf8_target) {
9293 while (scan < loceol
9295 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
9297 scan += UTF8SKIP(scan);
9302 while (scan < loceol
9304 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
9305 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
9307 scan += UTF8SKIP(scan);
9312 else if (c1 == c2) {
9313 scan = (char *) find_span_end((U8 *) scan, (U8 *) loceol, (U8) c1);
9316 /* See comments in regmatch() CURLY_B_min_known_fail. We avoid
9317 * a conditional each time through the loop if the characters
9318 * differ only in a single bit, as is the usual situation */
9319 U8 c1_c2_bits_differing = c1 ^ c2;
9321 if (isPOWER_OF_2(c1_c2_bits_differing)) {
9322 U8 c1_c2_mask = ~ c1_c2_bits_differing;
9324 scan = (char *) find_span_end_mask((U8 *) scan,
9330 while ( scan < loceol
9331 && (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
9341 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9343 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
9344 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
9350 while (hardcount < max
9352 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
9354 scan += UTF8SKIP(scan);
9358 else if (ANYOF_FLAGS(p)) {
9359 while (scan < loceol
9360 && reginclass(prog, p, (U8*)scan, (U8*)scan+1, 0))
9364 while (scan < loceol && ANYOF_BITMAP_TEST(p, *((U8*)scan)))
9370 if (utf8_target && loceol - scan > max) {
9372 /* We didn't adjust <loceol> at the beginning of this routine
9373 * because is UTF-8, but it is actually ok to do so, since here, to
9374 * match, 1 char == 1 byte. */
9375 loceol = scan + max;
9378 scan = (char *) find_span_end_mask((U8 *) scan, (U8 *) loceol, (U8) ARG(p), FLAGS(p));
9382 if (utf8_target && loceol - scan > max) {
9383 loceol = scan + max;
9386 scan = find_next_non_ascii(scan, loceol, utf8_target);
9391 while ( hardcount < max
9393 && ! isASCII_utf8_safe(scan, loceol))
9395 scan += UTF8SKIP(scan);
9400 scan = find_next_ascii(scan, loceol, utf8_target);
9404 /* The argument (FLAGS) to all the POSIX node types is the class number */
9411 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9412 if (! utf8_target) {
9413 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
9419 while (hardcount < max && scan < loceol
9420 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
9424 scan += UTF8SKIP(scan);
9437 if (utf8_target && loceol - scan > max) {
9439 /* We didn't adjust <loceol> at the beginning of this routine
9440 * because is UTF-8, but it is actually ok to do so, since here, to
9441 * match, 1 char == 1 byte. */
9442 loceol = scan + max;
9444 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
9457 if (! utf8_target) {
9458 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
9464 /* The complement of something that matches only ASCII matches all
9465 * non-ASCII, plus everything in ASCII that isn't in the class. */
9466 while (hardcount < max && scan < loceol
9467 && ( ! isASCII_utf8_safe(scan, reginfo->strend)
9468 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
9470 scan += UTF8SKIP(scan);
9481 if (! utf8_target) {
9482 while (scan < loceol && to_complement
9483 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
9490 classnum = (_char_class_number) FLAGS(p);
9493 while ( hardcount < max && scan < loceol
9494 && to_complement ^ cBOOL(_invlist_contains_cp(
9495 PL_XPosix_ptrs[classnum],
9496 utf8_to_uvchr_buf((U8 *) scan,
9500 scan += UTF8SKIP(scan);
9505 /* For the classes below, the knowledge of how to handle
9506 * every code point is compiled in to Perl via a macro.
9507 * This code is written for making the loops as tight as
9508 * possible. It could be refactored to save space instead.
9511 case _CC_ENUM_SPACE:
9512 while (hardcount < max
9515 ^ cBOOL(isSPACE_utf8_safe(scan, loceol))))
9517 scan += UTF8SKIP(scan);
9521 case _CC_ENUM_BLANK:
9522 while (hardcount < max
9525 ^ cBOOL(isBLANK_utf8_safe(scan, loceol))))
9527 scan += UTF8SKIP(scan);
9531 case _CC_ENUM_XDIGIT:
9532 while (hardcount < max
9535 ^ cBOOL(isXDIGIT_utf8_safe(scan, loceol))))
9537 scan += UTF8SKIP(scan);
9541 case _CC_ENUM_VERTSPACE:
9542 while (hardcount < max
9545 ^ cBOOL(isVERTWS_utf8_safe(scan, loceol))))
9547 scan += UTF8SKIP(scan);
9551 case _CC_ENUM_CNTRL:
9552 while (hardcount < max
9555 ^ cBOOL(isCNTRL_utf8_safe(scan, loceol))))
9557 scan += UTF8SKIP(scan);
9567 while (hardcount < max && scan < loceol &&
9568 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9573 /* LNBREAK can match one or two latin chars, which is ok, but we
9574 * have to use hardcount in this situation, and throw away the
9575 * adjustment to <loceol> done before the switch statement */
9576 loceol = reginfo->strend;
9577 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9586 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9600 /* These are all 0 width, so match right here or not at all. */
9604 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9605 NOT_REACHED; /* NOTREACHED */
9612 c = scan - *startposp;
9616 GET_RE_DEBUG_FLAGS_DECL;
9618 SV * const prop = sv_newmortal();
9619 regprop(prog, prop, p, reginfo, NULL);
9620 Perl_re_exec_indentf( aTHX_ "%s can match %" IVdf " times out of %" IVdf "...\n",
9621 depth, SvPVX_const(prop),(IV)c,(IV)max);
9629 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9631 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9632 create a copy so that changes the caller makes won't change the shared one.
9633 If <altsvp> is non-null, will return NULL in it, for back-compat.
9636 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9638 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9644 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9647 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9650 - reginclass - determine if a character falls into a character class
9652 n is the ANYOF-type regnode
9653 p is the target string
9654 p_end points to one byte beyond the end of the target string
9655 utf8_target tells whether p is in UTF-8.
9657 Returns true if matched; false otherwise.
9659 Note that this can be a synthetic start class, a combination of various
9660 nodes, so things you think might be mutually exclusive, such as locale,
9661 aren't. It can match both locale and non-locale
9666 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9669 const char flags = ANYOF_FLAGS(n);
9673 PERL_ARGS_ASSERT_REGINCLASS;
9675 /* If c is not already the code point, get it. Note that
9676 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9677 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9679 const U32 utf8n_flags = UTF8_ALLOW_DEFAULT;
9680 c = utf8n_to_uvchr(p, p_end - p, &c_len, utf8n_flags | UTF8_CHECK_ONLY);
9681 if (c_len == (STRLEN)-1) {
9682 _force_out_malformed_utf8_message(p, p_end,
9684 1 /* 1 means die */ );
9685 NOT_REACHED; /* NOTREACHED */
9687 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9688 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9692 /* If this character is potentially in the bitmap, check it */
9693 if (c < NUM_ANYOF_CODE_POINTS) {
9694 if (ANYOF_BITMAP_TEST(n, c))
9697 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9704 else if (flags & ANYOF_LOCALE_FLAGS) {
9705 if ((flags & ANYOFL_FOLD)
9707 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9711 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9715 /* The data structure is arranged so bits 0, 2, 4, ... are set
9716 * if the class includes the Posix character class given by
9717 * bit/2; and 1, 3, 5, ... are set if the class includes the
9718 * complemented Posix class given by int(bit/2). So we loop
9719 * through the bits, each time changing whether we complement
9720 * the result or not. Suppose for the sake of illustration
9721 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9722 * is set, it means there is a match for this ANYOF node if the
9723 * character is in the class given by the expression (0 / 2 = 0
9724 * = \w). If it is in that class, isFOO_lc() will return 1,
9725 * and since 'to_complement' is 0, the result will stay TRUE,
9726 * and we exit the loop. Suppose instead that bit 0 is 0, but
9727 * bit 1 is 1. That means there is a match if the character
9728 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9729 * but will on bit 1. On the second iteration 'to_complement'
9730 * will be 1, so the exclusive or will reverse things, so we
9731 * are testing for \W. On the third iteration, 'to_complement'
9732 * will be 0, and we would be testing for \s; the fourth
9733 * iteration would test for \S, etc.
9735 * Note that this code assumes that all the classes are closed
9736 * under folding. For example, if a character matches \w, then
9737 * its fold does too; and vice versa. This should be true for
9738 * any well-behaved locale for all the currently defined Posix
9739 * classes, except for :lower: and :upper:, which are handled
9740 * by the pseudo-class :cased: which matches if either of the
9741 * other two does. To get rid of this assumption, an outer
9742 * loop could be used below to iterate over both the source
9743 * character, and its fold (if different) */
9746 int to_complement = 0;
9748 while (count < ANYOF_MAX) {
9749 if (ANYOF_POSIXL_TEST(n, count)
9750 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9763 /* If the bitmap didn't (or couldn't) match, and something outside the
9764 * bitmap could match, try that. */
9766 if (c >= NUM_ANYOF_CODE_POINTS
9767 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9769 match = TRUE; /* Everything above the bitmap matches */
9771 /* Here doesn't match everything above the bitmap. If there is
9772 * some information available beyond the bitmap, we may find a
9773 * match in it. If so, this is most likely because the code point
9774 * is outside the bitmap range. But rarely, it could be because of
9775 * some other reason. If so, various flags are set to indicate
9776 * this possibility. On ANYOFD nodes, there may be matches that
9777 * happen only when the target string is UTF-8; or for other node
9778 * types, because runtime lookup is needed, regardless of the
9779 * UTF-8ness of the target string. Finally, under /il, there may
9780 * be some matches only possible if the locale is a UTF-8 one. */
9781 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9782 && ( c >= NUM_ANYOF_CODE_POINTS
9783 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9784 && ( UNLIKELY(OP(n) != ANYOFD)
9785 || (utf8_target && ! isASCII_uni(c)
9786 # if NUM_ANYOF_CODE_POINTS > 256
9790 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9791 && IN_UTF8_CTYPE_LOCALE)))
9793 SV* only_utf8_locale = NULL;
9794 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9795 &only_utf8_locale, NULL);
9801 } else { /* Convert to utf8 */
9802 utf8_p = utf8_buffer;
9803 append_utf8_from_native_byte(*p, &utf8_p);
9804 utf8_p = utf8_buffer;
9807 if (swash_fetch(sw, utf8_p, TRUE)) {
9811 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9812 match = _invlist_contains_cp(only_utf8_locale, c);
9816 if (UNICODE_IS_SUPER(c)
9818 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9820 && ckWARN_d(WARN_NON_UNICODE))
9822 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9823 "Matched non-Unicode code point 0x%04" UVXf " against Unicode property; may not be portable", c);
9827 #if ANYOF_INVERT != 1
9828 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9830 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9833 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9834 return (flags & ANYOF_INVERT) ^ match;
9838 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9840 /* return the position 'off' UTF-8 characters away from 's', forward if
9841 * 'off' >= 0, backwards if negative. But don't go outside of position
9842 * 'lim', which better be < s if off < 0 */
9844 PERL_ARGS_ASSERT_REGHOP3;
9847 while (off-- && s < lim) {
9848 /* XXX could check well-formedness here */
9849 U8 *new_s = s + UTF8SKIP(s);
9850 if (new_s > lim) /* lim may be in the middle of a long character */
9856 while (off++ && s > lim) {
9858 if (UTF8_IS_CONTINUED(*s)) {
9859 while (s > lim && UTF8_IS_CONTINUATION(*s))
9861 if (! UTF8_IS_START(*s)) {
9862 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9865 /* XXX could check well-formedness here */
9872 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9874 PERL_ARGS_ASSERT_REGHOP4;
9877 while (off-- && s < rlim) {
9878 /* XXX could check well-formedness here */
9883 while (off++ && s > llim) {
9885 if (UTF8_IS_CONTINUED(*s)) {
9886 while (s > llim && UTF8_IS_CONTINUATION(*s))
9888 if (! UTF8_IS_START(*s)) {
9889 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9892 /* XXX could check well-formedness here */
9898 /* like reghop3, but returns NULL on overrun, rather than returning last
9902 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9904 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9907 while (off-- && s < lim) {
9908 /* XXX could check well-formedness here */
9915 while (off++ && s > lim) {
9917 if (UTF8_IS_CONTINUED(*s)) {
9918 while (s > lim && UTF8_IS_CONTINUATION(*s))
9920 if (! UTF8_IS_START(*s)) {
9921 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9924 /* XXX could check well-formedness here */
9933 /* when executing a regex that may have (?{}), extra stuff needs setting
9934 up that will be visible to the called code, even before the current
9935 match has finished. In particular:
9937 * $_ is localised to the SV currently being matched;
9938 * pos($_) is created if necessary, ready to be updated on each call-out
9940 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9941 isn't set until the current pattern is successfully finished), so that
9942 $1 etc of the match-so-far can be seen;
9943 * save the old values of subbeg etc of the current regex, and set then
9944 to the current string (again, this is normally only done at the end
9949 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9952 regexp *const rex = ReANY(reginfo->prog);
9953 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9955 eval_state->rex = rex;
9958 /* Make $_ available to executed code. */
9959 if (reginfo->sv != DEFSV) {
9961 DEFSV_set(reginfo->sv);
9964 if (!(mg = mg_find_mglob(reginfo->sv))) {
9965 /* prepare for quick setting of pos */
9966 mg = sv_magicext_mglob(reginfo->sv);
9969 eval_state->pos_magic = mg;
9970 eval_state->pos = mg->mg_len;
9971 eval_state->pos_flags = mg->mg_flags;
9974 eval_state->pos_magic = NULL;
9976 if (!PL_reg_curpm) {
9977 /* PL_reg_curpm is a fake PMOP that we can attach the current
9978 * regex to and point PL_curpm at, so that $1 et al are visible
9979 * within a /(?{})/. It's just allocated once per interpreter the
9980 * first time its needed */
9981 Newxz(PL_reg_curpm, 1, PMOP);
9984 SV* const repointer = &PL_sv_undef;
9985 /* this regexp is also owned by the new PL_reg_curpm, which
9986 will try to free it. */
9987 av_push(PL_regex_padav, repointer);
9988 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9989 PL_regex_pad = AvARRAY(PL_regex_padav);
9993 SET_reg_curpm(reginfo->prog);
9994 eval_state->curpm = PL_curpm;
9995 PL_curpm_under = PL_curpm;
9996 PL_curpm = PL_reg_curpm;
9997 if (RXp_MATCH_COPIED(rex)) {
9998 /* Here is a serious problem: we cannot rewrite subbeg,
9999 since it may be needed if this match fails. Thus
10000 $` inside (?{}) could fail... */
10001 eval_state->subbeg = rex->subbeg;
10002 eval_state->sublen = rex->sublen;
10003 eval_state->suboffset = rex->suboffset;
10004 eval_state->subcoffset = rex->subcoffset;
10005 #ifdef PERL_ANY_COW
10006 eval_state->saved_copy = rex->saved_copy;
10008 RXp_MATCH_COPIED_off(rex);
10011 eval_state->subbeg = NULL;
10012 rex->subbeg = (char *)reginfo->strbeg;
10013 rex->suboffset = 0;
10014 rex->subcoffset = 0;
10015 rex->sublen = reginfo->strend - reginfo->strbeg;
10019 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
10022 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
10024 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
10025 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
10028 Safefree(aux->poscache);
10032 /* undo the effects of S_setup_eval_state() */
10034 if (eval_state->subbeg) {
10035 regexp * const rex = eval_state->rex;
10036 rex->subbeg = eval_state->subbeg;
10037 rex->sublen = eval_state->sublen;
10038 rex->suboffset = eval_state->suboffset;
10039 rex->subcoffset = eval_state->subcoffset;
10040 #ifdef PERL_ANY_COW
10041 rex->saved_copy = eval_state->saved_copy;
10043 RXp_MATCH_COPIED_on(rex);
10045 if (eval_state->pos_magic)
10047 eval_state->pos_magic->mg_len = eval_state->pos;
10048 eval_state->pos_magic->mg_flags =
10049 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
10050 | (eval_state->pos_flags & MGf_BYTES);
10053 PL_curpm = eval_state->curpm;
10056 PL_regmatch_state = aux->old_regmatch_state;
10057 PL_regmatch_slab = aux->old_regmatch_slab;
10059 /* free all slabs above current one - this must be the last action
10060 * of this function, as aux and eval_state are allocated within
10061 * slabs and may be freed here */
10063 s = PL_regmatch_slab->next;
10065 PL_regmatch_slab->next = NULL;
10067 regmatch_slab * const osl = s;
10076 S_to_utf8_substr(pTHX_ regexp *prog)
10078 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
10079 * on the converted value */
10083 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
10086 if (prog->substrs->data[i].substr
10087 && !prog->substrs->data[i].utf8_substr) {
10088 SV* const sv = newSVsv(prog->substrs->data[i].substr);
10089 prog->substrs->data[i].utf8_substr = sv;
10090 sv_utf8_upgrade(sv);
10091 if (SvVALID(prog->substrs->data[i].substr)) {
10092 if (SvTAIL(prog->substrs->data[i].substr)) {
10093 /* Trim the trailing \n that fbm_compile added last
10095 SvCUR_set(sv, SvCUR(sv) - 1);
10096 /* Whilst this makes the SV technically "invalid" (as its
10097 buffer is no longer followed by "\0") when fbm_compile()
10098 adds the "\n" back, a "\0" is restored. */
10099 fbm_compile(sv, FBMcf_TAIL);
10101 fbm_compile(sv, 0);
10103 if (prog->substrs->data[i].substr == prog->check_substr)
10104 prog->check_utf8 = sv;
10110 S_to_byte_substr(pTHX_ regexp *prog)
10112 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
10113 * on the converted value; returns FALSE if can't be converted. */
10117 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
10120 if (prog->substrs->data[i].utf8_substr
10121 && !prog->substrs->data[i].substr) {
10122 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
10123 if (! sv_utf8_downgrade(sv, TRUE)) {
10126 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
10127 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
10128 /* Trim the trailing \n that fbm_compile added last
10130 SvCUR_set(sv, SvCUR(sv) - 1);
10131 fbm_compile(sv, FBMcf_TAIL);
10133 fbm_compile(sv, 0);
10135 prog->substrs->data[i].substr = sv;
10136 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
10137 prog->check_substr = sv;
10144 #ifndef PERL_IN_XSUB_RE
10147 Perl__is_grapheme(pTHX_ const U8 * strbeg, const U8 * s, const U8 * strend, const UV cp)
10149 /* Temporary helper function for toke.c. Verify that the code point 'cp'
10150 * is a stand-alone grapheme. The UTF-8 for 'cp' begins at position 's' in
10151 * the larger string bounded by 'strbeg' and 'strend'.
10153 * 'cp' needs to be assigned (if not a future version of the Unicode
10154 * Standard could make it something that combines with adjacent characters,
10155 * so code using it would then break), and there has to be a GCB break
10156 * before and after the character. */
10158 GCB_enum cp_gcb_val, prev_cp_gcb_val, next_cp_gcb_val;
10159 const U8 * prev_cp_start;
10161 PERL_ARGS_ASSERT__IS_GRAPHEME;
10163 if ( UNLIKELY(UNICODE_IS_SUPER(cp))
10164 || UNLIKELY(UNICODE_IS_NONCHAR(cp)))
10166 /* These are considered graphemes */
10170 /* Otherwise, unassigned code points are forbidden */
10171 if (UNLIKELY(! ELEMENT_RANGE_MATCHES_INVLIST(
10172 _invlist_search(PL_Assigned_invlist, cp))))
10177 cp_gcb_val = getGCB_VAL_CP(cp);
10179 /* Find the GCB value of the previous code point in the input */
10180 prev_cp_start = utf8_hop_back(s, -1, strbeg);
10181 if (UNLIKELY(prev_cp_start == s)) {
10182 prev_cp_gcb_val = GCB_EDGE;
10185 prev_cp_gcb_val = getGCB_VAL_UTF8(prev_cp_start, strend);
10188 /* And check that is a grapheme boundary */
10189 if (! isGCB(prev_cp_gcb_val, cp_gcb_val, strbeg, s,
10190 TRUE /* is UTF-8 encoded */ ))
10195 /* Similarly verify there is a break between the current character and the
10199 next_cp_gcb_val = GCB_EDGE;
10202 next_cp_gcb_val = getGCB_VAL_UTF8(s, strend);
10205 return isGCB(cp_gcb_val, next_cp_gcb_val, strbeg, s, TRUE);
10209 =head1 Unicode Support
10211 =for apidoc isSCRIPT_RUN
10213 Returns a bool as to whether or not the sequence of bytes from C<s> up to but
10214 not including C<send> form a "script run". C<utf8_target> is TRUE iff the
10215 sequence starting at C<s> is to be treated as UTF-8. To be precise, except for
10216 two degenerate cases given below, this function returns TRUE iff all code
10217 points in it come from any combination of three "scripts" given by the Unicode
10218 "Script Extensions" property: Common, Inherited, and possibly one other.
10219 Additionally all decimal digits must come from the same consecutive sequence of
10222 For example, if all the characters in the sequence are Greek, or Common, or
10223 Inherited, this function will return TRUE, provided any decimal digits in it
10224 are the ASCII digits "0".."9". For scripts (unlike Greek) that have their own
10225 digits defined this will accept either digits from that set or from 0..9, but
10226 not a combination of the two. Some scripts, such as Arabic, have more than one
10227 set of digits. All digits must come from the same set for this function to
10230 C<*ret_script>, if C<ret_script> is not NULL, will on return of TRUE
10231 contain the script found, using the C<SCX_enum> typedef. Its value will be
10232 C<SCX_INVALID> if the function returns FALSE.
10234 If the sequence is empty, TRUE is returned, but C<*ret_script> (if asked for)
10235 will be C<SCX_INVALID>.
10237 If the sequence contains a single code point which is unassigned to a character
10238 in the version of Unicode being used, the function will return TRUE, and the
10239 script will be C<SCX_Unknown>. Any other combination of unassigned code points
10240 in the input sequence will result in the function treating the input as not
10241 being a script run.
10243 The returned script will be C<SCX_Inherited> iff all the code points in it are
10244 from the Inherited script.
10246 Otherwise, the returned script will be C<SCX_Common> iff all the code points in
10247 it are from the Inherited or Common scripts.
10254 Perl_isSCRIPT_RUN(pTHX_ const U8 * s, const U8 * send, const bool utf8_target)
10256 /* Basically, it looks at each character in the sequence to see if the
10257 * above conditions are met; if not it fails. It uses an inversion map to
10258 * find the enum corresponding to the script of each character. But this
10259 * is complicated by the fact that a few code points can be in any of
10260 * several scripts. The data has been constructed so that there are
10261 * additional enum values (all negative) for these situations. The
10262 * absolute value of those is an index into another table which contains
10263 * pointers to auxiliary tables for each such situation. Each aux array
10264 * lists all the scripts for the given situation. There is another,
10265 * parallel, table that gives the number of entries in each aux table.
10266 * These are all defined in charclass_invlists.h */
10268 /* XXX Here are the additional things UTS 39 says could be done:
10269 * Mark Chinese strings as “mixed script” if they contain both simplified
10270 * (S) and traditional (T) Chinese characters, using the Unihan data in the
10271 * Unicode Character Database [UCD]. The criterion can only be applied if
10272 * the language of the string is known to be Chinese. So, for example, the
10273 * string “写真だけの結婚式 ” is Japanese, and should not be marked as
10274 * mixed script because of a mixture of S and T characters. Testing for
10275 * whether a character is S or T needs to be based not on whether the
10276 * character has a S or T variant , but whether the character is an S or T
10277 * variant. khw notes that the sample contains a Hiragana character, and it
10278 * is unclear if absence of any foreign script marks the script as
10281 * Forbid sequences of the same nonspacing mark
10283 * Check to see that all the characters are in the sets of exemplar
10284 * characters for at least one language in the Unicode Common Locale Data
10285 * Repository [CLDR]. */
10288 /* Things that match /\d/u */
10289 SV * decimals_invlist = PL_XPosix_ptrs[_CC_DIGIT];
10290 UV * decimals_array = invlist_array(decimals_invlist);
10292 /* What code point is the digit '0' of the script run? */
10293 UV zero_of_run = 0;
10294 SCX_enum script_of_run = SCX_INVALID; /* Illegal value */
10295 SCX_enum script_of_char = SCX_INVALID;
10297 /* If the script remains not fully determined from iteration to iteration,
10298 * this is the current intersection of the possiblities. */
10299 SCX_enum * intersection = NULL;
10300 PERL_UINT_FAST8_T intersection_len = 0;
10302 bool retval = TRUE;
10304 /* This is supposed to be a return parameter, but currently unused */
10305 SCX_enum * ret_script = NULL;
10309 PERL_ARGS_ASSERT_ISSCRIPT_RUN;
10311 /* All code points in 0..255 are either Common or Latin, so must be a
10312 * script run. We can special case it */
10313 if (! utf8_target && LIKELY(send > s)) {
10314 if (ret_script == NULL) {
10318 /* If any character is Latin, the run is Latin */
10320 if (isALPHA_L1(*s) && LIKELY(*s != MICRO_SIGN_NATIVE)) {
10321 *ret_script = SCX_Latin;
10326 /* If all are Common ... */
10327 *ret_script = SCX_Common;
10331 /* Look at each character in the sequence */
10335 /* The code allows all scripts to use the ASCII digits. This is
10336 * because they are used in commerce even in scripts that have their
10337 * own set. Hence any ASCII ones found are ok, unless a digit from
10338 * another set has already been encountered. (The other digit ranges
10339 * in Common are not similarly blessed) */
10340 if (UNLIKELY(isDIGIT(*s))) {
10341 if (UNLIKELY(script_of_run == SCX_Unknown)) {
10345 if (zero_of_run > 0) {
10346 if (zero_of_run != '0') {
10358 /* Here, isn't an ASCII digit. Find the code point of the character */
10359 if (! UTF8_IS_INVARIANT(*s)) {
10361 cp = valid_utf8_to_uvchr((U8 *) s, &len);
10368 /* If is within the range [+0 .. +9] of the script's zero, it also is a
10369 * digit in that script. We can skip the rest of this code for this
10371 if (UNLIKELY( zero_of_run > 0
10372 && cp >= zero_of_run
10373 && cp - zero_of_run <= 9))
10378 /* Find the character's script. The correct values are hard-coded here
10379 * for small-enough code points. */
10380 if (cp < 0x2B9) { /* From inspection of Unicode db; extremely
10381 unlikely to change */
10383 || ( isALPHA_L1(cp)
10384 && LIKELY(cp != MICRO_SIGN_NATIVE)))
10386 script_of_char = SCX_Latin;
10389 script_of_char = SCX_Common;
10393 script_of_char = _Perl_SCX_invmap[
10394 _invlist_search(PL_SCX_invlist, cp)];
10397 /* We arbitrarily accept a single unassigned character, but not in
10398 * combination with anything else, and not a run of them. */
10399 if ( UNLIKELY(script_of_run == SCX_Unknown)
10400 || UNLIKELY( script_of_run != SCX_INVALID
10401 && script_of_char == SCX_Unknown))
10407 /* For the first character, or the run is inherited, the run's script
10408 * is set to the char's */
10409 if ( UNLIKELY(script_of_run == SCX_INVALID)
10410 || UNLIKELY(script_of_run == SCX_Inherited))
10412 script_of_run = script_of_char;
10415 /* For the character's script to be Unknown, it must be the first
10416 * character in the sequence (for otherwise a test above would have
10417 * prevented us from reaching here), and we have set the run's script
10418 * to it. Nothing further to be done for this character */
10419 if (UNLIKELY(script_of_char == SCX_Unknown)) {
10423 /* We accept 'inherited' script characters currently even at the
10424 * beginning. (We know that no characters in Inherited are digits, or
10425 * we'd have to check for that) */
10426 if (UNLIKELY(script_of_char == SCX_Inherited)) {
10430 /* If the run so far is Common, and the new character isn't, change the
10431 * run's script to that of this character */
10432 if (script_of_run == SCX_Common && script_of_char != SCX_Common) {
10434 /* But Common contains several sets of digits. Only the '0' set
10435 * can be part of another script. */
10436 if (zero_of_run > 0 && zero_of_run != '0') {
10441 script_of_run = script_of_char;
10444 /* All decimal digits must be from the same sequence of 10. Above, we
10445 * handled any ASCII digits without descending to here. We also
10446 * handled the case where we already knew what digit sequence is the
10447 * one to use, and the character is in that sequence. Now that we know
10448 * the script, we can use script_zeros[] to directly find which
10449 * sequence the script uses, except in a few cases it returns 0 */
10450 if (UNLIKELY(zero_of_run == 0) && script_of_char >= 0) {
10451 zero_of_run = script_zeros[script_of_char];
10454 /* Now we can see if the script of the character is the same as that of
10456 if (LIKELY(script_of_char == script_of_run)) {
10457 /* By far the most common case */
10458 goto scripts_match;
10462 /* Here, the script of the run isn't Common. But characters in Common
10463 * match any script */
10464 if (script_of_char == SCX_Common) {
10465 goto scripts_match;
10468 #ifndef HAS_SCX_AUX_TABLES
10470 /* Too early a Unicode version to have a code point belonging to more
10471 * than one script, so, if the scripts don't exactly match, fail */
10472 PERL_UNUSED_VAR(intersection_len);
10478 /* Here there is no exact match between the character's script and the
10479 * run's. And we've handled the special cases of scripts Unknown,
10480 * Inherited, and Common.
10482 * Negative script numbers signify that the value may be any of several
10483 * scripts, and we need to look at auxiliary information to make our
10484 * deterimination. But if both are non-negative, we can fail now */
10485 if (LIKELY(script_of_char >= 0)) {
10486 const SCX_enum * search_in;
10487 PERL_UINT_FAST8_T search_in_len;
10488 PERL_UINT_FAST8_T i;
10490 if (LIKELY(script_of_run >= 0)) {
10495 /* Use the previously constructed set of possible scripts, if any.
10497 if (intersection) {
10498 search_in = intersection;
10499 search_in_len = intersection_len;
10502 search_in = SCX_AUX_TABLE_ptrs[-script_of_run];
10503 search_in_len = SCX_AUX_TABLE_lengths[-script_of_run];
10506 for (i = 0; i < search_in_len; i++) {
10507 if (search_in[i] == script_of_char) {
10508 script_of_run = script_of_char;
10509 goto scripts_match;
10516 else if (LIKELY(script_of_run >= 0)) {
10517 /* script of character could be one of several, but run is a single
10519 const SCX_enum * search_in = SCX_AUX_TABLE_ptrs[-script_of_char];
10520 const PERL_UINT_FAST8_T search_in_len
10521 = SCX_AUX_TABLE_lengths[-script_of_char];
10522 PERL_UINT_FAST8_T i;
10524 for (i = 0; i < search_in_len; i++) {
10525 if (search_in[i] == script_of_run) {
10526 script_of_char = script_of_run;
10527 goto scripts_match;
10535 /* Both run and char could be in one of several scripts. If the
10536 * intersection is empty, then this character isn't in this script
10537 * run. Otherwise, we need to calculate the intersection to use
10538 * for future iterations of the loop, unless we are already at the
10539 * final character */
10540 const SCX_enum * search_char = SCX_AUX_TABLE_ptrs[-script_of_char];
10541 const PERL_UINT_FAST8_T char_len
10542 = SCX_AUX_TABLE_lengths[-script_of_char];
10543 const SCX_enum * search_run;
10544 PERL_UINT_FAST8_T run_len;
10546 SCX_enum * new_overlap = NULL;
10547 PERL_UINT_FAST8_T i, j;
10549 if (intersection) {
10550 search_run = intersection;
10551 run_len = intersection_len;
10554 search_run = SCX_AUX_TABLE_ptrs[-script_of_run];
10555 run_len = SCX_AUX_TABLE_lengths[-script_of_run];
10558 intersection_len = 0;
10560 for (i = 0; i < run_len; i++) {
10561 for (j = 0; j < char_len; j++) {
10562 if (search_run[i] == search_char[j]) {
10564 /* Here, the script at i,j matches. That means this
10565 * character is in the run. But continue on to find
10566 * the complete intersection, for the next loop
10567 * iteration, and for the digit check after it.
10569 * On the first found common script, we malloc space
10570 * for the intersection list for the worst case of the
10571 * intersection, which is the minimum of the number of
10572 * scripts remaining in each set. */
10573 if (intersection_len == 0) {
10575 MIN(run_len - i, char_len - j),
10578 new_overlap[intersection_len++] = search_run[i];
10583 /* Here we've looked through everything. If they have no scripts
10584 * in common, not a run */
10585 if (intersection_len == 0) {
10590 /* If there is only a single script in common, set to that.
10591 * Otherwise, use the intersection going forward */
10592 Safefree(intersection);
10593 intersection = NULL;
10594 if (intersection_len == 1) {
10595 script_of_run = script_of_char = new_overlap[0];
10596 Safefree(new_overlap);
10597 new_overlap = NULL;
10600 intersection = new_overlap;
10608 /* Here, the script of the character is compatible with that of the
10609 * run. Either they match exactly, or one or both can be any of
10610 * several scripts, and the intersection is not empty. If the
10611 * character is not a decimal digit, we are done with it. Otherwise,
10612 * it could still fail if it is from a different set of 10 than seen
10613 * already (or we may not have seen any, and we need to set the
10614 * sequence). If we have determined a single script and that script
10615 * only has one set of digits (almost all scripts are like that), then
10616 * this isn't a problem, as any digit must come from the same sequence.
10617 * The only scripts that have multiple sequences have been constructed
10618 * to be 0 in 'script_zeros[]'.
10620 * Here we check if it is a digit. */
10621 if ( cp >= FIRST_NON_ASCII_DECIMAL_DIGIT
10622 && ( ( zero_of_run == 0
10623 || ( ( script_of_char >= 0
10624 && script_zeros[script_of_char] == 0)
10625 || intersection))))
10627 SSize_t range_zero_index;
10628 range_zero_index = _invlist_search(decimals_invlist, cp);
10629 if ( LIKELY(range_zero_index >= 0)
10630 && ELEMENT_RANGE_MATCHES_INVLIST(range_zero_index))
10632 UV range_zero = decimals_array[range_zero_index];
10634 if (zero_of_run != range_zero) {
10640 zero_of_run = range_zero;
10644 } /* end of looping through CLOSESR text */
10646 Safefree(intersection);
10648 if (ret_script != NULL) {
10650 *ret_script = script_of_run;
10653 *ret_script = SCX_INVALID;
10660 #endif /* ifndef PERL_IN_XSUB_RE */
10663 * ex: set ts=8 sts=4 sw=4 et: