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 /* set the start and end positions of capture ix */
332 #define CLOSE_CAPTURE(ix, s, e) \
333 rex->offs[ix].start = s; \
334 rex->offs[ix].end = e; \
335 if (ix > rex->lastparen) \
336 rex->lastparen = ix; \
337 rex->lastcloseparen = ix; \
338 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
339 "CLOSE: rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf " max: %" UVuf "\n", \
344 (IV)rex->offs[ix].start, \
345 (IV)rex->offs[ix].end, \
349 #define UNWIND_PAREN(lp, lcp) \
350 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
351 "UNWIND_PAREN: rex=0x%" UVxf " offs=0x%" UVxf ": invalidate (%" UVuf "..%" UVuf "] set lcp: %" UVuf "\n", \
356 (UV)(rex->lastparen), \
359 for (n = rex->lastparen; n > lp; n--) \
360 rex->offs[n].end = -1; \
361 rex->lastparen = n; \
362 rex->lastcloseparen = lcp;
366 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
370 GET_RE_DEBUG_FLAGS_DECL;
372 PERL_ARGS_ASSERT_REGCPPOP;
374 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
376 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
377 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
378 rex->lastcloseparen = SSPOPINT;
379 rex->lastparen = SSPOPINT;
380 *maxopenparen_p = SSPOPINT;
382 i -= REGCP_OTHER_ELEMS;
383 /* Now restore the parentheses context. */
385 if (i || rex->lastparen + 1 <= rex->nparens)
386 Perl_re_exec_indentf( aTHX_
387 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
393 paren = *maxopenparen_p;
394 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
396 rex->offs[paren].start_tmp = SSPOPINT;
397 rex->offs[paren].start = SSPOPIV;
399 if (paren <= rex->lastparen)
400 rex->offs[paren].end = tmps;
401 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
402 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
405 (IV)rex->offs[paren].start,
406 (IV)rex->offs[paren].start_tmp,
407 (IV)rex->offs[paren].end,
408 (paren > rex->lastparen ? "(skipped)" : ""));
413 /* It would seem that the similar code in regtry()
414 * already takes care of this, and in fact it is in
415 * a better location to since this code can #if 0-ed out
416 * but the code in regtry() is needed or otherwise tests
417 * requiring null fields (pat.t#187 and split.t#{13,14}
418 * (as of patchlevel 7877) will fail. Then again,
419 * this code seems to be necessary or otherwise
420 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
421 * --jhi updated by dapm */
422 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
423 if (i > *maxopenparen_p)
424 rex->offs[i].start = -1;
425 rex->offs[i].end = -1;
426 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
427 " \\%" UVuf ": %s ..-1 undeffing\n",
430 (i > *maxopenparen_p) ? "-1" : " "
436 /* restore the parens and associated vars at savestack position ix,
437 * but without popping the stack */
440 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
442 I32 tmpix = PL_savestack_ix;
443 PERL_ARGS_ASSERT_REGCP_RESTORE;
445 PL_savestack_ix = ix;
446 regcppop(rex, maxopenparen_p);
447 PL_savestack_ix = tmpix;
450 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
452 #ifndef PERL_IN_XSUB_RE
455 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
457 /* Returns a boolean as to whether or not 'character' is a member of the
458 * Posix character class given by 'classnum' that should be equivalent to a
459 * value in the typedef '_char_class_number'.
461 * Ideally this could be replaced by a just an array of function pointers
462 * to the C library functions that implement the macros this calls.
463 * However, to compile, the precise function signatures are required, and
464 * these may vary from platform to to platform. To avoid having to figure
465 * out what those all are on each platform, I (khw) am using this method,
466 * which adds an extra layer of function call overhead (unless the C
467 * optimizer strips it away). But we don't particularly care about
468 * performance with locales anyway. */
470 switch ((_char_class_number) classnum) {
471 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
472 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
473 case _CC_ENUM_ASCII: return isASCII_LC(character);
474 case _CC_ENUM_BLANK: return isBLANK_LC(character);
475 case _CC_ENUM_CASED: return isLOWER_LC(character)
476 || isUPPER_LC(character);
477 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
478 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
479 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
480 case _CC_ENUM_LOWER: return isLOWER_LC(character);
481 case _CC_ENUM_PRINT: return isPRINT_LC(character);
482 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
483 case _CC_ENUM_SPACE: return isSPACE_LC(character);
484 case _CC_ENUM_UPPER: return isUPPER_LC(character);
485 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
486 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
487 default: /* VERTSPACE should never occur in locales */
488 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
491 NOT_REACHED; /* NOTREACHED */
498 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character, const U8* e)
500 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
501 * 'character' is a member of the Posix character class given by 'classnum'
502 * that should be equivalent to a value in the typedef
503 * '_char_class_number'.
505 * This just calls isFOO_lc on the code point for the character if it is in
506 * the range 0-255. Outside that range, all characters use Unicode
507 * rules, ignoring any locale. So use the Unicode function if this class
508 * requires a swash, and use the Unicode macro otherwise. */
510 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
512 if (UTF8_IS_INVARIANT(*character)) {
513 return isFOO_lc(classnum, *character);
515 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
516 return isFOO_lc(classnum,
517 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
520 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, e);
522 switch ((_char_class_number) classnum) {
523 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
524 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
525 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
526 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
528 return _invlist_contains_cp(PL_XPosix_ptrs[classnum],
529 utf8_to_uvchr_buf(character, e, NULL));
532 return FALSE; /* Things like CNTRL are always below 256 */
536 S_find_next_ascii(char * s, const char * send, const bool utf8_target)
538 /* Returns the position of the first ASCII byte in the sequence between 's'
539 * and 'send-1' inclusive; returns 'send' if none found */
541 PERL_ARGS_ASSERT_FIND_NEXT_ASCII;
545 if ((STRLEN) (send - s) >= PERL_WORDSIZE
547 /* This term is wordsize if subword; 0 if not */
548 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
551 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
554 /* Process per-byte until reach word boundary. XXX This loop could be
555 * eliminated if we knew that this platform had fast unaligned reads */
556 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
560 s++; /* khw didn't bother creating a separate loop for
564 /* Here, we know we have at least one full word to process. Process
565 * per-word as long as we have at least a full word left */
567 PERL_UINTMAX_T complemented = ~ * (PERL_UINTMAX_T *) s;
568 if (complemented & PERL_VARIANTS_WORD_MASK) {
570 # if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678 \
571 || BYTEORDER == 0x4321 || BYTEORDER == 0x87654321
573 s += _variant_byte_number(complemented);
576 # else /* If weird byte order, drop into next loop to do byte-at-a-time
585 } while (s + PERL_WORDSIZE <= send);
590 /* Process per-character */
612 S_find_next_non_ascii(char * s, const char * send, const bool utf8_target)
614 /* Returns the position of the first non-ASCII byte in the sequence between
615 * 's' and 'send-1' inclusive; returns 'send' if none found */
619 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
623 if ( ! isASCII(*s)) {
631 if ( ! isASCII(*s)) {
642 const U8 * next_non_ascii = NULL;
644 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
645 PERL_UNUSED_ARG(utf8_target);
647 /* On ASCII platforms invariants and ASCII are identical, so if the string
648 * is entirely invariants, there is no non-ASCII character */
649 return (is_utf8_invariant_string_loc((U8 *) s,
653 : (char *) next_non_ascii;
660 S_find_span_end(U8 * s, const U8 * send, const U8 span_byte)
662 /* Returns the position of the first byte in the sequence between 's' and
663 * 'send-1' inclusive that isn't 'span_byte'; returns 'send' if none found.
666 PERL_ARGS_ASSERT_FIND_SPAN_END;
670 if ((STRLEN) (send - s) >= PERL_WORDSIZE
671 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
672 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
674 PERL_UINTMAX_T span_word;
676 /* Process per-byte until reach word boundary. XXX This loop could be
677 * eliminated if we knew that this platform had fast unaligned reads */
678 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
679 if (*s != span_byte) {
685 /* Create a word filled with the bytes we are spanning */
686 span_word = PERL_COUNT_MULTIPLIER * span_byte;
688 /* Process per-word as long as we have at least a full word left */
691 /* Keep going if the whole word is composed of 'span_byte's */
692 if ((* (PERL_UINTMAX_T *) s) == span_word) {
697 /* Here, at least one byte in the word isn't 'span_byte'. */
705 /* This xor leaves 1 bits only in those non-matching bytes */
706 span_word ^= * (PERL_UINTMAX_T *) s;
708 /* Make sure the upper bit of each non-matching byte is set. This
709 * makes each such byte look like an ASCII platform variant byte */
710 span_word |= span_word << 1;
711 span_word |= span_word << 2;
712 span_word |= span_word << 4;
714 /* That reduces the problem to what this function solves */
715 return s + _variant_byte_number(span_word);
719 } while (s + PERL_WORDSIZE <= send);
722 /* Process the straggler bytes beyond the final word boundary */
724 if (*s != span_byte) {
734 S_find_next_masked(U8 * s, const U8 * send, const U8 byte, const U8 mask)
736 /* Returns the position of the first byte in the sequence between 's'
737 * and 'send-1' inclusive that when ANDed with 'mask' yields 'byte';
738 * returns 'send' if none found. It uses word-level operations instead of
739 * byte to speed up the process */
741 PERL_ARGS_ASSERT_FIND_NEXT_MASKED;
744 assert((byte & mask) == byte);
748 if ((STRLEN) (send - s) >= PERL_WORDSIZE
749 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
750 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
752 PERL_UINTMAX_T word_complemented, mask_word;
754 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
755 if (((*s) & mask) == byte) {
761 word_complemented = ~ (PERL_COUNT_MULTIPLIER * byte);
762 mask_word = PERL_COUNT_MULTIPLIER * mask;
765 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
767 /* If 'masked' contains 'byte' within it, anding with the
768 * complement will leave those 8 bits 0 */
769 masked &= word_complemented;
771 /* This causes the most significant bit to be set to 1 for any
772 * bytes in the word that aren't completely 0 */
773 masked |= masked << 1;
774 masked |= masked << 2;
775 masked |= masked << 4;
777 /* The msbits are the same as what marks a byte as variant, so we
778 * can use this mask. If all msbits are 1, the word doesn't
780 if ((masked & PERL_VARIANTS_WORD_MASK) == PERL_VARIANTS_WORD_MASK) {
785 /* Here, the msbit of bytes in the word that aren't 'byte' are 1,
786 * and any that are, are 0. Complement and re-AND to swap that */
788 masked &= PERL_VARIANTS_WORD_MASK;
790 /* This reduces the problem to that solved by this function */
791 s += _variant_byte_number(masked);
794 } while (s + PERL_WORDSIZE <= send);
800 if (((*s) & mask) == byte) {
810 S_find_span_end_mask(U8 * s, const U8 * send, const U8 span_byte, const U8 mask)
812 /* Returns the position of the first byte in the sequence between 's' and
813 * 'send-1' inclusive that when ANDed with 'mask' isn't 'span_byte'.
814 * 'span_byte' should have been ANDed with 'mask' in the call of this
815 * function. Returns 'send' if none found. Works like find_span_end(),
816 * except for the AND */
818 PERL_ARGS_ASSERT_FIND_SPAN_END_MASK;
821 assert((span_byte & mask) == span_byte);
823 if ((STRLEN) (send - s) >= PERL_WORDSIZE
824 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
825 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
827 PERL_UINTMAX_T span_word, mask_word;
829 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
830 if (((*s) & mask) != span_byte) {
836 span_word = PERL_COUNT_MULTIPLIER * span_byte;
837 mask_word = PERL_COUNT_MULTIPLIER * mask;
840 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
842 if (masked == span_word) {
854 masked |= masked << 1;
855 masked |= masked << 2;
856 masked |= masked << 4;
857 return s + _variant_byte_number(masked);
861 } while (s + PERL_WORDSIZE <= send);
865 if (((*s) & mask) != span_byte) {
875 * pregexec and friends
878 #ifndef PERL_IN_XSUB_RE
880 - pregexec - match a regexp against a string
883 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
884 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
885 /* stringarg: the point in the string at which to begin matching */
886 /* strend: pointer to null at end of string */
887 /* strbeg: real beginning of string */
888 /* minend: end of match must be >= minend bytes after stringarg. */
889 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
890 * itself is accessed via the pointers above */
891 /* nosave: For optimizations. */
893 PERL_ARGS_ASSERT_PREGEXEC;
896 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
897 nosave ? 0 : REXEC_COPY_STR);
903 /* re_intuit_start():
905 * Based on some optimiser hints, try to find the earliest position in the
906 * string where the regex could match.
908 * rx: the regex to match against
909 * sv: the SV being matched: only used for utf8 flag; the string
910 * itself is accessed via the pointers below. Note that on
911 * something like an overloaded SV, SvPOK(sv) may be false
912 * and the string pointers may point to something unrelated to
914 * strbeg: real beginning of string
915 * strpos: the point in the string at which to begin matching
916 * strend: pointer to the byte following the last char of the string
917 * flags currently unused; set to 0
918 * data: currently unused; set to NULL
920 * The basic idea of re_intuit_start() is to use some known information
921 * about the pattern, namely:
923 * a) the longest known anchored substring (i.e. one that's at a
924 * constant offset from the beginning of the pattern; but not
925 * necessarily at a fixed offset from the beginning of the
927 * b) the longest floating substring (i.e. one that's not at a constant
928 * offset from the beginning of the pattern);
929 * c) Whether the pattern is anchored to the string; either
930 * an absolute anchor: /^../, or anchored to \n: /^.../m,
931 * or anchored to pos(): /\G/;
932 * d) A start class: a real or synthetic character class which
933 * represents which characters are legal at the start of the pattern;
935 * to either quickly reject the match, or to find the earliest position
936 * within the string at which the pattern might match, thus avoiding
937 * running the full NFA engine at those earlier locations, only to
938 * eventually fail and retry further along.
940 * Returns NULL if the pattern can't match, or returns the address within
941 * the string which is the earliest place the match could occur.
943 * The longest of the anchored and floating substrings is called 'check'
944 * and is checked first. The other is called 'other' and is checked
945 * second. The 'other' substring may not be present. For example,
947 * /(abc|xyz)ABC\d{0,3}DEFG/
951 * check substr (float) = "DEFG", offset 6..9 chars
952 * other substr (anchored) = "ABC", offset 3..3 chars
955 * Be aware that during the course of this function, sometimes 'anchored'
956 * refers to a substring being anchored relative to the start of the
957 * pattern, and sometimes to the pattern itself being anchored relative to
958 * the string. For example:
960 * /\dabc/: "abc" is anchored to the pattern;
961 * /^\dabc/: "abc" is anchored to the pattern and the string;
962 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
963 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
964 * but the pattern is anchored to the string.
968 Perl_re_intuit_start(pTHX_
971 const char * const strbeg,
975 re_scream_pos_data *data)
977 struct regexp *const prog = ReANY(rx);
978 SSize_t start_shift = prog->check_offset_min;
979 /* Should be nonnegative! */
980 SSize_t end_shift = 0;
981 /* current lowest pos in string where the regex can start matching */
982 char *rx_origin = strpos;
984 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
985 U8 other_ix = 1 - prog->substrs->check_ix;
987 char *other_last = strpos;/* latest pos 'other' substr already checked to */
988 char *check_at = NULL; /* check substr found at this pos */
989 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
990 RXi_GET_DECL(prog,progi);
991 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
992 regmatch_info *const reginfo = ®info_buf;
993 GET_RE_DEBUG_FLAGS_DECL;
995 PERL_ARGS_ASSERT_RE_INTUIT_START;
996 PERL_UNUSED_ARG(flags);
997 PERL_UNUSED_ARG(data);
999 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1000 "Intuit: trying to determine minimum start position...\n"));
1002 /* for now, assume that all substr offsets are positive. If at some point
1003 * in the future someone wants to do clever things with lookbehind and
1004 * -ve offsets, they'll need to fix up any code in this function
1005 * which uses these offsets. See the thread beginning
1006 * <20140113145929.GF27210@iabyn.com>
1008 assert(prog->substrs->data[0].min_offset >= 0);
1009 assert(prog->substrs->data[0].max_offset >= 0);
1010 assert(prog->substrs->data[1].min_offset >= 0);
1011 assert(prog->substrs->data[1].max_offset >= 0);
1012 assert(prog->substrs->data[2].min_offset >= 0);
1013 assert(prog->substrs->data[2].max_offset >= 0);
1015 /* for now, assume that if both present, that the floating substring
1016 * doesn't start before the anchored substring.
1017 * If you break this assumption (e.g. doing better optimisations
1018 * with lookahead/behind), then you'll need to audit the code in this
1019 * function carefully first
1022 ! ( (prog->anchored_utf8 || prog->anchored_substr)
1023 && (prog->float_utf8 || prog->float_substr))
1024 || (prog->float_min_offset >= prog->anchored_offset));
1026 /* byte rather than char calculation for efficiency. It fails
1027 * to quickly reject some cases that can't match, but will reject
1028 * them later after doing full char arithmetic */
1029 if (prog->minlen > strend - strpos) {
1030 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1031 " String too short...\n"));
1035 RXp_MATCH_UTF8_set(prog, utf8_target);
1036 reginfo->is_utf8_target = cBOOL(utf8_target);
1037 reginfo->info_aux = NULL;
1038 reginfo->strbeg = strbeg;
1039 reginfo->strend = strend;
1040 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
1041 reginfo->intuit = 1;
1042 /* not actually used within intuit, but zero for safety anyway */
1043 reginfo->poscache_maxiter = 0;
1046 if ((!prog->anchored_utf8 && prog->anchored_substr)
1047 || (!prog->float_utf8 && prog->float_substr))
1048 to_utf8_substr(prog);
1049 check = prog->check_utf8;
1051 if (!prog->check_substr && prog->check_utf8) {
1052 if (! to_byte_substr(prog)) {
1053 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
1056 check = prog->check_substr;
1059 /* dump the various substring data */
1060 DEBUG_OPTIMISE_MORE_r({
1062 for (i=0; i<=2; i++) {
1063 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
1064 : prog->substrs->data[i].substr);
1068 Perl_re_printf( aTHX_
1069 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
1070 " useful=%" IVdf " utf8=%d [%s]\n",
1072 (IV)prog->substrs->data[i].min_offset,
1073 (IV)prog->substrs->data[i].max_offset,
1074 (IV)prog->substrs->data[i].end_shift,
1076 utf8_target ? 1 : 0,
1081 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
1083 /* ml_anch: check after \n?
1085 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
1086 * with /.*.../, these flags will have been added by the
1088 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
1089 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
1091 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
1092 && !(prog->intflags & PREGf_IMPLICIT);
1094 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
1095 /* we are only allowed to match at BOS or \G */
1097 /* trivially reject if there's a BOS anchor and we're not at BOS.
1099 * Note that we don't try to do a similar quick reject for
1100 * \G, since generally the caller will have calculated strpos
1101 * based on pos() and gofs, so the string is already correctly
1102 * anchored by definition; and handling the exceptions would
1103 * be too fiddly (e.g. REXEC_IGNOREPOS).
1105 if ( strpos != strbeg
1106 && (prog->intflags & PREGf_ANCH_SBOL))
1108 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1109 " Not at start...\n"));
1113 /* in the presence of an anchor, the anchored (relative to the
1114 * start of the regex) substr must also be anchored relative
1115 * to strpos. So quickly reject if substr isn't found there.
1116 * This works for \G too, because the caller will already have
1117 * subtracted gofs from pos, and gofs is the offset from the
1118 * \G to the start of the regex. For example, in /.abc\Gdef/,
1119 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
1120 * caller will have set strpos=pos()-4; we look for the substr
1121 * at position pos()-4+1, which lines up with the "a" */
1123 if (prog->check_offset_min == prog->check_offset_max) {
1124 /* Substring at constant offset from beg-of-str... */
1125 SSize_t slen = SvCUR(check);
1126 char *s = HOP3c(strpos, prog->check_offset_min, strend);
1128 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1129 " Looking for check substr at fixed offset %" IVdf "...\n",
1130 (IV)prog->check_offset_min));
1132 if (SvTAIL(check)) {
1133 /* In this case, the regex is anchored at the end too.
1134 * Unless it's a multiline match, the lengths must match
1135 * exactly, give or take a \n. NB: slen >= 1 since
1136 * the last char of check is \n */
1138 && ( strend - s > slen
1139 || strend - s < slen - 1
1140 || (strend - s == slen && strend[-1] != '\n')))
1142 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1143 " String too long...\n"));
1146 /* Now should match s[0..slen-2] */
1149 if (slen && (strend - s < slen
1150 || *SvPVX_const(check) != *s
1151 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
1153 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1154 " String not equal...\n"));
1159 goto success_at_start;
1164 end_shift = prog->check_end_shift;
1166 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
1168 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
1169 (IV)end_shift, RX_PRECOMP(rx));
1174 /* This is the (re)entry point of the main loop in this function.
1175 * The goal of this loop is to:
1176 * 1) find the "check" substring in the region rx_origin..strend
1177 * (adjusted by start_shift / end_shift). If not found, reject
1179 * 2) If it exists, look for the "other" substr too if defined; for
1180 * example, if the check substr maps to the anchored substr, then
1181 * check the floating substr, and vice-versa. If not found, go
1182 * back to (1) with rx_origin suitably incremented.
1183 * 3) If we find an rx_origin position that doesn't contradict
1184 * either of the substrings, then check the possible additional
1185 * constraints on rx_origin of /^.../m or a known start class.
1186 * If these fail, then depending on which constraints fail, jump
1187 * back to here, or to various other re-entry points further along
1188 * that skip some of the first steps.
1189 * 4) If we pass all those tests, update the BmUSEFUL() count on the
1190 * substring. If the start position was determined to be at the
1191 * beginning of the string - so, not rejected, but not optimised,
1192 * since we have to run regmatch from position 0 - decrement the
1193 * BmUSEFUL() count. Otherwise increment it.
1197 /* first, look for the 'check' substring */
1203 DEBUG_OPTIMISE_MORE_r({
1204 Perl_re_printf( aTHX_
1205 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
1206 " Start shift: %" IVdf " End shift %" IVdf
1207 " Real end Shift: %" IVdf "\n",
1208 (IV)(rx_origin - strbeg),
1209 (IV)prog->check_offset_min,
1212 (IV)prog->check_end_shift);
1215 end_point = HOPBACK3(strend, end_shift, rx_origin);
1218 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
1223 /* If the regex is absolutely anchored to either the start of the
1224 * string (SBOL) or to pos() (ANCH_GPOS), then
1225 * check_offset_max represents an upper bound on the string where
1226 * the substr could start. For the ANCH_GPOS case, we assume that
1227 * the caller of intuit will have already set strpos to
1228 * pos()-gofs, so in this case strpos + offset_max will still be
1229 * an upper bound on the substr.
1232 && prog->intflags & PREGf_ANCH
1233 && prog->check_offset_max != SSize_t_MAX)
1235 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
1236 const char * const anchor =
1237 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
1238 SSize_t targ_len = (char*)end_point - anchor;
1240 if (check_len > targ_len) {
1241 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1242 "Target string too short to match required substring...\n"));
1246 /* do a bytes rather than chars comparison. It's conservative;
1247 * so it skips doing the HOP if the result can't possibly end
1248 * up earlier than the old value of end_point.
1250 assert(anchor + check_len <= (char *)end_point);
1251 if (prog->check_offset_max + check_len < targ_len) {
1252 end_point = HOP3lim((U8*)anchor,
1253 prog->check_offset_max,
1254 end_point - check_len
1257 if (end_point < start_point)
1262 check_at = fbm_instr( start_point, end_point,
1263 check, multiline ? FBMrf_MULTILINE : 0);
1265 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1266 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1267 (IV)((char*)start_point - strbeg),
1268 (IV)((char*)end_point - strbeg),
1269 (IV)(check_at ? check_at - strbeg : -1)
1272 /* Update the count-of-usability, remove useless subpatterns,
1276 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1277 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
1278 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
1279 (check_at ? "Found" : "Did not find"),
1280 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
1281 ? "anchored" : "floating"),
1284 (check_at ? " at offset " : "...\n") );
1289 /* set rx_origin to the minimum position where the regex could start
1290 * matching, given the constraint of the just-matched check substring.
1291 * But don't set it lower than previously.
1294 if (check_at - rx_origin > prog->check_offset_max)
1295 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
1296 /* Finish the diagnostic message */
1297 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1298 "%ld (rx_origin now %" IVdf ")...\n",
1299 (long)(check_at - strbeg),
1300 (IV)(rx_origin - strbeg)
1305 /* now look for the 'other' substring if defined */
1307 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
1308 : prog->substrs->data[other_ix].substr)
1310 /* Take into account the "other" substring. */
1314 struct reg_substr_datum *other;
1317 other = &prog->substrs->data[other_ix];
1319 /* if "other" is anchored:
1320 * we've previously found a floating substr starting at check_at.
1321 * This means that the regex origin must lie somewhere
1322 * between min (rx_origin): HOP3(check_at, -check_offset_max)
1323 * and max: HOP3(check_at, -check_offset_min)
1324 * (except that min will be >= strpos)
1325 * So the fixed substr must lie somewhere between
1326 * HOP3(min, anchored_offset)
1327 * HOP3(max, anchored_offset) + SvCUR(substr)
1330 /* if "other" is floating
1331 * Calculate last1, the absolute latest point where the
1332 * floating substr could start in the string, ignoring any
1333 * constraints from the earlier fixed match. It is calculated
1336 * strend - prog->minlen (in chars) is the absolute latest
1337 * position within the string where the origin of the regex
1338 * could appear. The latest start point for the floating
1339 * substr is float_min_offset(*) on from the start of the
1340 * regex. last1 simply combines thee two offsets.
1342 * (*) You might think the latest start point should be
1343 * float_max_offset from the regex origin, and technically
1344 * you'd be correct. However, consider
1346 * Here, float min, max are 3,5 and minlen is 7.
1347 * This can match either
1351 * In the first case, the regex matches minlen chars; in the
1352 * second, minlen+1, in the third, minlen+2.
1353 * In the first case, the floating offset is 3 (which equals
1354 * float_min), in the second, 4, and in the third, 5 (which
1355 * equals float_max). In all cases, the floating string bcd
1356 * can never start more than 4 chars from the end of the
1357 * string, which equals minlen - float_min. As the substring
1358 * starts to match more than float_min from the start of the
1359 * regex, it makes the regex match more than minlen chars,
1360 * and the two cancel each other out. So we can always use
1361 * float_min - minlen, rather than float_max - minlen for the
1362 * latest position in the string.
1364 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1365 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1368 assert(prog->minlen >= other->min_offset);
1369 last1 = HOP3c(strend,
1370 other->min_offset - prog->minlen, strbeg);
1372 if (other_ix) {/* i.e. if (other-is-float) */
1373 /* last is the latest point where the floating substr could
1374 * start, *given* any constraints from the earlier fixed
1375 * match. This constraint is that the floating string starts
1376 * <= float_max_offset chars from the regex origin (rx_origin).
1377 * If this value is less than last1, use it instead.
1379 assert(rx_origin <= last1);
1381 /* this condition handles the offset==infinity case, and
1382 * is a short-cut otherwise. Although it's comparing a
1383 * byte offset to a char length, it does so in a safe way,
1384 * since 1 char always occupies 1 or more bytes,
1385 * so if a string range is (last1 - rx_origin) bytes,
1386 * it will be less than or equal to (last1 - rx_origin)
1387 * chars; meaning it errs towards doing the accurate HOP3
1388 * rather than just using last1 as a short-cut */
1389 (last1 - rx_origin) < other->max_offset
1391 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1394 assert(strpos + start_shift <= check_at);
1395 last = HOP4c(check_at, other->min_offset - start_shift,
1399 s = HOP3c(rx_origin, other->min_offset, strend);
1400 if (s < other_last) /* These positions already checked */
1403 must = utf8_target ? other->utf8_substr : other->substr;
1404 assert(SvPOK(must));
1407 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1413 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1414 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1415 (IV)(from - strbeg),
1421 (unsigned char*)from,
1424 multiline ? FBMrf_MULTILINE : 0
1426 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1427 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1428 (IV)(from - strbeg),
1430 (IV)(s ? s - strbeg : -1)
1436 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1437 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1438 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1439 s ? "Found" : "Contradicts",
1440 other_ix ? "floating" : "anchored",
1441 quoted, RE_SV_TAIL(must));
1446 /* last1 is latest possible substr location. If we didn't
1447 * find it before there, we never will */
1448 if (last >= last1) {
1449 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1450 "; giving up...\n"));
1454 /* try to find the check substr again at a later
1455 * position. Maybe next time we'll find the "other" substr
1457 other_last = HOP3c(last, 1, strend) /* highest failure */;
1459 other_ix /* i.e. if other-is-float */
1460 ? HOP3c(rx_origin, 1, strend)
1461 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1462 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1463 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1464 (other_ix ? "floating" : "anchored"),
1465 (long)(HOP3c(check_at, 1, strend) - strbeg),
1466 (IV)(rx_origin - strbeg)
1471 if (other_ix) { /* if (other-is-float) */
1472 /* other_last is set to s, not s+1, since its possible for
1473 * a floating substr to fail first time, then succeed
1474 * second time at the same floating position; e.g.:
1475 * "-AB--AABZ" =~ /\wAB\d*Z/
1476 * The first time round, anchored and float match at
1477 * "-(AB)--AAB(Z)" then fail on the initial \w character
1478 * class. Second time round, they match at "-AB--A(AB)(Z)".
1483 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1484 other_last = HOP3c(s, 1, strend);
1486 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1487 " at offset %ld (rx_origin now %" IVdf ")...\n",
1489 (IV)(rx_origin - strbeg)
1495 DEBUG_OPTIMISE_MORE_r(
1496 Perl_re_printf( aTHX_
1497 " Check-only match: offset min:%" IVdf " max:%" IVdf
1498 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1499 " strend:%" IVdf "\n",
1500 (IV)prog->check_offset_min,
1501 (IV)prog->check_offset_max,
1502 (IV)(check_at-strbeg),
1503 (IV)(rx_origin-strbeg),
1504 (IV)(rx_origin-check_at),
1510 postprocess_substr_matches:
1512 /* handle the extra constraint of /^.../m if present */
1514 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1517 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1518 " looking for /^/m anchor"));
1520 /* we have failed the constraint of a \n before rx_origin.
1521 * Find the next \n, if any, even if it's beyond the current
1522 * anchored and/or floating substrings. Whether we should be
1523 * scanning ahead for the next \n or the next substr is debatable.
1524 * On the one hand you'd expect rare substrings to appear less
1525 * often than \n's. On the other hand, searching for \n means
1526 * we're effectively flipping between check_substr and "\n" on each
1527 * iteration as the current "rarest" string candidate, which
1528 * means for example that we'll quickly reject the whole string if
1529 * hasn't got a \n, rather than trying every substr position
1533 s = HOP3c(strend, - prog->minlen, strpos);
1534 if (s <= rx_origin ||
1535 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1537 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1538 " Did not find /%s^%s/m...\n",
1539 PL_colors[0], PL_colors[1]));
1543 /* earliest possible origin is 1 char after the \n.
1544 * (since *rx_origin == '\n', it's safe to ++ here rather than
1545 * HOP(rx_origin, 1)) */
1548 if (prog->substrs->check_ix == 0 /* check is anchored */
1549 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1551 /* Position contradicts check-string; either because
1552 * check was anchored (and thus has no wiggle room),
1553 * or check was float and rx_origin is above the float range */
1554 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1555 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1556 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1560 /* if we get here, the check substr must have been float,
1561 * is in range, and we may or may not have had an anchored
1562 * "other" substr which still contradicts */
1563 assert(prog->substrs->check_ix); /* check is float */
1565 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1566 /* whoops, the anchored "other" substr exists, so we still
1567 * contradict. On the other hand, the float "check" substr
1568 * didn't contradict, so just retry the anchored "other"
1570 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1571 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1572 PL_colors[0], PL_colors[1],
1573 (IV)(rx_origin - strbeg + prog->anchored_offset),
1574 (IV)(rx_origin - strbeg)
1576 goto do_other_substr;
1579 /* success: we don't contradict the found floating substring
1580 * (and there's no anchored substr). */
1581 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1582 " Found /%s^%s/m with rx_origin %ld...\n",
1583 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1586 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1587 " (multiline anchor test skipped)\n"));
1593 /* if we have a starting character class, then test that extra constraint.
1594 * (trie stclasses are too expensive to use here, we are better off to
1595 * leave it to regmatch itself) */
1597 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1598 const U8* const str = (U8*)STRING(progi->regstclass);
1600 /* XXX this value could be pre-computed */
1601 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1602 ? (reginfo->is_utf8_pat
1603 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1604 : STR_LEN(progi->regstclass))
1608 /* latest pos that a matching float substr constrains rx start to */
1609 char *rx_max_float = NULL;
1611 /* if the current rx_origin is anchored, either by satisfying an
1612 * anchored substring constraint, or a /^.../m constraint, then we
1613 * can reject the current origin if the start class isn't found
1614 * at the current position. If we have a float-only match, then
1615 * rx_origin is constrained to a range; so look for the start class
1616 * in that range. if neither, then look for the start class in the
1617 * whole rest of the string */
1619 /* XXX DAPM it's not clear what the minlen test is for, and why
1620 * it's not used in the floating case. Nothing in the test suite
1621 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1622 * Here are some old comments, which may or may not be correct:
1624 * minlen == 0 is possible if regstclass is \b or \B,
1625 * and the fixed substr is ''$.
1626 * Since minlen is already taken into account, rx_origin+1 is
1627 * before strend; accidentally, minlen >= 1 guaranties no false
1628 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1629 * 0) below assumes that regstclass does not come from lookahead...
1630 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1631 * This leaves EXACTF-ish only, which are dealt with in
1635 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1636 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1637 else if (prog->float_substr || prog->float_utf8) {
1638 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1639 endpos = HOP3clim(rx_max_float, cl_l, strend);
1644 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1645 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1646 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1647 (IV)start_shift, (IV)(check_at - strbeg),
1648 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1650 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1653 if (endpos == strend) {
1654 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1655 " Could not match STCLASS...\n") );
1658 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1659 " This position contradicts STCLASS...\n") );
1660 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1661 && !(prog->intflags & PREGf_IMPLICIT))
1664 /* Contradict one of substrings */
1665 if (prog->anchored_substr || prog->anchored_utf8) {
1666 if (prog->substrs->check_ix == 1) { /* check is float */
1667 /* Have both, check_string is floating */
1668 assert(rx_origin + start_shift <= check_at);
1669 if (rx_origin + start_shift != check_at) {
1670 /* not at latest position float substr could match:
1671 * Recheck anchored substring, but not floating.
1672 * The condition above is in bytes rather than
1673 * chars for efficiency. It's conservative, in
1674 * that it errs on the side of doing 'goto
1675 * do_other_substr'. In this case, at worst,
1676 * an extra anchored search may get done, but in
1677 * practice the extra fbm_instr() is likely to
1678 * get skipped anyway. */
1679 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1680 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1681 (long)(other_last - strbeg),
1682 (IV)(rx_origin - strbeg)
1684 goto do_other_substr;
1692 /* In the presence of ml_anch, we might be able to
1693 * find another \n without breaking the current float
1696 /* strictly speaking this should be HOP3c(..., 1, ...),
1697 * but since we goto a block of code that's going to
1698 * search for the next \n if any, its safe here */
1700 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1701 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1702 PL_colors[0], PL_colors[1],
1703 (long)(rx_origin - strbeg)) );
1704 goto postprocess_substr_matches;
1707 /* strictly speaking this can never be true; but might
1708 * be if we ever allow intuit without substrings */
1709 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1712 rx_origin = rx_max_float;
1715 /* at this point, any matching substrings have been
1716 * contradicted. Start again... */
1718 rx_origin = HOP3c(rx_origin, 1, strend);
1720 /* uses bytes rather than char calculations for efficiency.
1721 * It's conservative: it errs on the side of doing 'goto restart',
1722 * where there is code that does a proper char-based test */
1723 if (rx_origin + start_shift + end_shift > strend) {
1724 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1725 " Could not match STCLASS...\n") );
1728 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1729 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1730 (prog->substrs->check_ix ? "floating" : "anchored"),
1731 (long)(rx_origin + start_shift - strbeg),
1732 (IV)(rx_origin - strbeg)
1739 if (rx_origin != s) {
1740 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1741 " By STCLASS: moving %ld --> %ld\n",
1742 (long)(rx_origin - strbeg), (long)(s - strbeg))
1746 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1747 " Does not contradict STCLASS...\n");
1752 /* Decide whether using the substrings helped */
1754 if (rx_origin != strpos) {
1755 /* Fixed substring is found far enough so that the match
1756 cannot start at strpos. */
1758 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1759 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1762 /* The found rx_origin position does not prohibit matching at
1763 * strpos, so calling intuit didn't gain us anything. Decrement
1764 * the BmUSEFUL() count on the check substring, and if we reach
1766 if (!(prog->intflags & PREGf_NAUGHTY)
1768 prog->check_utf8 /* Could be deleted already */
1769 && --BmUSEFUL(prog->check_utf8) < 0
1770 && (prog->check_utf8 == prog->float_utf8)
1772 prog->check_substr /* Could be deleted already */
1773 && --BmUSEFUL(prog->check_substr) < 0
1774 && (prog->check_substr == prog->float_substr)
1777 /* If flags & SOMETHING - do not do it many times on the same match */
1778 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1779 /* XXX Does the destruction order has to change with utf8_target? */
1780 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1781 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1782 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1783 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1784 check = NULL; /* abort */
1785 /* XXXX This is a remnant of the old implementation. It
1786 looks wasteful, since now INTUIT can use many
1787 other heuristics. */
1788 prog->extflags &= ~RXf_USE_INTUIT;
1792 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1793 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1794 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1798 fail_finish: /* Substring not found */
1799 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1800 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1802 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1803 PL_colors[4], PL_colors[5]));
1808 #define DECL_TRIE_TYPE(scan) \
1809 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1810 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1811 trie_utf8l, trie_flu8, trie_flu8_latin } \
1812 trie_type = ((scan->flags == EXACT) \
1813 ? (utf8_target ? trie_utf8 : trie_plain) \
1814 : (scan->flags == EXACTL) \
1815 ? (utf8_target ? trie_utf8l : trie_plain) \
1816 : (scan->flags == EXACTFAA) \
1818 ? trie_utf8_exactfa_fold \
1819 : trie_latin_utf8_exactfa_fold) \
1820 : (scan->flags == EXACTFLU8 \
1823 : trie_flu8_latin) \
1826 : trie_latin_utf8_fold)))
1828 /* 'uscan' is set to foldbuf, and incremented, so below the end of uscan is
1829 * 'foldbuf+sizeof(foldbuf)' */
1830 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uc_end, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1833 U8 flags = FOLD_FLAGS_FULL; \
1834 switch (trie_type) { \
1836 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1837 if (UTF8_IS_ABOVE_LATIN1(*uc)) { \
1838 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc_end); \
1840 goto do_trie_utf8_fold; \
1841 case trie_utf8_exactfa_fold: \
1842 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1844 case trie_utf8_fold: \
1845 do_trie_utf8_fold: \
1846 if ( foldlen>0 ) { \
1847 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1852 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc_end, foldbuf, &foldlen, \
1854 len = UTF8SKIP(uc); \
1855 skiplen = UVCHR_SKIP( uvc ); \
1856 foldlen -= skiplen; \
1857 uscan = foldbuf + skiplen; \
1860 case trie_flu8_latin: \
1861 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1862 goto do_trie_latin_utf8_fold; \
1863 case trie_latin_utf8_exactfa_fold: \
1864 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1866 case trie_latin_utf8_fold: \
1867 do_trie_latin_utf8_fold: \
1868 if ( foldlen>0 ) { \
1869 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1875 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1876 skiplen = UVCHR_SKIP( uvc ); \
1877 foldlen -= skiplen; \
1878 uscan = foldbuf + skiplen; \
1882 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1883 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1884 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1888 uvc = utf8n_to_uvchr( (const U8*) uc, uc_end - uc, &len, uniflags ); \
1895 charid = trie->charmap[ uvc ]; \
1899 if (widecharmap) { \
1900 SV** const svpp = hv_fetch(widecharmap, \
1901 (char*)&uvc, sizeof(UV), 0); \
1903 charid = (U16)SvIV(*svpp); \
1908 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1909 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1910 startpos, doutf8, depth)
1912 #define REXEC_FBC_SCAN(UTF8, CODE) \
1914 while (s < strend) { \
1916 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1920 #define REXEC_FBC_CLASS_SCAN(UTF8, COND) \
1922 while (s < strend) { \
1923 REXEC_FBC_CLASS_SCAN_GUTS(UTF8, COND) \
1927 #define REXEC_FBC_CLASS_SCAN_GUTS(UTF8, COND) \
1930 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1931 previous_occurrence_end = s; \
1934 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1937 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1938 if (utf8_target) { \
1939 REXEC_FBC_CLASS_SCAN(1, CONDUTF8); \
1942 REXEC_FBC_CLASS_SCAN(0, COND); \
1945 /* We keep track of where the next character should start after an occurrence
1946 * of the one we're looking for. Knowing that, we can see right away if the
1947 * next occurrence is adjacent to the previous. When 'doevery' is FALSE, we
1948 * don't accept the 2nd and succeeding adjacent occurrences */
1949 #define FBC_CHECK_AND_TRY \
1951 || s != previous_occurrence_end) \
1952 && (reginfo->intuit || regtry(reginfo, &s))) \
1958 /* This differs from the above macros in that it calls a function which returns
1959 * the next occurrence of the thing being looked for in 's'; and 'strend' if
1960 * there is no such occurrence. */
1961 #define REXEC_FBC_FIND_NEXT_SCAN(UTF8, f) \
1962 while (s < strend) { \
1964 if (s >= strend) { \
1969 s += (UTF8) ? UTF8SKIP(s) : 1; \
1970 previous_occurrence_end = s; \
1973 /* The three macros below are slightly different versions of the same logic.
1975 * The first is for /a and /aa when the target string is UTF-8. This can only
1976 * match ascii, but it must advance based on UTF-8. The other two handle the
1977 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1978 * for the boundary (or non-boundary) between a word and non-word character.
1979 * The utf8 and non-utf8 cases have the same logic, but the details must be
1980 * different. Find the "wordness" of the character just prior to this one, and
1981 * compare it with the wordness of this one. If they differ, we have a
1982 * boundary. At the beginning of the string, pretend that the previous
1983 * character was a new-line.
1985 * All these macros uncleanly have side-effects with each other and outside
1986 * variables. So far it's been too much trouble to clean-up
1988 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1989 * a word character or not.
1990 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1992 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1994 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1995 * are looking for a boundary or for a non-boundary. If we are looking for a
1996 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1997 * see if this tentative match actually works, and if so, to quit the loop
1998 * here. And vice-versa if we are looking for a non-boundary.
2000 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
2001 * REXEC_FBC_SCAN loops is a loop invariant, a bool giving the return of
2002 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
2003 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
2004 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
2005 * complement. But in that branch we complement tmp, meaning that at the
2006 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
2007 * which means at the top of the loop in the next iteration, it is
2008 * TEST_NON_UTF8(s-1) */
2009 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
2010 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
2011 tmp = TEST_NON_UTF8(tmp); \
2012 REXEC_FBC_SCAN(1, /* 1=>is-utf8; advances s while s < strend */ \
2013 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
2015 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
2022 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
2023 * TEST_UTF8 is a macro that for the same input code points returns identically
2024 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
2025 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
2026 if (s == reginfo->strbeg) { \
2029 else { /* Back-up to the start of the previous character */ \
2030 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
2031 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
2032 0, UTF8_ALLOW_DEFAULT); \
2034 tmp = TEST_UV(tmp); \
2035 REXEC_FBC_SCAN(1, /* 1=>is-utf8; advances s while s < strend */ \
2036 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
2045 /* Like the above two macros. UTF8_CODE is the complete code for handling
2046 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
2048 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
2049 if (utf8_target) { \
2052 else { /* Not utf8 */ \
2053 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
2054 tmp = TEST_NON_UTF8(tmp); \
2055 REXEC_FBC_SCAN(0, /* 0=>not-utf8; advances s while s < strend */ \
2056 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
2065 /* Here, things have been set up by the previous code so that tmp is the \
2066 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
2067 * utf8ness of the target). We also have to check if this matches against \
2068 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
2069 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
2071 if (tmp == ! TEST_NON_UTF8('\n')) { \
2078 /* This is the macro to use when we want to see if something that looks like it
2079 * could match, actually does, and if so exits the loop */
2080 #define REXEC_FBC_TRYIT \
2081 if ((reginfo->intuit || regtry(reginfo, &s))) \
2084 /* The only difference between the BOUND and NBOUND cases is that
2085 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
2086 * NBOUND. This is accomplished by passing it as either the if or else clause,
2087 * with the other one being empty (PLACEHOLDER is defined as empty).
2089 * The TEST_FOO parameters are for operating on different forms of input, but
2090 * all should be ones that return identically for the same underlying code
2092 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2094 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
2095 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2097 #define FBC_BOUND_A(TEST_NON_UTF8) \
2099 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
2100 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2102 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2104 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2105 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2107 #define FBC_NBOUND_A(TEST_NON_UTF8) \
2109 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2110 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2114 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
2115 IV cp_out = _invlist_search(invlist, cp_in);
2116 assert(cp_out >= 0);
2119 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2120 invmap[S_get_break_val_cp_checked(invlist, cp)]
2122 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2123 invmap[_invlist_search(invlist, cp)]
2126 /* Takes a pointer to an inversion list, a pointer to its corresponding
2127 * inversion map, and a code point, and returns the code point's value
2128 * according to the two arrays. It assumes that all code points have a value.
2129 * This is used as the base macro for macros for particular properties */
2130 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
2131 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
2133 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
2134 * of a code point, returning the value for the first code point in the string.
2135 * And it takes the particular macro name that finds the desired value given a
2136 * code point. Merely convert the UTF-8 to code point and call the cp macro */
2137 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
2138 (__ASSERT_(pos < strend) \
2139 /* Note assumes is valid UTF-8 */ \
2140 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
2142 /* Returns the GCB value for the input code point */
2143 #define getGCB_VAL_CP(cp) \
2144 _generic_GET_BREAK_VAL_CP( \
2149 /* Returns the GCB value for the first code point in the UTF-8 encoded string
2150 * bounded by pos and strend */
2151 #define getGCB_VAL_UTF8(pos, strend) \
2152 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
2154 /* Returns the LB value for the input code point */
2155 #define getLB_VAL_CP(cp) \
2156 _generic_GET_BREAK_VAL_CP( \
2161 /* Returns the LB value for the first code point in the UTF-8 encoded string
2162 * bounded by pos and strend */
2163 #define getLB_VAL_UTF8(pos, strend) \
2164 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
2167 /* Returns the SB value for the input code point */
2168 #define getSB_VAL_CP(cp) \
2169 _generic_GET_BREAK_VAL_CP( \
2174 /* Returns the SB value for the first code point in the UTF-8 encoded string
2175 * bounded by pos and strend */
2176 #define getSB_VAL_UTF8(pos, strend) \
2177 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
2179 /* Returns the WB value for the input code point */
2180 #define getWB_VAL_CP(cp) \
2181 _generic_GET_BREAK_VAL_CP( \
2186 /* Returns the WB value for the first code point in the UTF-8 encoded string
2187 * bounded by pos and strend */
2188 #define getWB_VAL_UTF8(pos, strend) \
2189 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
2191 /* We know what class REx starts with. Try to find this position... */
2192 /* if reginfo->intuit, its a dryrun */
2193 /* annoyingly all the vars in this routine have different names from their counterparts
2194 in regmatch. /grrr */
2196 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
2197 const char *strend, regmatch_info *reginfo)
2201 /* TRUE if x+ need not match at just the 1st pos of run of x's */
2202 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
2204 char *pat_string; /* The pattern's exactish string */
2205 char *pat_end; /* ptr to end char of pat_string */
2206 re_fold_t folder; /* Function for computing non-utf8 folds */
2207 const U8 *fold_array; /* array for folding ords < 256 */
2214 /* In some cases we accept only the first occurence of 'x' in a sequence of
2215 * them. This variable points to just beyond the end of the previous
2216 * occurrence of 'x', hence we can tell if we are in a sequence. (Having
2217 * it point to beyond the 'x' allows us to work for UTF-8 without having to
2219 char * previous_occurrence_end = 0;
2221 I32 tmp; /* Scratch variable */
2222 const bool utf8_target = reginfo->is_utf8_target;
2223 UV utf8_fold_flags = 0;
2224 const bool is_utf8_pat = reginfo->is_utf8_pat;
2225 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
2226 with a result inverts that result, as 0^1 =
2228 _char_class_number classnum;
2230 RXi_GET_DECL(prog,progi);
2232 PERL_ARGS_ASSERT_FIND_BYCLASS;
2234 /* We know what class it must start with. */
2238 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2240 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
2241 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
2248 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2249 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
2251 else if (ANYOF_FLAGS(c)) {
2252 REXEC_FBC_CLASS_SCAN(0, reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
2255 REXEC_FBC_CLASS_SCAN(0, ANYOF_BITMAP_TEST(c, *((U8*)s)));
2259 case ANYOFM: /* ARG() is the base byte; FLAGS() the mask byte */
2260 /* UTF-8ness doesn't matter, so use 0 */
2261 REXEC_FBC_FIND_NEXT_SCAN(0,
2262 (char *) find_next_masked((U8 *) s, (U8 *) strend,
2263 (U8) ARG(c), FLAGS(c)));
2266 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8 patterns */
2267 assert(! is_utf8_pat);
2270 if (is_utf8_pat || utf8_target) {
2271 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2272 goto do_exactf_utf8;
2274 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
2275 folder = foldEQ_latin1; /* /a, except the sharp s one which */
2276 goto do_exactf_non_utf8; /* isn't dealt with by these */
2278 case EXACTF: /* This node only generated for non-utf8 patterns */
2279 assert(! is_utf8_pat);
2281 utf8_fold_flags = 0;
2282 goto do_exactf_utf8;
2284 fold_array = PL_fold;
2286 goto do_exactf_non_utf8;
2289 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2290 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
2291 utf8_fold_flags = FOLDEQ_LOCALE;
2292 goto do_exactf_utf8;
2294 fold_array = PL_fold_locale;
2295 folder = foldEQ_locale;
2296 goto do_exactf_non_utf8;
2300 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2302 goto do_exactf_utf8;
2305 if (! utf8_target) { /* All code points in this node require
2306 UTF-8 to express. */
2309 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
2310 | FOLDEQ_S2_FOLDS_SANE;
2311 goto do_exactf_utf8;
2314 if (is_utf8_pat || utf8_target) {
2315 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
2316 goto do_exactf_utf8;
2319 /* Any 'ss' in the pattern should have been replaced by regcomp,
2320 * so we don't have to worry here about this single special case
2321 * in the Latin1 range */
2322 fold_array = PL_fold_latin1;
2323 folder = foldEQ_latin1;
2327 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
2328 are no glitches with fold-length differences
2329 between the target string and pattern */
2331 /* The idea in the non-utf8 EXACTF* cases is to first find the
2332 * first character of the EXACTF* node and then, if necessary,
2333 * case-insensitively compare the full text of the node. c1 is the
2334 * first character. c2 is its fold. This logic will not work for
2335 * Unicode semantics and the german sharp ss, which hence should
2336 * not be compiled into a node that gets here. */
2337 pat_string = STRING(c);
2338 ln = STR_LEN(c); /* length to match in octets/bytes */
2340 /* We know that we have to match at least 'ln' bytes (which is the
2341 * same as characters, since not utf8). If we have to match 3
2342 * characters, and there are only 2 availabe, we know without
2343 * trying that it will fail; so don't start a match past the
2344 * required minimum number from the far end */
2345 e = HOP3c(strend, -((SSize_t)ln), s);
2350 c2 = fold_array[c1];
2351 if (c1 == c2) { /* If char and fold are the same */
2353 s = (char *) memchr(s, c1, e + 1 - s);
2358 /* Check that the rest of the node matches */
2359 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2360 && (reginfo->intuit || regtry(reginfo, &s)) )
2368 U8 bits_differing = c1 ^ c2;
2370 /* If the folds differ in one bit position only, we can mask to
2371 * match either of them, and can use this faster find method. Both
2372 * ASCII and EBCDIC tend to have their case folds differ in only
2373 * one position, so this is very likely */
2374 if (LIKELY(PL_bitcount[bits_differing] == 1)) {
2375 bits_differing = ~ bits_differing;
2377 s = (char *) find_next_masked((U8 *) s, (U8 *) e + 1,
2378 (c1 & bits_differing), bits_differing);
2383 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2384 && (reginfo->intuit || regtry(reginfo, &s)) )
2391 else { /* Otherwise, stuck with looking byte-at-a-time. This
2392 should actually happen only in EXACTFL nodes */
2394 if ( (*(U8*)s == c1 || *(U8*)s == c2)
2395 && (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2396 && (reginfo->intuit || regtry(reginfo, &s)) )
2410 /* If one of the operands is in utf8, we can't use the simpler folding
2411 * above, due to the fact that many different characters can have the
2412 * same fold, or portion of a fold, or different- length fold */
2413 pat_string = STRING(c);
2414 ln = STR_LEN(c); /* length to match in octets/bytes */
2415 pat_end = pat_string + ln;
2416 lnc = is_utf8_pat /* length to match in characters */
2417 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2420 /* We have 'lnc' characters to match in the pattern, but because of
2421 * multi-character folding, each character in the target can match
2422 * up to 3 characters (Unicode guarantees it will never exceed
2423 * this) if it is utf8-encoded; and up to 2 if not (based on the
2424 * fact that the Latin 1 folds are already determined, and the
2425 * only multi-char fold in that range is the sharp-s folding to
2426 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2427 * string character. Adjust lnc accordingly, rounding up, so that
2428 * if we need to match at least 4+1/3 chars, that really is 5. */
2429 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2430 lnc = (lnc + expansion - 1) / expansion;
2432 /* As in the non-UTF8 case, if we have to match 3 characters, and
2433 * only 2 are left, it's guaranteed to fail, so don't start a
2434 * match that would require us to go beyond the end of the string
2436 e = HOP3c(strend, -((SSize_t)lnc), s);
2438 /* XXX Note that we could recalculate e to stop the loop earlier,
2439 * as the worst case expansion above will rarely be met, and as we
2440 * go along we would usually find that e moves further to the left.
2441 * This would happen only after we reached the point in the loop
2442 * where if there were no expansion we should fail. Unclear if
2443 * worth the expense */
2446 char *my_strend= (char *)strend;
2447 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2448 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2449 && (reginfo->intuit || regtry(reginfo, &s)) )
2453 s += (utf8_target) ? UTF8SKIP(s) : 1;
2459 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2460 if (FLAGS(c) != TRADITIONAL_BOUND) {
2461 if (! IN_UTF8_CTYPE_LOCALE) {
2462 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2463 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2468 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2472 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2473 if (FLAGS(c) != TRADITIONAL_BOUND) {
2474 if (! IN_UTF8_CTYPE_LOCALE) {
2475 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2476 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2481 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2484 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2486 assert(FLAGS(c) == TRADITIONAL_BOUND);
2488 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2491 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2493 assert(FLAGS(c) == TRADITIONAL_BOUND);
2495 FBC_BOUND_A(isWORDCHAR_A);
2498 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2500 assert(FLAGS(c) == TRADITIONAL_BOUND);
2502 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2505 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2507 assert(FLAGS(c) == TRADITIONAL_BOUND);
2509 FBC_NBOUND_A(isWORDCHAR_A);
2513 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2514 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2525 switch((bound_type) FLAGS(c)) {
2526 case TRADITIONAL_BOUND:
2527 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2530 if (s == reginfo->strbeg) {
2531 if (reginfo->intuit || regtry(reginfo, &s))
2536 /* Didn't match. Try at the next position (if there is one) */
2537 s += (utf8_target) ? UTF8SKIP(s) : 1;
2538 if (UNLIKELY(s >= reginfo->strend)) {
2544 GCB_enum before = getGCB_VAL_UTF8(
2546 (U8*)(reginfo->strbeg)),
2547 (U8*) reginfo->strend);
2548 while (s < strend) {
2549 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2550 (U8*) reginfo->strend);
2551 if ( (to_complement ^ isGCB(before,
2553 (U8*) reginfo->strbeg,
2556 && (reginfo->intuit || regtry(reginfo, &s)))
2564 else { /* Not utf8. Everything is a GCB except between CR and
2566 while (s < strend) {
2567 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2568 || UCHARAT(s) != '\n'))
2569 && (reginfo->intuit || regtry(reginfo, &s)))
2577 /* And, since this is a bound, it can match after the final
2578 * character in the string */
2579 if ((reginfo->intuit || regtry(reginfo, &s))) {
2585 if (s == reginfo->strbeg) {
2586 if (reginfo->intuit || regtry(reginfo, &s)) {
2589 s += (utf8_target) ? UTF8SKIP(s) : 1;
2590 if (UNLIKELY(s >= reginfo->strend)) {
2596 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2598 (U8*)(reginfo->strbeg)),
2599 (U8*) reginfo->strend);
2600 while (s < strend) {
2601 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2602 if (to_complement ^ isLB(before,
2604 (U8*) reginfo->strbeg,
2606 (U8*) reginfo->strend,
2608 && (reginfo->intuit || regtry(reginfo, &s)))
2616 else { /* Not utf8. */
2617 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2618 while (s < strend) {
2619 LB_enum after = getLB_VAL_CP((U8) *s);
2620 if (to_complement ^ isLB(before,
2622 (U8*) reginfo->strbeg,
2624 (U8*) reginfo->strend,
2626 && (reginfo->intuit || regtry(reginfo, &s)))
2635 if (reginfo->intuit || regtry(reginfo, &s)) {
2642 if (s == reginfo->strbeg) {
2643 if (reginfo->intuit || regtry(reginfo, &s)) {
2646 s += (utf8_target) ? UTF8SKIP(s) : 1;
2647 if (UNLIKELY(s >= reginfo->strend)) {
2653 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2655 (U8*)(reginfo->strbeg)),
2656 (U8*) reginfo->strend);
2657 while (s < strend) {
2658 SB_enum after = getSB_VAL_UTF8((U8*) s,
2659 (U8*) reginfo->strend);
2660 if ((to_complement ^ isSB(before,
2662 (U8*) reginfo->strbeg,
2664 (U8*) reginfo->strend,
2666 && (reginfo->intuit || regtry(reginfo, &s)))
2674 else { /* Not utf8. */
2675 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2676 while (s < strend) {
2677 SB_enum after = getSB_VAL_CP((U8) *s);
2678 if ((to_complement ^ isSB(before,
2680 (U8*) reginfo->strbeg,
2682 (U8*) reginfo->strend,
2684 && (reginfo->intuit || regtry(reginfo, &s)))
2693 /* Here are at the final position in the target string. The SB
2694 * value is always true here, so matches, depending on other
2696 if (reginfo->intuit || regtry(reginfo, &s)) {
2703 if (s == reginfo->strbeg) {
2704 if (reginfo->intuit || regtry(reginfo, &s)) {
2707 s += (utf8_target) ? UTF8SKIP(s) : 1;
2708 if (UNLIKELY(s >= reginfo->strend)) {
2714 /* We are at a boundary between char_sub_0 and char_sub_1.
2715 * We also keep track of the value for char_sub_-1 as we
2716 * loop through the line. Context may be needed to make a
2717 * determination, and if so, this can save having to
2719 WB_enum previous = WB_UNKNOWN;
2720 WB_enum before = getWB_VAL_UTF8(
2723 (U8*)(reginfo->strbeg)),
2724 (U8*) reginfo->strend);
2725 while (s < strend) {
2726 WB_enum after = getWB_VAL_UTF8((U8*) s,
2727 (U8*) reginfo->strend);
2728 if ((to_complement ^ isWB(previous,
2731 (U8*) reginfo->strbeg,
2733 (U8*) reginfo->strend,
2735 && (reginfo->intuit || regtry(reginfo, &s)))
2744 else { /* Not utf8. */
2745 WB_enum previous = WB_UNKNOWN;
2746 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2747 while (s < strend) {
2748 WB_enum after = getWB_VAL_CP((U8) *s);
2749 if ((to_complement ^ isWB(previous,
2752 (U8*) reginfo->strbeg,
2754 (U8*) reginfo->strend,
2756 && (reginfo->intuit || regtry(reginfo, &s)))
2766 if (reginfo->intuit || regtry(reginfo, &s)) {
2773 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2774 is_LNBREAK_latin1_safe(s, strend)
2779 REXEC_FBC_FIND_NEXT_SCAN(0, find_next_ascii(s, strend, utf8_target));
2784 REXEC_FBC_FIND_NEXT_SCAN(1, find_next_non_ascii(s, strend,
2788 REXEC_FBC_FIND_NEXT_SCAN(0, find_next_non_ascii(s, strend,
2794 /* The argument to all the POSIX node types is the class number to pass to
2795 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2802 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2803 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s, (U8 *) strend)),
2804 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2819 /* The complement of something that matches only ASCII matches all
2820 * non-ASCII, plus everything in ASCII that isn't in the class. */
2821 REXEC_FBC_CLASS_SCAN(1, ! isASCII_utf8_safe(s, strend)
2822 || ! _generic_isCC_A(*s, FLAGS(c)));
2830 /* Don't need to worry about utf8, as it can match only a single
2831 * byte invariant character. But we do anyway for performance reasons,
2832 * as otherwise we would have to examine all the continuation
2835 REXEC_FBC_CLASS_SCAN(1, _generic_isCC_A(*s, FLAGS(c)));
2840 REXEC_FBC_CLASS_SCAN(0, /* 0=>not-utf8 */
2841 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2849 if (! utf8_target) {
2850 REXEC_FBC_CLASS_SCAN(0, /* 0=>not-utf8 */
2851 to_complement ^ cBOOL(_generic_isCC(*s,
2857 classnum = (_char_class_number) FLAGS(c);
2860 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2861 to_complement ^ cBOOL(_invlist_contains_cp(
2862 PL_XPosix_ptrs[classnum],
2863 utf8_to_uvchr_buf((U8 *) s,
2867 case _CC_ENUM_SPACE:
2868 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2869 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2872 case _CC_ENUM_BLANK:
2873 REXEC_FBC_CLASS_SCAN(1,
2874 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2877 case _CC_ENUM_XDIGIT:
2878 REXEC_FBC_CLASS_SCAN(1,
2879 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2882 case _CC_ENUM_VERTSPACE:
2883 REXEC_FBC_CLASS_SCAN(1,
2884 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2887 case _CC_ENUM_CNTRL:
2888 REXEC_FBC_CLASS_SCAN(1,
2889 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2899 /* what trie are we using right now */
2900 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2901 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2902 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2904 const char *last_start = strend - trie->minlen;
2906 const char *real_start = s;
2908 STRLEN maxlen = trie->maxlen;
2910 U8 **points; /* map of where we were in the input string
2911 when reading a given char. For ASCII this
2912 is unnecessary overhead as the relationship
2913 is always 1:1, but for Unicode, especially
2914 case folded Unicode this is not true. */
2915 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2919 GET_RE_DEBUG_FLAGS_DECL;
2921 /* We can't just allocate points here. We need to wrap it in
2922 * an SV so it gets freed properly if there is a croak while
2923 * running the match */
2926 sv_points=newSV(maxlen * sizeof(U8 *));
2927 SvCUR_set(sv_points,
2928 maxlen * sizeof(U8 *));
2929 SvPOK_on(sv_points);
2930 sv_2mortal(sv_points);
2931 points=(U8**)SvPV_nolen(sv_points );
2932 if ( trie_type != trie_utf8_fold
2933 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2936 bitmap=(U8*)trie->bitmap;
2938 bitmap=(U8*)ANYOF_BITMAP(c);
2940 /* this is the Aho-Corasick algorithm modified a touch
2941 to include special handling for long "unknown char" sequences.
2942 The basic idea being that we use AC as long as we are dealing
2943 with a possible matching char, when we encounter an unknown char
2944 (and we have not encountered an accepting state) we scan forward
2945 until we find a legal starting char.
2946 AC matching is basically that of trie matching, except that when
2947 we encounter a failing transition, we fall back to the current
2948 states "fail state", and try the current char again, a process
2949 we repeat until we reach the root state, state 1, or a legal
2950 transition. If we fail on the root state then we can either
2951 terminate if we have reached an accepting state previously, or
2952 restart the entire process from the beginning if we have not.
2955 while (s <= last_start) {
2956 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2964 U8 *uscan = (U8*)NULL;
2965 U8 *leftmost = NULL;
2967 U32 accepted_word= 0;
2971 while ( state && uc <= (U8*)strend ) {
2973 U32 word = aho->states[ state ].wordnum;
2977 DEBUG_TRIE_EXECUTE_r(
2978 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2979 dump_exec_pos( (char *)uc, c, strend, real_start,
2980 (char *)uc, utf8_target, 0 );
2981 Perl_re_printf( aTHX_
2982 " Scanning for legal start char...\n");
2986 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2990 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2996 if (uc >(U8*)last_start) break;
3000 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
3001 if (!leftmost || lpos < leftmost) {
3002 DEBUG_r(accepted_word=word);
3008 points[pointpos++ % maxlen]= uc;
3009 if (foldlen || uc < (U8*)strend) {
3010 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3011 (U8 *) strend, uscan, len, uvc,
3012 charid, foldlen, foldbuf,
3014 DEBUG_TRIE_EXECUTE_r({
3015 dump_exec_pos( (char *)uc, c, strend,
3016 real_start, s, utf8_target, 0);
3017 Perl_re_printf( aTHX_
3018 " Charid:%3u CP:%4" UVxf " ",
3030 word = aho->states[ state ].wordnum;
3032 base = aho->states[ state ].trans.base;
3034 DEBUG_TRIE_EXECUTE_r({
3036 dump_exec_pos( (char *)uc, c, strend, real_start,
3037 s, utf8_target, 0 );
3038 Perl_re_printf( aTHX_
3039 "%sState: %4" UVxf ", word=%" UVxf,
3040 failed ? " Fail transition to " : "",
3041 (UV)state, (UV)word);
3047 ( ((offset = base + charid
3048 - 1 - trie->uniquecharcount)) >= 0)
3049 && ((U32)offset < trie->lasttrans)
3050 && trie->trans[offset].check == state
3051 && (tmp=trie->trans[offset].next))
3053 DEBUG_TRIE_EXECUTE_r(
3054 Perl_re_printf( aTHX_ " - legal\n"));
3059 DEBUG_TRIE_EXECUTE_r(
3060 Perl_re_printf( aTHX_ " - fail\n"));
3062 state = aho->fail[state];
3066 /* we must be accepting here */
3067 DEBUG_TRIE_EXECUTE_r(
3068 Perl_re_printf( aTHX_ " - accepting\n"));
3077 if (!state) state = 1;
3080 if ( aho->states[ state ].wordnum ) {
3081 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
3082 if (!leftmost || lpos < leftmost) {
3083 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
3088 s = (char*)leftmost;
3089 DEBUG_TRIE_EXECUTE_r({
3090 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
3091 (UV)accepted_word, (IV)(s - real_start)
3094 if (reginfo->intuit || regtry(reginfo, &s)) {
3100 DEBUG_TRIE_EXECUTE_r({
3101 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
3104 DEBUG_TRIE_EXECUTE_r(
3105 Perl_re_printf( aTHX_ "No match.\n"));
3114 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
3121 /* set RX_SAVED_COPY, RX_SUBBEG etc.
3122 * flags have same meanings as with regexec_flags() */
3125 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
3132 struct regexp *const prog = ReANY(rx);
3134 if (flags & REXEC_COPY_STR) {
3137 DEBUG_C(Perl_re_printf( aTHX_
3138 "Copy on write: regexp capture, type %d\n",
3140 /* Create a new COW SV to share the match string and store
3141 * in saved_copy, unless the current COW SV in saved_copy
3142 * is valid and suitable for our purpose */
3143 if (( prog->saved_copy
3144 && SvIsCOW(prog->saved_copy)
3145 && SvPOKp(prog->saved_copy)
3148 && SvPVX(sv) == SvPVX(prog->saved_copy)))
3150 /* just reuse saved_copy SV */
3151 if (RXp_MATCH_COPIED(prog)) {
3152 Safefree(prog->subbeg);
3153 RXp_MATCH_COPIED_off(prog);
3157 /* create new COW SV to share string */
3158 RXp_MATCH_COPY_FREE(prog);
3159 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
3161 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
3162 assert (SvPOKp(prog->saved_copy));
3163 prog->sublen = strend - strbeg;
3164 prog->suboffset = 0;
3165 prog->subcoffset = 0;
3170 SSize_t max = strend - strbeg;
3173 if ( (flags & REXEC_COPY_SKIP_POST)
3174 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3175 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
3176 ) { /* don't copy $' part of string */
3179 /* calculate the right-most part of the string covered
3180 * by a capture. Due to lookahead, this may be to
3181 * the right of $&, so we have to scan all captures */
3182 while (n <= prog->lastparen) {
3183 if (prog->offs[n].end > max)
3184 max = prog->offs[n].end;
3188 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
3189 ? prog->offs[0].start
3191 assert(max >= 0 && max <= strend - strbeg);
3194 if ( (flags & REXEC_COPY_SKIP_PRE)
3195 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3196 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
3197 ) { /* don't copy $` part of string */
3200 /* calculate the left-most part of the string covered
3201 * by a capture. Due to lookbehind, this may be to
3202 * the left of $&, so we have to scan all captures */
3203 while (min && n <= prog->lastparen) {
3204 if ( prog->offs[n].start != -1
3205 && prog->offs[n].start < min)
3207 min = prog->offs[n].start;
3211 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
3212 && min > prog->offs[0].end
3214 min = prog->offs[0].end;
3218 assert(min >= 0 && min <= max && min <= strend - strbeg);
3221 if (RXp_MATCH_COPIED(prog)) {
3222 if (sublen > prog->sublen)
3224 (char*)saferealloc(prog->subbeg, sublen+1);
3227 prog->subbeg = (char*)safemalloc(sublen+1);
3228 Copy(strbeg + min, prog->subbeg, sublen, char);
3229 prog->subbeg[sublen] = '\0';
3230 prog->suboffset = min;
3231 prog->sublen = sublen;
3232 RXp_MATCH_COPIED_on(prog);
3234 prog->subcoffset = prog->suboffset;
3235 if (prog->suboffset && utf8_target) {
3236 /* Convert byte offset to chars.
3237 * XXX ideally should only compute this if @-/@+
3238 * has been seen, a la PL_sawampersand ??? */
3240 /* If there's a direct correspondence between the
3241 * string which we're matching and the original SV,
3242 * then we can use the utf8 len cache associated with
3243 * the SV. In particular, it means that under //g,
3244 * sv_pos_b2u() will use the previously cached
3245 * position to speed up working out the new length of
3246 * subcoffset, rather than counting from the start of
3247 * the string each time. This stops
3248 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
3249 * from going quadratic */
3250 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
3251 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
3252 SV_GMAGIC|SV_CONST_RETURN);
3254 prog->subcoffset = utf8_length((U8*)strbeg,
3255 (U8*)(strbeg+prog->suboffset));
3259 RXp_MATCH_COPY_FREE(prog);
3260 prog->subbeg = strbeg;
3261 prog->suboffset = 0;
3262 prog->subcoffset = 0;
3263 prog->sublen = strend - strbeg;
3271 - regexec_flags - match a regexp against a string
3274 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
3275 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
3276 /* stringarg: the point in the string at which to begin matching */
3277 /* strend: pointer to null at end of string */
3278 /* strbeg: real beginning of string */
3279 /* minend: end of match must be >= minend bytes after stringarg. */
3280 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
3281 * itself is accessed via the pointers above */
3282 /* data: May be used for some additional optimizations.
3283 Currently unused. */
3284 /* flags: For optimizations. See REXEC_* in regexp.h */
3287 struct regexp *const prog = ReANY(rx);
3291 SSize_t minlen; /* must match at least this many chars */
3292 SSize_t dontbother = 0; /* how many characters not to try at end */
3293 const bool utf8_target = cBOOL(DO_UTF8(sv));
3295 RXi_GET_DECL(prog,progi);
3296 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
3297 regmatch_info *const reginfo = ®info_buf;
3298 regexp_paren_pair *swap = NULL;
3300 GET_RE_DEBUG_FLAGS_DECL;
3302 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
3303 PERL_UNUSED_ARG(data);
3305 /* Be paranoid... */
3307 Perl_croak(aTHX_ "NULL regexp parameter");
3311 debug_start_match(rx, utf8_target, stringarg, strend,
3315 startpos = stringarg;
3317 /* set these early as they may be used by the HOP macros below */
3318 reginfo->strbeg = strbeg;
3319 reginfo->strend = strend;
3320 reginfo->is_utf8_target = cBOOL(utf8_target);
3322 if (prog->intflags & PREGf_GPOS_SEEN) {
3325 /* set reginfo->ganch, the position where \G can match */
3328 (flags & REXEC_IGNOREPOS)
3329 ? stringarg /* use start pos rather than pos() */
3330 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
3331 /* Defined pos(): */
3332 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
3333 : strbeg; /* pos() not defined; use start of string */
3335 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3336 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
3338 /* in the presence of \G, we may need to start looking earlier in
3339 * the string than the suggested start point of stringarg:
3340 * if prog->gofs is set, then that's a known, fixed minimum
3343 * /ab|c\G/: gofs = 1
3344 * or if the minimum offset isn't known, then we have to go back
3345 * to the start of the string, e.g. /w+\G/
3348 if (prog->intflags & PREGf_ANCH_GPOS) {
3350 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
3352 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
3354 DEBUG_r(Perl_re_printf( aTHX_
3355 "fail: ganch-gofs before earliest possible start\n"));
3360 startpos = reginfo->ganch;
3362 else if (prog->gofs) {
3363 startpos = HOPBACKc(startpos, prog->gofs);
3367 else if (prog->intflags & PREGf_GPOS_FLOAT)
3371 minlen = prog->minlen;
3372 if ((startpos + minlen) > strend || startpos < strbeg) {
3373 DEBUG_r(Perl_re_printf( aTHX_
3374 "Regex match can't succeed, so not even tried\n"));
3378 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3379 * which will call destuctors to reset PL_regmatch_state, free higher
3380 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3381 * regmatch_info_aux_eval */
3383 oldsave = PL_savestack_ix;
3387 if ((prog->extflags & RXf_USE_INTUIT)
3388 && !(flags & REXEC_CHECKED))
3390 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3395 if (prog->extflags & RXf_CHECK_ALL) {
3396 /* we can match based purely on the result of INTUIT.
3397 * Set up captures etc just for $& and $-[0]
3398 * (an intuit-only match wont have $1,$2,..) */
3399 assert(!prog->nparens);
3401 /* s/// doesn't like it if $& is earlier than where we asked it to
3402 * start searching (which can happen on something like /.\G/) */
3403 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3406 /* this should only be possible under \G */
3407 assert(prog->intflags & PREGf_GPOS_SEEN);
3408 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3409 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3413 /* match via INTUIT shouldn't have any captures.
3414 * Let @-, @+, $^N know */
3415 prog->lastparen = prog->lastcloseparen = 0;
3416 RXp_MATCH_UTF8_set(prog, utf8_target);
3417 prog->offs[0].start = s - strbeg;
3418 prog->offs[0].end = utf8_target
3419 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3420 : s - strbeg + prog->minlenret;
3421 if ( !(flags & REXEC_NOT_FIRST) )
3422 S_reg_set_capture_string(aTHX_ rx,
3424 sv, flags, utf8_target);
3430 multiline = prog->extflags & RXf_PMf_MULTILINE;
3432 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3433 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3434 "String too short [regexec_flags]...\n"));
3438 /* Check validity of program. */
3439 if (UCHARAT(progi->program) != REG_MAGIC) {
3440 Perl_croak(aTHX_ "corrupted regexp program");
3443 RXp_MATCH_TAINTED_off(prog);
3444 RXp_MATCH_UTF8_set(prog, utf8_target);
3446 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3447 reginfo->intuit = 0;
3448 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3449 reginfo->warned = FALSE;
3451 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3452 /* see how far we have to get to not match where we matched before */
3453 reginfo->till = stringarg + minend;
3455 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3456 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3457 S_cleanup_regmatch_info_aux has executed (registered by
3458 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3459 magic belonging to this SV.
3460 Not newSVsv, either, as it does not COW.
3462 reginfo->sv = newSV(0);
3463 SvSetSV_nosteal(reginfo->sv, sv);
3464 SAVEFREESV(reginfo->sv);
3467 /* reserve next 2 or 3 slots in PL_regmatch_state:
3468 * slot N+0: may currently be in use: skip it
3469 * slot N+1: use for regmatch_info_aux struct
3470 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3471 * slot N+3: ready for use by regmatch()
3475 regmatch_state *old_regmatch_state;
3476 regmatch_slab *old_regmatch_slab;
3477 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3479 /* on first ever match, allocate first slab */
3480 if (!PL_regmatch_slab) {
3481 Newx(PL_regmatch_slab, 1, regmatch_slab);
3482 PL_regmatch_slab->prev = NULL;
3483 PL_regmatch_slab->next = NULL;
3484 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3487 old_regmatch_state = PL_regmatch_state;
3488 old_regmatch_slab = PL_regmatch_slab;
3490 for (i=0; i <= max; i++) {
3492 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3494 reginfo->info_aux_eval =
3495 reginfo->info_aux->info_aux_eval =
3496 &(PL_regmatch_state->u.info_aux_eval);
3498 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3499 PL_regmatch_state = S_push_slab(aTHX);
3502 /* note initial PL_regmatch_state position; at end of match we'll
3503 * pop back to there and free any higher slabs */
3505 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3506 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3507 reginfo->info_aux->poscache = NULL;
3509 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3511 if ((prog->extflags & RXf_EVAL_SEEN))
3512 S_setup_eval_state(aTHX_ reginfo);
3514 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3517 /* If there is a "must appear" string, look for it. */
3519 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3520 /* We have to be careful. If the previous successful match
3521 was from this regex we don't want a subsequent partially
3522 successful match to clobber the old results.
3523 So when we detect this possibility we add a swap buffer
3524 to the re, and switch the buffer each match. If we fail,
3525 we switch it back; otherwise we leave it swapped.
3528 /* do we need a save destructor here for eval dies? */
3529 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3530 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3531 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3539 if (prog->recurse_locinput)
3540 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3542 /* Simplest case: anchored match need be tried only once, or with
3543 * MBOL, only at the beginning of each line.
3545 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3546 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3547 * match at the start of the string then it won't match anywhere else
3548 * either; while with /.*.../, if it doesn't match at the beginning,
3549 * the earliest it could match is at the start of the next line */
3551 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3554 if (regtry(reginfo, &s))
3557 if (!(prog->intflags & PREGf_ANCH_MBOL))
3560 /* didn't match at start, try at other newline positions */
3563 dontbother = minlen - 1;
3564 end = HOP3c(strend, -dontbother, strbeg) - 1;
3566 /* skip to next newline */
3568 while (s <= end) { /* note it could be possible to match at the end of the string */
3569 /* NB: newlines are the same in unicode as they are in latin */
3572 if (prog->check_substr || prog->check_utf8) {
3573 /* note that with PREGf_IMPLICIT, intuit can only fail
3574 * or return the start position, so it's of limited utility.
3575 * Nevertheless, I made the decision that the potential for
3576 * quick fail was still worth it - DAPM */
3577 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3581 if (regtry(reginfo, &s))
3585 } /* end anchored search */
3587 if (prog->intflags & PREGf_ANCH_GPOS)
3589 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3590 assert(prog->intflags & PREGf_GPOS_SEEN);
3591 /* For anchored \G, the only position it can match from is
3592 * (ganch-gofs); we already set startpos to this above; if intuit
3593 * moved us on from there, we can't possibly succeed */
3594 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3595 if (s == startpos && regtry(reginfo, &s))
3600 /* Messy cases: unanchored match. */
3601 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3602 /* we have /x+whatever/ */
3603 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3609 if (! prog->anchored_utf8) {
3610 to_utf8_substr(prog);
3612 ch = SvPVX_const(prog->anchored_utf8)[0];
3613 REXEC_FBC_SCAN(0, /* 0=>not-utf8 */
3615 DEBUG_EXECUTE_r( did_match = 1 );
3616 if (regtry(reginfo, &s)) goto got_it;
3618 while (s < strend && *s == ch)
3625 if (! prog->anchored_substr) {
3626 if (! to_byte_substr(prog)) {
3627 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3630 ch = SvPVX_const(prog->anchored_substr)[0];
3631 REXEC_FBC_SCAN(0, /* 0=>not-utf8 */
3633 DEBUG_EXECUTE_r( did_match = 1 );
3634 if (regtry(reginfo, &s)) goto got_it;
3636 while (s < strend && *s == ch)
3641 DEBUG_EXECUTE_r(if (!did_match)
3642 Perl_re_printf( aTHX_
3643 "Did not find anchored character...\n")
3646 else if (prog->anchored_substr != NULL
3647 || prog->anchored_utf8 != NULL
3648 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3649 && prog->float_max_offset < strend - s)) {
3654 char *last1; /* Last position checked before */
3658 if (prog->anchored_substr || prog->anchored_utf8) {
3660 if (! prog->anchored_utf8) {
3661 to_utf8_substr(prog);
3663 must = prog->anchored_utf8;
3666 if (! prog->anchored_substr) {
3667 if (! to_byte_substr(prog)) {
3668 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3671 must = prog->anchored_substr;
3673 back_max = back_min = prog->anchored_offset;
3676 if (! prog->float_utf8) {
3677 to_utf8_substr(prog);
3679 must = prog->float_utf8;
3682 if (! prog->float_substr) {
3683 if (! to_byte_substr(prog)) {
3684 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3687 must = prog->float_substr;
3689 back_max = prog->float_max_offset;
3690 back_min = prog->float_min_offset;
3696 last = HOP3c(strend, /* Cannot start after this */
3697 -(SSize_t)(CHR_SVLEN(must)
3698 - (SvTAIL(must) != 0) + back_min), strbeg);
3700 if (s > reginfo->strbeg)
3701 last1 = HOPc(s, -1);
3703 last1 = s - 1; /* bogus */
3705 /* XXXX check_substr already used to find "s", can optimize if
3706 check_substr==must. */
3708 strend = HOPc(strend, -dontbother);
3709 while ( (s <= last) &&
3710 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3711 (unsigned char*)strend, must,
3712 multiline ? FBMrf_MULTILINE : 0)) ) {
3713 DEBUG_EXECUTE_r( did_match = 1 );
3714 if (HOPc(s, -back_max) > last1) {
3715 last1 = HOPc(s, -back_min);
3716 s = HOPc(s, -back_max);
3719 char * const t = (last1 >= reginfo->strbeg)
3720 ? HOPc(last1, 1) : last1 + 1;
3722 last1 = HOPc(s, -back_min);
3726 while (s <= last1) {
3727 if (regtry(reginfo, &s))
3730 s++; /* to break out of outer loop */
3737 while (s <= last1) {
3738 if (regtry(reginfo, &s))
3744 DEBUG_EXECUTE_r(if (!did_match) {
3745 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3746 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3747 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3748 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3749 ? "anchored" : "floating"),
3750 quoted, RE_SV_TAIL(must));
3754 else if ( (c = progi->regstclass) ) {
3756 const OPCODE op = OP(progi->regstclass);
3757 /* don't bother with what can't match */
3758 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3759 strend = HOPc(strend, -(minlen - 1));
3762 SV * const prop = sv_newmortal();
3763 regprop(prog, prop, c, reginfo, NULL);
3765 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3766 s,strend-s,PL_dump_re_max_len);
3767 Perl_re_printf( aTHX_
3768 "Matching stclass %.*s against %s (%d bytes)\n",
3769 (int)SvCUR(prop), SvPVX_const(prop),
3770 quoted, (int)(strend - s));
3773 if (find_byclass(prog, c, s, strend, reginfo))
3775 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3779 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3787 if (! prog->float_utf8) {
3788 to_utf8_substr(prog);
3790 float_real = prog->float_utf8;
3793 if (! prog->float_substr) {
3794 if (! to_byte_substr(prog)) {
3795 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3798 float_real = prog->float_substr;
3801 little = SvPV_const(float_real, len);
3802 if (SvTAIL(float_real)) {
3803 /* This means that float_real contains an artificial \n on
3804 * the end due to the presence of something like this:
3805 * /foo$/ where we can match both "foo" and "foo\n" at the
3806 * end of the string. So we have to compare the end of the
3807 * string first against the float_real without the \n and
3808 * then against the full float_real with the string. We
3809 * have to watch out for cases where the string might be
3810 * smaller than the float_real or the float_real without
3812 char *checkpos= strend - len;
3814 Perl_re_printf( aTHX_
3815 "%sChecking for float_real.%s\n",
3816 PL_colors[4], PL_colors[5]));
3817 if (checkpos + 1 < strbeg) {
3818 /* can't match, even if we remove the trailing \n
3819 * string is too short to match */
3821 Perl_re_printf( aTHX_
3822 "%sString shorter than required trailing substring, cannot match.%s\n",
3823 PL_colors[4], PL_colors[5]));
3825 } else if (memEQ(checkpos + 1, little, len - 1)) {
3826 /* can match, the end of the string matches without the
3828 last = checkpos + 1;
3829 } else if (checkpos < strbeg) {
3830 /* cant match, string is too short when the "\n" is
3833 Perl_re_printf( aTHX_
3834 "%sString does not contain required trailing substring, cannot match.%s\n",
3835 PL_colors[4], PL_colors[5]));
3837 } else if (!multiline) {
3838 /* non multiline match, so compare with the "\n" at the
3839 * end of the string */
3840 if (memEQ(checkpos, little, len)) {
3844 Perl_re_printf( aTHX_
3845 "%sString does not contain required trailing substring, cannot match.%s\n",
3846 PL_colors[4], PL_colors[5]));