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 #define RF_tainted 1 /* tainted information used? */
84 #define RF_warned 2 /* warned about big count? */
86 #define RF_utf8 8 /* Pattern contains multibyte chars? */
88 #define UTF ((PL_reg_flags & RF_utf8) != 0)
90 #define RS_init 1 /* eval environment created */
91 #define RS_set 2 /* replsv value is set */
97 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) : ANYOF_BITMAP_TEST(p,*(c)))
103 #define CHR_SVLEN(sv) (do_utf8 ? sv_len_utf8(sv) : SvCUR(sv))
104 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
106 #define HOPc(pos,off) \
107 (char *)(PL_reg_match_utf8 \
108 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
110 #define HOPBACKc(pos, off) \
111 (char*)(PL_reg_match_utf8\
112 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
113 : (pos - off >= PL_bostr) \
117 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
118 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
120 /* these are unrolled below in the CCC_TRY_XXX defined */
121 #define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
122 if (!CAT2(PL_utf8_,class)) { bool ok; ENTER; save_re_context(); ok=CAT2(is_utf8_,class)((const U8*)str); assert(ok); LEAVE; } } STMT_END
124 /* Doesn't do an assert to verify that is correct */
125 #define LOAD_UTF8_CHARCLASS_NO_CHECK(class) STMT_START { \
126 if (!CAT2(PL_utf8_,class)) { bool ok; ENTER; save_re_context(); ok=CAT2(is_utf8_,class)((const U8*)" "); LEAVE; } } STMT_END
128 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
129 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
130 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
132 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
133 LOAD_UTF8_CHARCLASS(X_begin, " "); \
134 LOAD_UTF8_CHARCLASS(X_non_hangul, "A"); \
135 /* These are utf8 constants, and not utf-ebcdic constants, so the \
136 * assert should likely and hopefully fail on an EBCDIC machine */ \
137 LOAD_UTF8_CHARCLASS(X_extend, "\xcc\x80"); /* U+0300 */ \
139 /* No asserts are done for these, in case called on an early \
140 * Unicode version in which they map to nothing */ \
141 LOAD_UTF8_CHARCLASS_NO_CHECK(X_prepend);/* U+0E40 "\xe0\xb9\x80" */ \
142 LOAD_UTF8_CHARCLASS_NO_CHECK(X_L); /* U+1100 "\xe1\x84\x80" */ \
143 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV); /* U+AC00 "\xea\xb0\x80" */ \
144 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LVT); /* U+AC01 "\xea\xb0\x81" */ \
145 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV_LVT_V);/* U+AC01 "\xea\xb0\x81" */\
146 LOAD_UTF8_CHARCLASS_NO_CHECK(X_T); /* U+11A8 "\xe1\x86\xa8" */ \
147 LOAD_UTF8_CHARCLASS_NO_CHECK(X_V) /* U+1160 "\xe1\x85\xa0" */
150 We dont use PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS as the direct test
151 so that it is possible to override the option here without having to
152 rebuild the entire core. as we are required to do if we change regcomp.h
153 which is where PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS is defined.
155 #if PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS
156 #define BROKEN_UNICODE_CHARCLASS_MAPPINGS
159 #ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
160 #define LOAD_UTF8_CHARCLASS_PERL_WORD() LOAD_UTF8_CHARCLASS_ALNUM()
161 #define LOAD_UTF8_CHARCLASS_PERL_SPACE() LOAD_UTF8_CHARCLASS_SPACE()
162 #define LOAD_UTF8_CHARCLASS_POSIX_DIGIT() LOAD_UTF8_CHARCLASS_DIGIT()
163 #define RE_utf8_perl_word PL_utf8_alnum
164 #define RE_utf8_perl_space PL_utf8_space
165 #define RE_utf8_posix_digit PL_utf8_digit
166 #define perl_word alnum
167 #define perl_space space
168 #define posix_digit digit
170 #define LOAD_UTF8_CHARCLASS_PERL_WORD() LOAD_UTF8_CHARCLASS(perl_word,"a")
171 #define LOAD_UTF8_CHARCLASS_PERL_SPACE() LOAD_UTF8_CHARCLASS(perl_space," ")
172 #define LOAD_UTF8_CHARCLASS_POSIX_DIGIT() LOAD_UTF8_CHARCLASS(posix_digit,"0")
173 #define RE_utf8_perl_word PL_utf8_perl_word
174 #define RE_utf8_perl_space PL_utf8_perl_space
175 #define RE_utf8_posix_digit PL_utf8_posix_digit
179 #define CCC_TRY_AFF(NAME,NAMEL,CLASS,STR,LCFUNC_utf8,FUNC,LCFUNC) \
181 PL_reg_flags |= RF_tainted; \
186 if (do_utf8 && UTF8_IS_CONTINUED(nextchr)) { \
187 if (!CAT2(PL_utf8_,CLASS)) { \
191 ok=CAT2(is_utf8_,CLASS)((const U8*)STR); \
195 if (!(OP(scan) == NAME \
196 ? (bool)swash_fetch(CAT2(PL_utf8_,CLASS), (U8*)locinput, do_utf8) \
197 : LCFUNC_utf8((U8*)locinput))) \
201 locinput += PL_utf8skip[nextchr]; \
202 nextchr = UCHARAT(locinput); \
205 if (!(OP(scan) == NAME ? FUNC(nextchr) : LCFUNC(nextchr))) \
207 nextchr = UCHARAT(++locinput); \
210 #define CCC_TRY_NEG(NAME,NAMEL,CLASS,STR,LCFUNC_utf8,FUNC,LCFUNC) \
212 PL_reg_flags |= RF_tainted; \
215 if (!nextchr && locinput >= PL_regeol) \
217 if (do_utf8 && UTF8_IS_CONTINUED(nextchr)) { \
218 if (!CAT2(PL_utf8_,CLASS)) { \
222 ok=CAT2(is_utf8_,CLASS)((const U8*)STR); \
226 if ((OP(scan) == NAME \
227 ? (bool)swash_fetch(CAT2(PL_utf8_,CLASS), (U8*)locinput, do_utf8) \
228 : LCFUNC_utf8((U8*)locinput))) \
232 locinput += PL_utf8skip[nextchr]; \
233 nextchr = UCHARAT(locinput); \
236 if ((OP(scan) == NAME ? FUNC(nextchr) : LCFUNC(nextchr))) \
238 nextchr = UCHARAT(++locinput); \
245 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
247 /* for use after a quantifier and before an EXACT-like node -- japhy */
248 /* it would be nice to rework regcomp.sym to generate this stuff. sigh */
249 #define JUMPABLE(rn) ( \
251 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
253 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
254 OP(rn) == PLUS || OP(rn) == MINMOD || \
255 OP(rn) == KEEPS || (PL_regkind[OP(rn)] == VERB) || \
256 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
258 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
260 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
263 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
264 we don't need this definition. */
265 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
266 #define IS_TEXTF(rn) ( OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
267 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
270 /* ... so we use this as its faster. */
271 #define IS_TEXT(rn) ( OP(rn)==EXACT )
272 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
273 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
278 Search for mandatory following text node; for lookahead, the text must
279 follow but for lookbehind (rn->flags != 0) we skip to the next step.
281 #define FIND_NEXT_IMPT(rn) STMT_START { \
282 while (JUMPABLE(rn)) { \
283 const OPCODE type = OP(rn); \
284 if (type == SUSPEND || PL_regkind[type] == CURLY) \
285 rn = NEXTOPER(NEXTOPER(rn)); \
286 else if (type == PLUS) \
288 else if (type == IFMATCH) \
289 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
290 else rn += NEXT_OFF(rn); \
295 static void restore_pos(pTHX_ void *arg);
298 S_regcppush(pTHX_ I32 parenfloor)
301 const int retval = PL_savestack_ix;
302 #define REGCP_PAREN_ELEMS 4
303 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
305 GET_RE_DEBUG_FLAGS_DECL;
307 if (paren_elems_to_push < 0)
308 Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
310 #define REGCP_OTHER_ELEMS 7
311 SSGROW(paren_elems_to_push + REGCP_OTHER_ELEMS);
313 for (p = PL_regsize; p > parenfloor; p--) {
314 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
315 SSPUSHINT(PL_regoffs[p].end);
316 SSPUSHINT(PL_regoffs[p].start);
317 SSPUSHPTR(PL_reg_start_tmp[p]);
319 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
320 " saving \\%"UVuf" %"IVdf"(%"IVdf")..%"IVdf"\n",
321 (UV)p, (IV)PL_regoffs[p].start,
322 (IV)(PL_reg_start_tmp[p] - PL_bostr),
323 (IV)PL_regoffs[p].end
326 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
327 SSPUSHPTR(PL_regoffs);
328 SSPUSHINT(PL_regsize);
329 SSPUSHINT(*PL_reglastparen);
330 SSPUSHINT(*PL_reglastcloseparen);
331 SSPUSHPTR(PL_reginput);
332 #define REGCP_FRAME_ELEMS 2
333 /* REGCP_FRAME_ELEMS are part of the REGCP_OTHER_ELEMS and
334 * are needed for the regexp context stack bookkeeping. */
335 SSPUSHINT(paren_elems_to_push + REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
336 SSPUSHINT(SAVEt_REGCONTEXT); /* Magic cookie. */
341 /* These are needed since we do not localize EVAL nodes: */
342 #define REGCP_SET(cp) \
344 PerlIO_printf(Perl_debug_log, \
345 " Setting an EVAL scope, savestack=%"IVdf"\n", \
346 (IV)PL_savestack_ix)); \
349 #define REGCP_UNWIND(cp) \
351 if (cp != PL_savestack_ix) \
352 PerlIO_printf(Perl_debug_log, \
353 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
354 (IV)(cp), (IV)PL_savestack_ix)); \
358 S_regcppop(pTHX_ const regexp *rex)
363 GET_RE_DEBUG_FLAGS_DECL;
365 PERL_ARGS_ASSERT_REGCPPOP;
367 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
369 assert(i == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
370 i = SSPOPINT; /* Parentheses elements to pop. */
371 input = (char *) SSPOPPTR;
372 *PL_reglastcloseparen = SSPOPINT;
373 *PL_reglastparen = SSPOPINT;
374 PL_regsize = SSPOPINT;
375 PL_regoffs=(regexp_paren_pair *) SSPOPPTR;
378 /* Now restore the parentheses context. */
379 for (i -= (REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
380 i > 0; i -= REGCP_PAREN_ELEMS) {
382 U32 paren = (U32)SSPOPINT;
383 PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
384 PL_regoffs[paren].start = SSPOPINT;
386 if (paren <= *PL_reglastparen)
387 PL_regoffs[paren].end = tmps;
389 PerlIO_printf(Perl_debug_log,
390 " restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
391 (UV)paren, (IV)PL_regoffs[paren].start,
392 (IV)(PL_reg_start_tmp[paren] - PL_bostr),
393 (IV)PL_regoffs[paren].end,
394 (paren > *PL_reglastparen ? "(no)" : ""));
398 if (*PL_reglastparen + 1 <= rex->nparens) {
399 PerlIO_printf(Perl_debug_log,
400 " restoring \\%"IVdf"..\\%"IVdf" to undef\n",
401 (IV)(*PL_reglastparen + 1), (IV)rex->nparens);
405 /* It would seem that the similar code in regtry()
406 * already takes care of this, and in fact it is in
407 * a better location to since this code can #if 0-ed out
408 * but the code in regtry() is needed or otherwise tests
409 * requiring null fields (pat.t#187 and split.t#{13,14}
410 * (as of patchlevel 7877) will fail. Then again,
411 * this code seems to be necessary or otherwise
412 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
413 * --jhi updated by dapm */
414 for (i = *PL_reglastparen + 1; i <= rex->nparens; i++) {
416 PL_regoffs[i].start = -1;
417 PL_regoffs[i].end = -1;
423 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
426 * pregexec and friends
429 #ifndef PERL_IN_XSUB_RE
431 - pregexec - match a regexp against a string
434 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
435 char *strbeg, I32 minend, SV *screamer, U32 nosave)
436 /* strend: pointer to null at end of string */
437 /* strbeg: real beginning of string */
438 /* minend: end of match must be >=minend after stringarg. */
439 /* nosave: For optimizations. */
441 PERL_ARGS_ASSERT_PREGEXEC;
444 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
445 nosave ? 0 : REXEC_COPY_STR);
450 * Need to implement the following flags for reg_anch:
452 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
454 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
455 * INTUIT_AUTORITATIVE_ML
456 * INTUIT_ONCE_NOML - Intuit can match in one location only.
459 * Another flag for this function: SECOND_TIME (so that float substrs
460 * with giant delta may be not rechecked).
463 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
465 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
466 Otherwise, only SvCUR(sv) is used to get strbeg. */
468 /* XXXX We assume that strpos is strbeg unless sv. */
470 /* XXXX Some places assume that there is a fixed substring.
471 An update may be needed if optimizer marks as "INTUITable"
472 RExen without fixed substrings. Similarly, it is assumed that
473 lengths of all the strings are no more than minlen, thus they
474 cannot come from lookahead.
475 (Or minlen should take into account lookahead.)
476 NOTE: Some of this comment is not correct. minlen does now take account
477 of lookahead/behind. Further research is required. -- demerphq
481 /* A failure to find a constant substring means that there is no need to make
482 an expensive call to REx engine, thus we celebrate a failure. Similarly,
483 finding a substring too deep into the string means that less calls to
484 regtry() should be needed.
486 REx compiler's optimizer found 4 possible hints:
487 a) Anchored substring;
489 c) Whether we are anchored (beginning-of-line or \G);
490 d) First node (of those at offset 0) which may distingush positions;
491 We use a)b)d) and multiline-part of c), and try to find a position in the
492 string which does not contradict any of them.
495 /* Most of decisions we do here should have been done at compile time.
496 The nodes of the REx which we used for the search should have been
497 deleted from the finite automaton. */
500 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
501 char *strend, const U32 flags, re_scream_pos_data *data)
504 struct regexp *const prog = (struct regexp *)SvANY(rx);
505 register I32 start_shift = 0;
506 /* Should be nonnegative! */
507 register I32 end_shift = 0;
512 const bool do_utf8 = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
514 register char *other_last = NULL; /* other substr checked before this */
515 char *check_at = NULL; /* check substr found at this pos */
516 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
517 RXi_GET_DECL(prog,progi);
519 const char * const i_strpos = strpos;
521 GET_RE_DEBUG_FLAGS_DECL;
523 PERL_ARGS_ASSERT_RE_INTUIT_START;
525 RX_MATCH_UTF8_set(rx,do_utf8);
528 PL_reg_flags |= RF_utf8;
531 debug_start_match(rx, do_utf8, strpos, strend,
532 sv ? "Guessing start of match in sv for"
533 : "Guessing start of match in string for");
536 /* CHR_DIST() would be more correct here but it makes things slow. */
537 if (prog->minlen > strend - strpos) {
538 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
539 "String too short... [re_intuit_start]\n"));
543 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
546 if (!prog->check_utf8 && prog->check_substr)
547 to_utf8_substr(prog);
548 check = prog->check_utf8;
550 if (!prog->check_substr && prog->check_utf8)
551 to_byte_substr(prog);
552 check = prog->check_substr;
554 if (check == &PL_sv_undef) {
555 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
556 "Non-utf8 string cannot match utf8 check string\n"));
559 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
560 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
561 || ( (prog->extflags & RXf_ANCH_BOL)
562 && !multiline ) ); /* Check after \n? */
565 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
566 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
567 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
569 && (strpos != strbeg)) {
570 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
573 if (prog->check_offset_min == prog->check_offset_max &&
574 !(prog->extflags & RXf_CANY_SEEN)) {
575 /* Substring at constant offset from beg-of-str... */
578 s = HOP3c(strpos, prog->check_offset_min, strend);
581 slen = SvCUR(check); /* >= 1 */
583 if ( strend - s > slen || strend - s < slen - 1
584 || (strend - s == slen && strend[-1] != '\n')) {
585 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
588 /* Now should match s[0..slen-2] */
590 if (slen && (*SvPVX_const(check) != *s
592 && memNE(SvPVX_const(check), s, slen)))) {
594 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
598 else if (*SvPVX_const(check) != *s
599 || ((slen = SvCUR(check)) > 1
600 && memNE(SvPVX_const(check), s, slen)))
603 goto success_at_start;
606 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
608 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
609 end_shift = prog->check_end_shift;
612 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
613 - (SvTAIL(check) != 0);
614 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
616 if (end_shift < eshift)
620 else { /* Can match at random position */
623 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
624 end_shift = prog->check_end_shift;
626 /* end shift should be non negative here */
629 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
631 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
632 (IV)end_shift, RX_PRECOMP(prog));
636 /* Find a possible match in the region s..strend by looking for
637 the "check" substring in the region corrected by start/end_shift. */
640 I32 srch_start_shift = start_shift;
641 I32 srch_end_shift = end_shift;
642 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
643 srch_end_shift -= ((strbeg - s) - srch_start_shift);
644 srch_start_shift = strbeg - s;
646 DEBUG_OPTIMISE_MORE_r({
647 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
648 (IV)prog->check_offset_min,
649 (IV)srch_start_shift,
651 (IV)prog->check_end_shift);
654 if (flags & REXEC_SCREAM) {
655 I32 p = -1; /* Internal iterator of scream. */
656 I32 * const pp = data ? data->scream_pos : &p;
658 if (PL_screamfirst[BmRARE(check)] >= 0
659 || ( BmRARE(check) == '\n'
660 && (BmPREVIOUS(check) == SvCUR(check) - 1)
662 s = screaminstr(sv, check,
663 srch_start_shift + (s - strbeg), srch_end_shift, pp, 0);
666 /* we may be pointing at the wrong string */
667 if (s && RXp_MATCH_COPIED(prog))
668 s = strbeg + (s - SvPVX_const(sv));
670 *data->scream_olds = s;
675 if (prog->extflags & RXf_CANY_SEEN) {
676 start_point= (U8*)(s + srch_start_shift);
677 end_point= (U8*)(strend - srch_end_shift);
679 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
680 end_point= HOP3(strend, -srch_end_shift, strbeg);
682 DEBUG_OPTIMISE_MORE_r({
683 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
684 (int)(end_point - start_point),
685 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
689 s = fbm_instr( start_point, end_point,
690 check, multiline ? FBMrf_MULTILINE : 0);
693 /* Update the count-of-usability, remove useless subpatterns,
697 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
698 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
699 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
700 (s ? "Found" : "Did not find"),
701 (check == (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)
702 ? "anchored" : "floating"),
705 (s ? " at offset " : "...\n") );
710 /* Finish the diagnostic message */
711 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
713 /* XXX dmq: first branch is for positive lookbehind...
714 Our check string is offset from the beginning of the pattern.
715 So we need to do any stclass tests offset forward from that
724 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
725 Start with the other substr.
726 XXXX no SCREAM optimization yet - and a very coarse implementation
727 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
728 *always* match. Probably should be marked during compile...
729 Probably it is right to do no SCREAM here...
732 if (do_utf8 ? (prog->float_utf8 && prog->anchored_utf8)
733 : (prog->float_substr && prog->anchored_substr))
735 /* Take into account the "other" substring. */
736 /* XXXX May be hopelessly wrong for UTF... */
739 if (check == (do_utf8 ? prog->float_utf8 : prog->float_substr)) {
742 char * const last = HOP3c(s, -start_shift, strbeg);
744 char * const saved_s = s;
747 t = s - prog->check_offset_max;
748 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
750 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
755 t = HOP3c(t, prog->anchored_offset, strend);
756 if (t < other_last) /* These positions already checked */
758 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
761 /* XXXX It is not documented what units *_offsets are in.
762 We assume bytes, but this is clearly wrong.
763 Meaning this code needs to be carefully reviewed for errors.
767 /* On end-of-str: see comment below. */
768 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
769 if (must == &PL_sv_undef) {
771 DEBUG_r(must = prog->anchored_utf8); /* for debug */
776 HOP3(HOP3(last1, prog->anchored_offset, strend)
777 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
779 multiline ? FBMrf_MULTILINE : 0
782 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
783 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
784 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
785 (s ? "Found" : "Contradicts"),
786 quoted, RE_SV_TAIL(must));
791 if (last1 >= last2) {
792 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
793 ", giving up...\n"));
796 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
797 ", trying floating at offset %ld...\n",
798 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
799 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
800 s = HOP3c(last, 1, strend);
804 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
805 (long)(s - i_strpos)));
806 t = HOP3c(s, -prog->anchored_offset, strbeg);
807 other_last = HOP3c(s, 1, strend);
815 else { /* Take into account the floating substring. */
817 char * const saved_s = s;
820 t = HOP3c(s, -start_shift, strbeg);
822 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
823 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
824 last = HOP3c(t, prog->float_max_offset, strend);
825 s = HOP3c(t, prog->float_min_offset, strend);
828 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
829 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
830 /* fbm_instr() takes into account exact value of end-of-str
831 if the check is SvTAIL(ed). Since false positives are OK,
832 and end-of-str is not later than strend we are OK. */
833 if (must == &PL_sv_undef) {
835 DEBUG_r(must = prog->float_utf8); /* for debug message */
838 s = fbm_instr((unsigned char*)s,
839 (unsigned char*)last + SvCUR(must)
841 must, multiline ? FBMrf_MULTILINE : 0);
843 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
844 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
845 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
846 (s ? "Found" : "Contradicts"),
847 quoted, RE_SV_TAIL(must));
851 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
852 ", giving up...\n"));
855 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
856 ", trying anchored starting at offset %ld...\n",
857 (long)(saved_s + 1 - i_strpos)));
859 s = HOP3c(t, 1, strend);
863 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
864 (long)(s - i_strpos)));
865 other_last = s; /* Fix this later. --Hugo */
875 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
877 DEBUG_OPTIMISE_MORE_r(
878 PerlIO_printf(Perl_debug_log,
879 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
880 (IV)prog->check_offset_min,
881 (IV)prog->check_offset_max,
889 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
891 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
894 /* Fixed substring is found far enough so that the match
895 cannot start at strpos. */
897 if (ml_anch && t[-1] != '\n') {
898 /* Eventually fbm_*() should handle this, but often
899 anchored_offset is not 0, so this check will not be wasted. */
900 /* XXXX In the code below we prefer to look for "^" even in
901 presence of anchored substrings. And we search even
902 beyond the found float position. These pessimizations
903 are historical artefacts only. */
905 while (t < strend - prog->minlen) {
907 if (t < check_at - prog->check_offset_min) {
908 if (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) {
909 /* Since we moved from the found position,
910 we definitely contradict the found anchored
911 substr. Due to the above check we do not
912 contradict "check" substr.
913 Thus we can arrive here only if check substr
914 is float. Redo checking for "other"=="fixed".
917 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
918 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
919 goto do_other_anchored;
921 /* We don't contradict the found floating substring. */
922 /* XXXX Why not check for STCLASS? */
924 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
925 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
928 /* Position contradicts check-string */
929 /* XXXX probably better to look for check-string
930 than for "\n", so one should lower the limit for t? */
931 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
932 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
933 other_last = strpos = s = t + 1;
938 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
939 PL_colors[0], PL_colors[1]));
943 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
944 PL_colors[0], PL_colors[1]));
948 ++BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
951 /* The found string does not prohibit matching at strpos,
952 - no optimization of calling REx engine can be performed,
953 unless it was an MBOL and we are not after MBOL,
954 or a future STCLASS check will fail this. */
956 /* Even in this situation we may use MBOL flag if strpos is offset
957 wrt the start of the string. */
958 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
959 && (strpos != strbeg) && strpos[-1] != '\n'
960 /* May be due to an implicit anchor of m{.*foo} */
961 && !(prog->intflags & PREGf_IMPLICIT))
966 DEBUG_EXECUTE_r( if (ml_anch)
967 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
968 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
971 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
973 prog->check_utf8 /* Could be deleted already */
974 && --BmUSEFUL(prog->check_utf8) < 0
975 && (prog->check_utf8 == prog->float_utf8)
977 prog->check_substr /* Could be deleted already */
978 && --BmUSEFUL(prog->check_substr) < 0
979 && (prog->check_substr == prog->float_substr)
982 /* If flags & SOMETHING - do not do it many times on the same match */
983 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
984 /* XXX Does the destruction order has to change with do_utf8? */
985 SvREFCNT_dec(do_utf8 ? prog->check_utf8 : prog->check_substr);
986 SvREFCNT_dec(do_utf8 ? prog->check_substr : prog->check_utf8);
987 prog->check_substr = prog->check_utf8 = NULL; /* disable */
988 prog->float_substr = prog->float_utf8 = NULL; /* clear */
989 check = NULL; /* abort */
991 /* XXXX This is a remnant of the old implementation. It
992 looks wasteful, since now INTUIT can use many
994 prog->extflags &= ~RXf_USE_INTUIT;
1000 /* Last resort... */
1001 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
1002 /* trie stclasses are too expensive to use here, we are better off to
1003 leave it to regmatch itself */
1004 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1005 /* minlen == 0 is possible if regstclass is \b or \B,
1006 and the fixed substr is ''$.
1007 Since minlen is already taken into account, s+1 is before strend;
1008 accidentally, minlen >= 1 guaranties no false positives at s + 1
1009 even for \b or \B. But (minlen? 1 : 0) below assumes that
1010 regstclass does not come from lookahead... */
1011 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
1012 This leaves EXACTF only, which is dealt with in find_byclass(). */
1013 const U8* const str = (U8*)STRING(progi->regstclass);
1014 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1015 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
1018 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1019 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
1020 else if (prog->float_substr || prog->float_utf8)
1021 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
1025 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf"\n",
1026 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg)));
1029 s = find_byclass(prog, progi->regstclass, s, endpos, NULL);
1032 const char *what = NULL;
1034 if (endpos == strend) {
1035 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1036 "Could not match STCLASS...\n") );
1039 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1040 "This position contradicts STCLASS...\n") );
1041 if ((prog->extflags & RXf_ANCH) && !ml_anch)
1043 /* Contradict one of substrings */
1044 if (prog->anchored_substr || prog->anchored_utf8) {
1045 if ((do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) == check) {
1046 DEBUG_EXECUTE_r( what = "anchored" );
1048 s = HOP3c(t, 1, strend);
1049 if (s + start_shift + end_shift > strend) {
1050 /* XXXX Should be taken into account earlier? */
1051 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1052 "Could not match STCLASS...\n") );
1057 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1058 "Looking for %s substr starting at offset %ld...\n",
1059 what, (long)(s + start_shift - i_strpos)) );
1062 /* Have both, check_string is floating */
1063 if (t + start_shift >= check_at) /* Contradicts floating=check */
1064 goto retry_floating_check;
1065 /* Recheck anchored substring, but not floating... */
1069 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1070 "Looking for anchored substr starting at offset %ld...\n",
1071 (long)(other_last - i_strpos)) );
1072 goto do_other_anchored;
1074 /* Another way we could have checked stclass at the
1075 current position only: */
1080 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1081 "Looking for /%s^%s/m starting at offset %ld...\n",
1082 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
1085 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
1087 /* Check is floating subtring. */
1088 retry_floating_check:
1089 t = check_at - start_shift;
1090 DEBUG_EXECUTE_r( what = "floating" );
1091 goto hop_and_restart;
1094 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1095 "By STCLASS: moving %ld --> %ld\n",
1096 (long)(t - i_strpos), (long)(s - i_strpos))
1100 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1101 "Does not contradict STCLASS...\n");
1106 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
1107 PL_colors[4], (check ? "Guessed" : "Giving up"),
1108 PL_colors[5], (long)(s - i_strpos)) );
1111 fail_finish: /* Substring not found */
1112 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1113 BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1115 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1116 PL_colors[4], PL_colors[5]));
1120 #define DECL_TRIE_TYPE(scan) \
1121 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1122 trie_type = (scan->flags != EXACT) \
1123 ? (do_utf8 ? trie_utf8_fold : (UTF ? trie_latin_utf8_fold : trie_plain)) \
1124 : (do_utf8 ? trie_utf8 : trie_plain)
1126 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1127 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1128 switch (trie_type) { \
1129 case trie_utf8_fold: \
1130 if ( foldlen>0 ) { \
1131 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1136 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1137 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1138 foldlen -= UNISKIP( uvc ); \
1139 uscan = foldbuf + UNISKIP( uvc ); \
1142 case trie_latin_utf8_fold: \
1143 if ( foldlen>0 ) { \
1144 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1150 uvc = to_uni_fold( *(U8*)uc, foldbuf, &foldlen ); \
1151 foldlen -= UNISKIP( uvc ); \
1152 uscan = foldbuf + UNISKIP( uvc ); \
1156 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1163 charid = trie->charmap[ uvc ]; \
1167 if (widecharmap) { \
1168 SV** const svpp = hv_fetch(widecharmap, \
1169 (char*)&uvc, sizeof(UV), 0); \
1171 charid = (U16)SvIV(*svpp); \
1176 #define REXEC_FBC_EXACTISH_CHECK(CoNd) \
1178 char *my_strend= (char *)strend; \
1181 !ibcmp_utf8(s, &my_strend, 0, do_utf8, \
1182 m, NULL, ln, (bool)UTF)) \
1183 && (!reginfo || regtry(reginfo, &s)) ) \
1186 U8 foldbuf[UTF8_MAXBYTES_CASE+1]; \
1187 uvchr_to_utf8(tmpbuf, c); \
1188 f = to_utf8_fold(tmpbuf, foldbuf, &foldlen); \
1190 && (f == c1 || f == c2) \
1192 !ibcmp_utf8(s, &my_strend, 0, do_utf8,\
1193 m, NULL, ln, (bool)UTF)) \
1194 && (!reginfo || regtry(reginfo, &s)) ) \
1200 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1204 && (ln == 1 || !(OP(c) == EXACTF \
1206 : ibcmp_locale(s, m, ln))) \
1207 && (!reginfo || regtry(reginfo, &s)) ) \
1213 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1215 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1221 #define REXEC_FBC_SCAN(CoDe) \
1223 while (s < strend) { \
1229 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1230 REXEC_FBC_UTF8_SCAN( \
1232 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1241 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1244 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1253 #define REXEC_FBC_TRYIT \
1254 if ((!reginfo || regtry(reginfo, &s))) \
1257 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1259 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1262 REXEC_FBC_CLASS_SCAN(CoNd); \
1266 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1269 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1272 REXEC_FBC_CLASS_SCAN(CoNd); \
1276 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1277 PL_reg_flags |= RF_tainted; \
1279 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1282 REXEC_FBC_CLASS_SCAN(CoNd); \
1286 #define DUMP_EXEC_POS(li,s,doutf8) \
1287 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1289 /* We know what class REx starts with. Try to find this position... */
1290 /* if reginfo is NULL, its a dryrun */
1291 /* annoyingly all the vars in this routine have different names from their counterparts
1292 in regmatch. /grrr */
1295 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1296 const char *strend, regmatch_info *reginfo)
1299 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1303 register STRLEN uskip;
1307 register I32 tmp = 1; /* Scratch variable? */
1308 register const bool do_utf8 = PL_reg_match_utf8;
1309 RXi_GET_DECL(prog,progi);
1311 PERL_ARGS_ASSERT_FIND_BYCLASS;
1313 /* We know what class it must start with. */
1317 REXEC_FBC_UTF8_CLASS_SCAN((ANYOF_FLAGS(c) & ANYOF_UNICODE) ||
1318 !UTF8_IS_INVARIANT((U8)s[0]) ?
1319 reginclass(prog, c, (U8*)s, 0, do_utf8) :
1320 REGINCLASS(prog, c, (U8*)s));
1323 while (s < strend) {
1326 if (REGINCLASS(prog, c, (U8*)s) ||
1327 (ANYOF_FOLD_SHARP_S(c, s, strend) &&
1328 /* The assignment of 2 is intentional:
1329 * for the folded sharp s, the skip is 2. */
1330 (skip = SHARP_S_SKIP))) {
1331 if (tmp && (!reginfo || regtry(reginfo, &s)))
1344 if (tmp && (!reginfo || regtry(reginfo, &s)))
1352 ln = STR_LEN(c); /* length to match in octets/bytes */
1353 lnc = (I32) ln; /* length to match in characters */
1355 STRLEN ulen1, ulen2;
1357 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
1358 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
1359 /* used by commented-out code below */
1360 /*const U32 uniflags = UTF8_ALLOW_DEFAULT;*/
1362 /* XXX: Since the node will be case folded at compile
1363 time this logic is a little odd, although im not
1364 sure that its actually wrong. --dmq */
1366 c1 = to_utf8_lower((U8*)m, tmpbuf1, &ulen1);
1367 c2 = to_utf8_upper((U8*)m, tmpbuf2, &ulen2);
1369 /* XXX: This is kinda strange. to_utf8_XYZ returns the
1370 codepoint of the first character in the converted
1371 form, yet originally we did the extra step.
1372 No tests fail by commenting this code out however
1373 so Ive left it out. -- dmq.
1375 c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXBYTES_CASE,
1377 c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXBYTES_CASE,
1382 while (sm < ((U8 *) m + ln)) {
1397 c2 = PL_fold_locale[c1];
1399 e = HOP3c(strend, -((I32)lnc), s);
1401 if (!reginfo && e < s)
1402 e = s; /* Due to minlen logic of intuit() */
1404 /* The idea in the EXACTF* cases is to first find the
1405 * first character of the EXACTF* node and then, if
1406 * necessary, case-insensitively compare the full
1407 * text of the node. The c1 and c2 are the first
1408 * characters (though in Unicode it gets a bit
1409 * more complicated because there are more cases
1410 * than just upper and lower: one needs to use
1411 * the so-called folding case for case-insensitive
1412 * matching (called "loose matching" in Unicode).
1413 * ibcmp_utf8() will do just that. */
1415 if (do_utf8 || UTF) {
1417 U8 tmpbuf [UTF8_MAXBYTES+1];
1420 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1422 /* Upper and lower of 1st char are equal -
1423 * probably not a "letter". */
1426 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1431 REXEC_FBC_EXACTISH_CHECK(c == c1);
1437 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1443 /* Handle some of the three Greek sigmas cases.
1444 * Note that not all the possible combinations
1445 * are handled here: some of them are handled
1446 * by the standard folding rules, and some of
1447 * them (the character class or ANYOF cases)
1448 * are handled during compiletime in
1449 * regexec.c:S_regclass(). */
1450 if (c == (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA ||
1451 c == (UV)UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA)
1452 c = (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA;
1454 REXEC_FBC_EXACTISH_CHECK(c == c1 || c == c2);
1459 /* Neither pattern nor string are UTF8 */
1461 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1463 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1467 PL_reg_flags |= RF_tainted;
1474 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1475 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1477 tmp = ((OP(c) == BOUND ?
1478 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1479 LOAD_UTF8_CHARCLASS_ALNUM();
1480 REXEC_FBC_UTF8_SCAN(
1481 if (tmp == !(OP(c) == BOUND ?
1482 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1483 isALNUM_LC_utf8((U8*)s)))
1491 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1492 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1495 !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
1501 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s)))
1505 PL_reg_flags |= RF_tainted;
1512 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1513 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1515 tmp = ((OP(c) == NBOUND ?
1516 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1517 LOAD_UTF8_CHARCLASS_ALNUM();
1518 REXEC_FBC_UTF8_SCAN(
1519 if (tmp == !(OP(c) == NBOUND ?
1520 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1521 isALNUM_LC_utf8((U8*)s)))
1523 else REXEC_FBC_TRYIT;
1527 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1528 tmp = ((OP(c) == NBOUND ?
1529 isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1532 !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
1534 else REXEC_FBC_TRYIT;
1537 if ((!prog->minlen && !tmp) && (!reginfo || regtry(reginfo, &s)))
1541 REXEC_FBC_CSCAN_PRELOAD(
1542 LOAD_UTF8_CHARCLASS_PERL_WORD(),
1543 swash_fetch(RE_utf8_perl_word, (U8*)s, do_utf8),
1547 REXEC_FBC_CSCAN_TAINT(
1548 isALNUM_LC_utf8((U8*)s),
1552 REXEC_FBC_CSCAN_PRELOAD(
1553 LOAD_UTF8_CHARCLASS_PERL_WORD(),
1554 !swash_fetch(RE_utf8_perl_word, (U8*)s, do_utf8),
1558 REXEC_FBC_CSCAN_TAINT(
1559 !isALNUM_LC_utf8((U8*)s),
1563 REXEC_FBC_CSCAN_PRELOAD(
1564 LOAD_UTF8_CHARCLASS_PERL_SPACE(),
1565 *s == ' ' || swash_fetch(RE_utf8_perl_space,(U8*)s, do_utf8),
1569 REXEC_FBC_CSCAN_TAINT(
1570 *s == ' ' || isSPACE_LC_utf8((U8*)s),
1574 REXEC_FBC_CSCAN_PRELOAD(
1575 LOAD_UTF8_CHARCLASS_PERL_SPACE(),
1576 !(*s == ' ' || swash_fetch(RE_utf8_perl_space,(U8*)s, do_utf8)),
1580 REXEC_FBC_CSCAN_TAINT(
1581 !(*s == ' ' || isSPACE_LC_utf8((U8*)s)),
1585 REXEC_FBC_CSCAN_PRELOAD(
1586 LOAD_UTF8_CHARCLASS_POSIX_DIGIT(),
1587 swash_fetch(RE_utf8_posix_digit,(U8*)s, do_utf8),
1591 REXEC_FBC_CSCAN_TAINT(
1592 isDIGIT_LC_utf8((U8*)s),
1596 REXEC_FBC_CSCAN_PRELOAD(
1597 LOAD_UTF8_CHARCLASS_POSIX_DIGIT(),
1598 !swash_fetch(RE_utf8_posix_digit,(U8*)s, do_utf8),
1602 REXEC_FBC_CSCAN_TAINT(
1603 !isDIGIT_LC_utf8((U8*)s),
1609 is_LNBREAK_latin1(s)
1619 !is_VERTWS_latin1(s)
1624 is_HORIZWS_latin1(s)
1628 !is_HORIZWS_utf8(s),
1629 !is_HORIZWS_latin1(s)
1635 /* what trie are we using right now */
1637 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1639 = (reg_trie_data*)progi->data->data[ aho->trie ];
1640 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1642 const char *last_start = strend - trie->minlen;
1644 const char *real_start = s;
1646 STRLEN maxlen = trie->maxlen;
1648 U8 **points; /* map of where we were in the input string
1649 when reading a given char. For ASCII this
1650 is unnecessary overhead as the relationship
1651 is always 1:1, but for Unicode, especially
1652 case folded Unicode this is not true. */
1653 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1657 GET_RE_DEBUG_FLAGS_DECL;
1659 /* We can't just allocate points here. We need to wrap it in
1660 * an SV so it gets freed properly if there is a croak while
1661 * running the match */
1664 sv_points=newSV(maxlen * sizeof(U8 *));
1665 SvCUR_set(sv_points,
1666 maxlen * sizeof(U8 *));
1667 SvPOK_on(sv_points);
1668 sv_2mortal(sv_points);
1669 points=(U8**)SvPV_nolen(sv_points );
1670 if ( trie_type != trie_utf8_fold
1671 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1674 bitmap=(U8*)trie->bitmap;
1676 bitmap=(U8*)ANYOF_BITMAP(c);
1678 /* this is the Aho-Corasick algorithm modified a touch
1679 to include special handling for long "unknown char"
1680 sequences. The basic idea being that we use AC as long
1681 as we are dealing with a possible matching char, when
1682 we encounter an unknown char (and we have not encountered
1683 an accepting state) we scan forward until we find a legal
1685 AC matching is basically that of trie matching, except
1686 that when we encounter a failing transition, we fall back
1687 to the current states "fail state", and try the current char
1688 again, a process we repeat until we reach the root state,
1689 state 1, or a legal transition. If we fail on the root state
1690 then we can either terminate if we have reached an accepting
1691 state previously, or restart the entire process from the beginning
1695 while (s <= last_start) {
1696 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1704 U8 *uscan = (U8*)NULL;
1705 U8 *leftmost = NULL;
1707 U32 accepted_word= 0;
1711 while ( state && uc <= (U8*)strend ) {
1713 U32 word = aho->states[ state ].wordnum;
1717 DEBUG_TRIE_EXECUTE_r(
1718 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1719 dump_exec_pos( (char *)uc, c, strend, real_start,
1720 (char *)uc, do_utf8 );
1721 PerlIO_printf( Perl_debug_log,
1722 " Scanning for legal start char...\n");
1725 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1730 if (uc >(U8*)last_start) break;
1734 U8 *lpos= points[ (pointpos - trie->wordlen[word-1] ) % maxlen ];
1735 if (!leftmost || lpos < leftmost) {
1736 DEBUG_r(accepted_word=word);
1742 points[pointpos++ % maxlen]= uc;
1743 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1744 uscan, len, uvc, charid, foldlen,
1746 DEBUG_TRIE_EXECUTE_r({
1747 dump_exec_pos( (char *)uc, c, strend, real_start,
1749 PerlIO_printf(Perl_debug_log,
1750 " Charid:%3u CP:%4"UVxf" ",
1756 word = aho->states[ state ].wordnum;
1758 base = aho->states[ state ].trans.base;
1760 DEBUG_TRIE_EXECUTE_r({
1762 dump_exec_pos( (char *)uc, c, strend, real_start,
1764 PerlIO_printf( Perl_debug_log,
1765 "%sState: %4"UVxf", word=%"UVxf,
1766 failed ? " Fail transition to " : "",
1767 (UV)state, (UV)word);
1772 (base + charid > trie->uniquecharcount )
1773 && (base + charid - 1 - trie->uniquecharcount
1775 && trie->trans[base + charid - 1 -
1776 trie->uniquecharcount].check == state
1777 && (tmp=trie->trans[base + charid - 1 -
1778 trie->uniquecharcount ].next))
1780 DEBUG_TRIE_EXECUTE_r(
1781 PerlIO_printf( Perl_debug_log," - legal\n"));
1786 DEBUG_TRIE_EXECUTE_r(
1787 PerlIO_printf( Perl_debug_log," - fail\n"));
1789 state = aho->fail[state];
1793 /* we must be accepting here */
1794 DEBUG_TRIE_EXECUTE_r(
1795 PerlIO_printf( Perl_debug_log," - accepting\n"));
1804 if (!state) state = 1;
1807 if ( aho->states[ state ].wordnum ) {
1808 U8 *lpos = points[ (pointpos - trie->wordlen[aho->states[ state ].wordnum-1]) % maxlen ];
1809 if (!leftmost || lpos < leftmost) {
1810 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
1815 s = (char*)leftmost;
1816 DEBUG_TRIE_EXECUTE_r({
1818 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
1819 (UV)accepted_word, (IV)(s - real_start)
1822 if (!reginfo || regtry(reginfo, &s)) {
1828 DEBUG_TRIE_EXECUTE_r({
1829 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
1832 DEBUG_TRIE_EXECUTE_r(
1833 PerlIO_printf( Perl_debug_log,"No match.\n"));
1842 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1852 - regexec_flags - match a regexp against a string
1855 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
1856 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1857 /* strend: pointer to null at end of string */
1858 /* strbeg: real beginning of string */
1859 /* minend: end of match must be >=minend after stringarg. */
1860 /* data: May be used for some additional optimizations.
1861 Currently its only used, with a U32 cast, for transmitting
1862 the ganch offset when doing a /g match. This will change */
1863 /* nosave: For optimizations. */
1866 struct regexp *const prog = (struct regexp *)SvANY(rx);
1867 /*register*/ char *s;
1868 register regnode *c;
1869 /*register*/ char *startpos = stringarg;
1870 I32 minlen; /* must match at least this many chars */
1871 I32 dontbother = 0; /* how many characters not to try at end */
1872 I32 end_shift = 0; /* Same for the end. */ /* CC */
1873 I32 scream_pos = -1; /* Internal iterator of scream. */
1874 char *scream_olds = NULL;
1875 const bool do_utf8 = (bool)DO_UTF8(sv);
1877 RXi_GET_DECL(prog,progi);
1878 regmatch_info reginfo; /* create some info to pass to regtry etc */
1879 regexp_paren_pair *swap = NULL;
1880 GET_RE_DEBUG_FLAGS_DECL;
1882 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
1883 PERL_UNUSED_ARG(data);
1885 /* Be paranoid... */
1886 if (prog == NULL || startpos == NULL) {
1887 Perl_croak(aTHX_ "NULL regexp parameter");
1891 multiline = prog->extflags & RXf_PMf_MULTILINE;
1892 reginfo.prog = rx; /* Yes, sorry that this is confusing. */
1894 RX_MATCH_UTF8_set(rx, do_utf8);
1896 debug_start_match(rx, do_utf8, startpos, strend,
1900 minlen = prog->minlen;
1902 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
1903 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1904 "String too short [regexec_flags]...\n"));
1909 /* Check validity of program. */
1910 if (UCHARAT(progi->program) != REG_MAGIC) {
1911 Perl_croak(aTHX_ "corrupted regexp program");
1915 PL_reg_eval_set = 0;
1919 PL_reg_flags |= RF_utf8;
1921 /* Mark beginning of line for ^ and lookbehind. */
1922 reginfo.bol = startpos; /* XXX not used ??? */
1926 /* Mark end of line for $ (and such) */
1929 /* see how far we have to get to not match where we matched before */
1930 reginfo.till = startpos+minend;
1932 /* If there is a "must appear" string, look for it. */
1935 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
1937 if (flags & REXEC_IGNOREPOS){ /* Means: check only at start */
1938 reginfo.ganch = startpos + prog->gofs;
1939 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1940 "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
1941 } else if (sv && SvTYPE(sv) >= SVt_PVMG
1943 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
1944 && mg->mg_len >= 0) {
1945 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
1946 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1947 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
1949 if (prog->extflags & RXf_ANCH_GPOS) {
1950 if (s > reginfo.ganch)
1952 s = reginfo.ganch - prog->gofs;
1953 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1954 "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
1960 reginfo.ganch = strbeg + PTR2UV(data);
1961 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1962 "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
1964 } else { /* pos() not defined */
1965 reginfo.ganch = strbeg;
1966 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1967 "GPOS: reginfo.ganch = strbeg\n"));
1970 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
1971 /* We have to be careful. If the previous successful match
1972 was from this regex we don't want a subsequent partially
1973 successful match to clobber the old results.
1974 So when we detect this possibility we add a swap buffer
1975 to the re, and switch the buffer each match. If we fail
1976 we switch it back, otherwise we leave it swapped.
1979 /* do we need a save destructor here for eval dies? */
1980 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
1982 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
1983 re_scream_pos_data d;
1985 d.scream_olds = &scream_olds;
1986 d.scream_pos = &scream_pos;
1987 s = re_intuit_start(rx, sv, s, strend, flags, &d);
1989 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
1990 goto phooey; /* not present */
1996 /* Simplest case: anchored match need be tried only once. */
1997 /* [unless only anchor is BOL and multiline is set] */
1998 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
1999 if (s == startpos && regtry(®info, &startpos))
2001 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
2002 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
2007 dontbother = minlen - 1;
2008 end = HOP3c(strend, -dontbother, strbeg) - 1;
2009 /* for multiline we only have to try after newlines */
2010 if (prog->check_substr || prog->check_utf8) {
2014 if (regtry(®info, &s))
2019 if (prog->extflags & RXf_USE_INTUIT) {
2020 s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
2031 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2032 if (regtry(®info, &s))
2039 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
2041 /* the warning about reginfo.ganch being used without intialization
2042 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
2043 and we only enter this block when the same bit is set. */
2044 char *tmp_s = reginfo.ganch - prog->gofs;
2046 if (tmp_s >= strbeg && regtry(®info, &tmp_s))
2051 /* Messy cases: unanchored match. */
2052 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2053 /* we have /x+whatever/ */
2054 /* it must be a one character string (XXXX Except UTF?) */
2059 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
2060 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2061 ch = SvPVX_const(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)[0];
2066 DEBUG_EXECUTE_r( did_match = 1 );
2067 if (regtry(®info, &s)) goto got_it;
2069 while (s < strend && *s == ch)
2077 DEBUG_EXECUTE_r( did_match = 1 );
2078 if (regtry(®info, &s)) goto got_it;
2080 while (s < strend && *s == ch)
2085 DEBUG_EXECUTE_r(if (!did_match)
2086 PerlIO_printf(Perl_debug_log,
2087 "Did not find anchored character...\n")
2090 else if (prog->anchored_substr != NULL
2091 || prog->anchored_utf8 != NULL
2092 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2093 && prog->float_max_offset < strend - s)) {
2098 char *last1; /* Last position checked before */
2102 if (prog->anchored_substr || prog->anchored_utf8) {
2103 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
2104 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2105 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
2106 back_max = back_min = prog->anchored_offset;
2108 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
2109 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2110 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
2111 back_max = prog->float_max_offset;
2112 back_min = prog->float_min_offset;
2116 if (must == &PL_sv_undef)
2117 /* could not downgrade utf8 check substring, so must fail */
2123 last = HOP3c(strend, /* Cannot start after this */
2124 -(I32)(CHR_SVLEN(must)
2125 - (SvTAIL(must) != 0) + back_min), strbeg);
2128 last1 = HOPc(s, -1);
2130 last1 = s - 1; /* bogus */
2132 /* XXXX check_substr already used to find "s", can optimize if
2133 check_substr==must. */
2135 dontbother = end_shift;
2136 strend = HOPc(strend, -dontbother);
2137 while ( (s <= last) &&
2138 ((flags & REXEC_SCREAM)
2139 ? (s = screaminstr(sv, must, HOP3c(s, back_min, (back_min<0 ? strbeg : strend)) - strbeg,
2140 end_shift, &scream_pos, 0))
2141 : (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2142 (unsigned char*)strend, must,
2143 multiline ? FBMrf_MULTILINE : 0))) ) {
2144 /* we may be pointing at the wrong string */
2145 if ((flags & REXEC_SCREAM) && RXp_MATCH_COPIED(prog))
2146 s = strbeg + (s - SvPVX_const(sv));
2147 DEBUG_EXECUTE_r( did_match = 1 );
2148 if (HOPc(s, -back_max) > last1) {
2149 last1 = HOPc(s, -back_min);
2150 s = HOPc(s, -back_max);
2153 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2155 last1 = HOPc(s, -back_min);
2159 while (s <= last1) {
2160 if (regtry(®info, &s))
2166 while (s <= last1) {
2167 if (regtry(®info, &s))
2173 DEBUG_EXECUTE_r(if (!did_match) {
2174 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
2175 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2176 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2177 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2178 ? "anchored" : "floating"),
2179 quoted, RE_SV_TAIL(must));
2183 else if ( (c = progi->regstclass) ) {
2185 const OPCODE op = OP(progi->regstclass);
2186 /* don't bother with what can't match */
2187 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2188 strend = HOPc(strend, -(minlen - 1));
2191 SV * const prop = sv_newmortal();
2192 regprop(prog, prop, c);
2194 RE_PV_QUOTED_DECL(quoted,do_utf8,PERL_DEBUG_PAD_ZERO(1),
2196 PerlIO_printf(Perl_debug_log,
2197 "Matching stclass %.*s against %s (%d chars)\n",
2198 (int)SvCUR(prop), SvPVX_const(prop),
2199 quoted, (int)(strend - s));
2202 if (find_byclass(prog, c, s, strend, ®info))
2204 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2208 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2213 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
2214 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2215 float_real = do_utf8 ? prog->float_utf8 : prog->float_substr;
2217 if (flags & REXEC_SCREAM) {
2218 last = screaminstr(sv, float_real, s - strbeg,
2219 end_shift, &scream_pos, 1); /* last one */
2221 last = scream_olds; /* Only one occurrence. */
2222 /* we may be pointing at the wrong string */
2223 else if (RXp_MATCH_COPIED(prog))
2224 s = strbeg + (s - SvPVX_const(sv));
2228 const char * const little = SvPV_const(float_real, len);
2230 if (SvTAIL(float_real)) {
2231 if (memEQ(strend - len + 1, little, len - 1))
2232 last = strend - len + 1;
2233 else if (!multiline)
2234 last = memEQ(strend - len, little, len)
2235 ? strend - len : NULL;
2241 last = rninstr(s, strend, little, little + len);
2243 last = strend; /* matching "$" */
2248 PerlIO_printf(Perl_debug_log,
2249 "%sCan't trim the tail, match fails (should not happen)%s\n",
2250 PL_colors[4], PL_colors[5]));
2251 goto phooey; /* Should not happen! */
2253 dontbother = strend - last + prog->float_min_offset;
2255 if (minlen && (dontbother < minlen))
2256 dontbother = minlen - 1;
2257 strend -= dontbother; /* this one's always in bytes! */
2258 /* We don't know much -- general case. */
2261 if (regtry(®info, &s))
2270 if (regtry(®info, &s))
2272 } while (s++ < strend);
2281 RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2283 if (PL_reg_eval_set)
2284 restore_pos(aTHX_ prog);
2285 if (RXp_PAREN_NAMES(prog))
2286 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2288 /* make sure $`, $&, $', and $digit will work later */
2289 if ( !(flags & REXEC_NOT_FIRST) ) {
2290 RX_MATCH_COPY_FREE(rx);
2291 if (flags & REXEC_COPY_STR) {
2292 const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2293 #ifdef PERL_OLD_COPY_ON_WRITE
2295 || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2297 PerlIO_printf(Perl_debug_log,
2298 "Copy on write: regexp capture, type %d\n",
2301 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2302 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2303 assert (SvPOKp(prog->saved_copy));
2307 RX_MATCH_COPIED_on(rx);
2308 s = savepvn(strbeg, i);
2314 prog->subbeg = strbeg;
2315 prog->sublen = PL_regeol - strbeg; /* strend may have been modified */
2322 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2323 PL_colors[4], PL_colors[5]));
2324 if (PL_reg_eval_set)
2325 restore_pos(aTHX_ prog);
2327 /* we failed :-( roll it back */
2328 Safefree(prog->offs);
2337 - regtry - try match at specific point
2339 STATIC I32 /* 0 failure, 1 success */
2340 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2344 REGEXP *const rx = reginfo->prog;
2345 regexp *const prog = (struct regexp *)SvANY(rx);
2346 RXi_GET_DECL(prog,progi);
2347 GET_RE_DEBUG_FLAGS_DECL;
2349 PERL_ARGS_ASSERT_REGTRY;
2351 reginfo->cutpoint=NULL;
2353 if ((prog->extflags & RXf_EVAL_SEEN) && !PL_reg_eval_set) {
2356 PL_reg_eval_set = RS_init;
2357 DEBUG_EXECUTE_r(DEBUG_s(
2358 PerlIO_printf(Perl_debug_log, " setting stack tmpbase at %"IVdf"\n",
2359 (IV)(PL_stack_sp - PL_stack_base));
2362 cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2363 /* Otherwise OP_NEXTSTATE will free whatever on stack now. */
2365 /* Apparently this is not needed, judging by wantarray. */
2366 /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2367 cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2370 /* Make $_ available to executed code. */
2371 if (reginfo->sv != DEFSV) {
2373 DEFSV_set(reginfo->sv);
2376 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2377 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2378 /* prepare for quick setting of pos */
2379 #ifdef PERL_OLD_COPY_ON_WRITE
2380 if (SvIsCOW(reginfo->sv))
2381 sv_force_normal_flags(reginfo->sv, 0);
2383 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2384 &PL_vtbl_mglob, NULL, 0);
2388 PL_reg_oldpos = mg->mg_len;
2389 SAVEDESTRUCTOR_X(restore_pos, prog);
2391 if (!PL_reg_curpm) {
2392 Newxz(PL_reg_curpm, 1, PMOP);
2395 SV* const repointer = &PL_sv_undef;
2396 /* this regexp is also owned by the new PL_reg_curpm, which
2397 will try to free it. */
2398 av_push(PL_regex_padav, repointer);
2399 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2400 PL_regex_pad = AvARRAY(PL_regex_padav);
2405 /* It seems that non-ithreads works both with and without this code.
2406 So for efficiency reasons it seems best not to have the code
2407 compiled when it is not needed. */
2408 /* This is safe against NULLs: */
2409 ReREFCNT_dec(PM_GETRE(PL_reg_curpm));
2410 /* PM_reg_curpm owns a reference to this regexp. */
2413 PM_SETRE(PL_reg_curpm, rx);
2414 PL_reg_oldcurpm = PL_curpm;
2415 PL_curpm = PL_reg_curpm;
2416 if (RXp_MATCH_COPIED(prog)) {
2417 /* Here is a serious problem: we cannot rewrite subbeg,
2418 since it may be needed if this match fails. Thus
2419 $` inside (?{}) could fail... */
2420 PL_reg_oldsaved = prog->subbeg;
2421 PL_reg_oldsavedlen = prog->sublen;
2422 #ifdef PERL_OLD_COPY_ON_WRITE
2423 PL_nrs = prog->saved_copy;
2425 RXp_MATCH_COPIED_off(prog);
2428 PL_reg_oldsaved = NULL;
2429 prog->subbeg = PL_bostr;
2430 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2432 DEBUG_EXECUTE_r(PL_reg_starttry = *startpos);
2433 prog->offs[0].start = *startpos - PL_bostr;
2434 PL_reginput = *startpos;
2435 PL_reglastparen = &prog->lastparen;
2436 PL_reglastcloseparen = &prog->lastcloseparen;
2437 prog->lastparen = 0;
2438 prog->lastcloseparen = 0;
2440 PL_regoffs = prog->offs;
2441 if (PL_reg_start_tmpl <= prog->nparens) {
2442 PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2443 if(PL_reg_start_tmp)
2444 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2446 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2449 /* XXXX What this code is doing here?!!! There should be no need
2450 to do this again and again, PL_reglastparen should take care of
2453 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2454 * Actually, the code in regcppop() (which Ilya may be meaning by
2455 * PL_reglastparen), is not needed at all by the test suite
2456 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2457 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2458 * Meanwhile, this code *is* needed for the
2459 * above-mentioned test suite tests to succeed. The common theme
2460 * on those tests seems to be returning null fields from matches.
2461 * --jhi updated by dapm */
2463 if (prog->nparens) {
2464 regexp_paren_pair *pp = PL_regoffs;
2466 for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2474 if (regmatch(reginfo, progi->program + 1)) {
2475 PL_regoffs[0].end = PL_reginput - PL_bostr;
2478 if (reginfo->cutpoint)
2479 *startpos= reginfo->cutpoint;
2480 REGCP_UNWIND(lastcp);
2485 #define sayYES goto yes
2486 #define sayNO goto no
2487 #define sayNO_SILENT goto no_silent
2489 /* we dont use STMT_START/END here because it leads to
2490 "unreachable code" warnings, which are bogus, but distracting. */
2491 #define CACHEsayNO \
2492 if (ST.cache_mask) \
2493 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2496 /* this is used to determine how far from the left messages like
2497 'failed...' are printed. It should be set such that messages
2498 are inline with the regop output that created them.
2500 #define REPORT_CODE_OFF 32
2503 /* Make sure there is a test for this +1 options in re_tests */
2504 #define TRIE_INITAL_ACCEPT_BUFFLEN 4;
2506 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2507 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2509 #define SLAB_FIRST(s) (&(s)->states[0])
2510 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2512 /* grab a new slab and return the first slot in it */
2514 STATIC regmatch_state *
2517 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2520 regmatch_slab *s = PL_regmatch_slab->next;
2522 Newx(s, 1, regmatch_slab);
2523 s->prev = PL_regmatch_slab;
2525 PL_regmatch_slab->next = s;
2527 PL_regmatch_slab = s;
2528 return SLAB_FIRST(s);
2532 /* push a new state then goto it */
2534 #define PUSH_STATE_GOTO(state, node) \
2536 st->resume_state = state; \
2539 /* push a new state with success backtracking, then goto it */
2541 #define PUSH_YES_STATE_GOTO(state, node) \
2543 st->resume_state = state; \
2544 goto push_yes_state;
2550 regmatch() - main matching routine
2552 This is basically one big switch statement in a loop. We execute an op,
2553 set 'next' to point the next op, and continue. If we come to a point which
2554 we may need to backtrack to on failure such as (A|B|C), we push a
2555 backtrack state onto the backtrack stack. On failure, we pop the top
2556 state, and re-enter the loop at the state indicated. If there are no more
2557 states to pop, we return failure.
2559 Sometimes we also need to backtrack on success; for example /A+/, where
2560 after successfully matching one A, we need to go back and try to
2561 match another one; similarly for lookahead assertions: if the assertion
2562 completes successfully, we backtrack to the state just before the assertion
2563 and then carry on. In these cases, the pushed state is marked as
2564 'backtrack on success too'. This marking is in fact done by a chain of
2565 pointers, each pointing to the previous 'yes' state. On success, we pop to
2566 the nearest yes state, discarding any intermediate failure-only states.
2567 Sometimes a yes state is pushed just to force some cleanup code to be
2568 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2569 it to free the inner regex.
2571 Note that failure backtracking rewinds the cursor position, while
2572 success backtracking leaves it alone.
2574 A pattern is complete when the END op is executed, while a subpattern
2575 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2576 ops trigger the "pop to last yes state if any, otherwise return true"
2579 A common convention in this function is to use A and B to refer to the two
2580 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2581 the subpattern to be matched possibly multiple times, while B is the entire
2582 rest of the pattern. Variable and state names reflect this convention.
2584 The states in the main switch are the union of ops and failure/success of
2585 substates associated with with that op. For example, IFMATCH is the op
2586 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2587 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2588 successfully matched A and IFMATCH_A_fail is a state saying that we have
2589 just failed to match A. Resume states always come in pairs. The backtrack
2590 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2591 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2592 on success or failure.
2594 The struct that holds a backtracking state is actually a big union, with
2595 one variant for each major type of op. The variable st points to the
2596 top-most backtrack struct. To make the code clearer, within each
2597 block of code we #define ST to alias the relevant union.
2599 Here's a concrete example of a (vastly oversimplified) IFMATCH
2605 #define ST st->u.ifmatch
2607 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2608 ST.foo = ...; // some state we wish to save
2610 // push a yes backtrack state with a resume value of
2611 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2613 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2616 case IFMATCH_A: // we have successfully executed A; now continue with B
2618 bar = ST.foo; // do something with the preserved value
2621 case IFMATCH_A_fail: // A failed, so the assertion failed
2622 ...; // do some housekeeping, then ...
2623 sayNO; // propagate the failure
2630 For any old-timers reading this who are familiar with the old recursive
2631 approach, the code above is equivalent to:
2633 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2642 ...; // do some housekeeping, then ...
2643 sayNO; // propagate the failure
2646 The topmost backtrack state, pointed to by st, is usually free. If you
2647 want to claim it, populate any ST.foo fields in it with values you wish to
2648 save, then do one of
2650 PUSH_STATE_GOTO(resume_state, node);
2651 PUSH_YES_STATE_GOTO(resume_state, node);
2653 which sets that backtrack state's resume value to 'resume_state', pushes a
2654 new free entry to the top of the backtrack stack, then goes to 'node'.
2655 On backtracking, the free slot is popped, and the saved state becomes the
2656 new free state. An ST.foo field in this new top state can be temporarily
2657 accessed to retrieve values, but once the main loop is re-entered, it
2658 becomes available for reuse.
2660 Note that the depth of the backtrack stack constantly increases during the
2661 left-to-right execution of the pattern, rather than going up and down with
2662 the pattern nesting. For example the stack is at its maximum at Z at the
2663 end of the pattern, rather than at X in the following:
2665 /(((X)+)+)+....(Y)+....Z/
2667 The only exceptions to this are lookahead/behind assertions and the cut,
2668 (?>A), which pop all the backtrack states associated with A before
2671 Bascktrack state structs are allocated in slabs of about 4K in size.
2672 PL_regmatch_state and st always point to the currently active state,
2673 and PL_regmatch_slab points to the slab currently containing
2674 PL_regmatch_state. The first time regmatch() is called, the first slab is
2675 allocated, and is never freed until interpreter destruction. When the slab
2676 is full, a new one is allocated and chained to the end. At exit from
2677 regmatch(), slabs allocated since entry are freed.
2682 #define DEBUG_STATE_pp(pp) \
2684 DUMP_EXEC_POS(locinput, scan, do_utf8); \
2685 PerlIO_printf(Perl_debug_log, \
2686 " %*s"pp" %s%s%s%s%s\n", \
2688 PL_reg_name[st->resume_state], \
2689 ((st==yes_state||st==mark_state) ? "[" : ""), \
2690 ((st==yes_state) ? "Y" : ""), \
2691 ((st==mark_state) ? "M" : ""), \
2692 ((st==yes_state||st==mark_state) ? "]" : "") \
2697 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2702 S_debug_start_match(pTHX_ const REGEXP *prog, const bool do_utf8,
2703 const char *start, const char *end, const char *blurb)
2705 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2707 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2712 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2713 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2715 RE_PV_QUOTED_DECL(s1, do_utf8, PERL_DEBUG_PAD_ZERO(1),
2716 start, end - start, 60);
2718 PerlIO_printf(Perl_debug_log,
2719 "%s%s REx%s %s against %s\n",
2720 PL_colors[4], blurb, PL_colors[5], s0, s1);
2722 if (do_utf8||utf8_pat)
2723 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2724 utf8_pat ? "pattern" : "",
2725 utf8_pat && do_utf8 ? " and " : "",
2726 do_utf8 ? "string" : ""
2732 S_dump_exec_pos(pTHX_ const char *locinput,
2733 const regnode *scan,
2734 const char *loc_regeol,
2735 const char *loc_bostr,
2736 const char *loc_reg_starttry,
2739 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
2740 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2741 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
2742 /* The part of the string before starttry has one color
2743 (pref0_len chars), between starttry and current
2744 position another one (pref_len - pref0_len chars),
2745 after the current position the third one.
2746 We assume that pref0_len <= pref_len, otherwise we
2747 decrease pref0_len. */
2748 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
2749 ? (5 + taill) - l : locinput - loc_bostr;
2752 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
2754 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2756 pref0_len = pref_len - (locinput - loc_reg_starttry);
2757 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
2758 l = ( loc_regeol - locinput > (5 + taill) - pref_len
2759 ? (5 + taill) - pref_len : loc_regeol - locinput);
2760 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2764 if (pref0_len > pref_len)
2765 pref0_len = pref_len;
2767 const int is_uni = (do_utf8 && OP(scan) != CANY) ? 1 : 0;
2769 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
2770 (locinput - pref_len),pref0_len, 60, 4, 5);
2772 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
2773 (locinput - pref_len + pref0_len),
2774 pref_len - pref0_len, 60, 2, 3);
2776 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
2777 locinput, loc_regeol - locinput, 10, 0, 1);
2779 const STRLEN tlen=len0+len1+len2;
2780 PerlIO_printf(Perl_debug_log,
2781 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
2782 (IV)(locinput - loc_bostr),
2785 (docolor ? "" : "> <"),
2787 (int)(tlen > 19 ? 0 : 19 - tlen),
2794 /* reg_check_named_buff_matched()
2795 * Checks to see if a named buffer has matched. The data array of
2796 * buffer numbers corresponding to the buffer is expected to reside
2797 * in the regexp->data->data array in the slot stored in the ARG() of
2798 * node involved. Note that this routine doesn't actually care about the
2799 * name, that information is not preserved from compilation to execution.
2800 * Returns the index of the leftmost defined buffer with the given name
2801 * or 0 if non of the buffers matched.
2804 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
2807 RXi_GET_DECL(rex,rexi);
2808 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
2809 I32 *nums=(I32*)SvPVX(sv_dat);
2811 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
2813 for ( n=0; n<SvIVX(sv_dat); n++ ) {
2814 if ((I32)*PL_reglastparen >= nums[n] &&
2815 PL_regoffs[nums[n]].end != -1)
2824 /* free all slabs above current one - called during LEAVE_SCOPE */
2827 S_clear_backtrack_stack(pTHX_ void *p)
2829 regmatch_slab *s = PL_regmatch_slab->next;
2834 PL_regmatch_slab->next = NULL;
2836 regmatch_slab * const osl = s;
2843 #define SETREX(Re1,Re2) \
2844 if (PL_reg_eval_set) PM_SETRE((PL_reg_curpm), (Re2)); \
2847 STATIC I32 /* 0 failure, 1 success */
2848 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
2850 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2854 register const bool do_utf8 = PL_reg_match_utf8;
2855 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2856 REGEXP *rex_sv = reginfo->prog;
2857 regexp *rex = (struct regexp *)SvANY(rex_sv);
2858 RXi_GET_DECL(rex,rexi);
2860 /* the current state. This is a cached copy of PL_regmatch_state */
2861 register regmatch_state *st;
2862 /* cache heavy used fields of st in registers */
2863 register regnode *scan;
2864 register regnode *next;
2865 register U32 n = 0; /* general value; init to avoid compiler warning */
2866 register I32 ln = 0; /* len or last; init to avoid compiler warning */
2867 register char *locinput = PL_reginput;
2868 register I32 nextchr; /* is always set to UCHARAT(locinput) */
2870 bool result = 0; /* return value of S_regmatch */
2871 int depth = 0; /* depth of backtrack stack */
2872 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
2873 const U32 max_nochange_depth =
2874 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
2875 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
2876 regmatch_state *yes_state = NULL; /* state to pop to on success of
2878 /* mark_state piggy backs on the yes_state logic so that when we unwind
2879 the stack on success we can update the mark_state as we go */
2880 regmatch_state *mark_state = NULL; /* last mark state we have seen */
2881 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
2882 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
2884 bool no_final = 0; /* prevent failure from backtracking? */
2885 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
2886 char *startpoint = PL_reginput;
2887 SV *popmark = NULL; /* are we looking for a mark? */
2888 SV *sv_commit = NULL; /* last mark name seen in failure */
2889 SV *sv_yes_mark = NULL; /* last mark name we have seen
2890 during a successfull match */
2891 U32 lastopen = 0; /* last open we saw */
2892 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
2893 SV* const oreplsv = GvSV(PL_replgv);
2894 /* these three flags are set by various ops to signal information to
2895 * the very next op. They have a useful lifetime of exactly one loop
2896 * iteration, and are not preserved or restored by state pushes/pops
2898 bool sw = 0; /* the condition value in (?(cond)a|b) */
2899 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
2900 int logical = 0; /* the following EVAL is:
2904 or the following IFMATCH/UNLESSM is:
2905 false: plain (?=foo)
2906 true: used as a condition: (?(?=foo))
2909 GET_RE_DEBUG_FLAGS_DECL;
2912 PERL_ARGS_ASSERT_REGMATCH;
2914 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
2915 PerlIO_printf(Perl_debug_log,"regmatch start\n");
2917 /* on first ever call to regmatch, allocate first slab */
2918 if (!PL_regmatch_slab) {
2919 Newx(PL_regmatch_slab, 1, regmatch_slab);
2920 PL_regmatch_slab->prev = NULL;
2921 PL_regmatch_slab->next = NULL;
2922 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2925 oldsave = PL_savestack_ix;
2926 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
2927 SAVEVPTR(PL_regmatch_slab);
2928 SAVEVPTR(PL_regmatch_state);
2930 /* grab next free state slot */
2931 st = ++PL_regmatch_state;
2932 if (st > SLAB_LAST(PL_regmatch_slab))
2933 st = PL_regmatch_state = S_push_slab(aTHX);
2935 /* Note that nextchr is a byte even in UTF */
2936 nextchr = UCHARAT(locinput);
2938 while (scan != NULL) {
2941 SV * const prop = sv_newmortal();
2942 regnode *rnext=regnext(scan);
2943 DUMP_EXEC_POS( locinput, scan, do_utf8 );
2944 regprop(rex, prop, scan);
2946 PerlIO_printf(Perl_debug_log,
2947 "%3"IVdf":%*s%s(%"IVdf")\n",
2948 (IV)(scan - rexi->program), depth*2, "",
2950 (PL_regkind[OP(scan)] == END || !rnext) ?
2951 0 : (IV)(rnext - rexi->program));
2954 next = scan + NEXT_OFF(scan);
2957 state_num = OP(scan);
2961 assert(PL_reglastparen == &rex->lastparen);
2962 assert(PL_reglastcloseparen == &rex->lastcloseparen);
2963 assert(PL_regoffs == rex->offs);
2965 switch (state_num) {
2967 if (locinput == PL_bostr)
2969 /* reginfo->till = reginfo->bol; */
2974 if (locinput == PL_bostr ||
2975 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
2981 if (locinput == PL_bostr)
2985 if (locinput == reginfo->ganch)
2990 /* update the startpoint */
2991 st->u.keeper.val = PL_regoffs[0].start;
2992 PL_reginput = locinput;
2993 PL_regoffs[0].start = locinput - PL_bostr;
2994 PUSH_STATE_GOTO(KEEPS_next, next);
2996 case KEEPS_next_fail:
2997 /* rollback the start point change */
2998 PL_regoffs[0].start = st->u.keeper.val;
3004 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3009 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3011 if (PL_regeol - locinput > 1)
3015 if (PL_regeol != locinput)
3019 if (!nextchr && locinput >= PL_regeol)
3022 locinput += PL_utf8skip[nextchr];
3023 if (locinput > PL_regeol)
3025 nextchr = UCHARAT(locinput);
3028 nextchr = UCHARAT(++locinput);
3031 if (!nextchr && locinput >= PL_regeol)
3033 nextchr = UCHARAT(++locinput);
3036 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
3039 locinput += PL_utf8skip[nextchr];
3040 if (locinput > PL_regeol)
3042 nextchr = UCHARAT(locinput);
3045 nextchr = UCHARAT(++locinput);
3049 #define ST st->u.trie
3051 /* In this case the charclass data is available inline so
3052 we can fail fast without a lot of extra overhead.
3054 if (scan->flags == EXACT || !do_utf8) {
3055 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
3057 PerlIO_printf(Perl_debug_log,
3058 "%*s %sfailed to match trie start class...%s\n",
3059 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3068 /* what type of TRIE am I? (utf8 makes this contextual) */
3069 DECL_TRIE_TYPE(scan);
3071 /* what trie are we using right now */
3072 reg_trie_data * const trie
3073 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
3074 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3075 U32 state = trie->startstate;
3077 if (trie->bitmap && trie_type != trie_utf8_fold &&
3078 !TRIE_BITMAP_TEST(trie,*locinput)
3080 if (trie->states[ state ].wordnum) {
3082 PerlIO_printf(Perl_debug_log,
3083 "%*s %smatched empty string...%s\n",
3084 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3089 PerlIO_printf(Perl_debug_log,
3090 "%*s %sfailed to match trie start class...%s\n",
3091 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3098 U8 *uc = ( U8* )locinput;
3102 U8 *uscan = (U8*)NULL;
3104 SV *sv_accept_buff = NULL;
3105 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3107 ST.accepted = 0; /* how many accepting states we have seen */
3109 ST.jump = trie->jump;
3112 traverse the TRIE keeping track of all accepting states
3113 we transition through until we get to a failing node.
3116 while ( state && uc <= (U8*)PL_regeol ) {
3117 U32 base = trie->states[ state ].trans.base;
3120 /* We use charid to hold the wordnum as we don't use it
3121 for charid until after we have done the wordnum logic.
3122 We define an alias just so that the wordnum logic reads
3125 #define got_wordnum charid
3126 got_wordnum = trie->states[ state ].wordnum;
3128 if ( got_wordnum ) {
3129 if ( ! ST.accepted ) {
3131 SAVETMPS; /* XXX is this necessary? dmq */
3132 bufflen = TRIE_INITAL_ACCEPT_BUFFLEN;
3133 sv_accept_buff=newSV(bufflen *
3134 sizeof(reg_trie_accepted) - 1);
3135 SvCUR_set(sv_accept_buff, 0);
3136 SvPOK_on(sv_accept_buff);
3137 sv_2mortal(sv_accept_buff);
3140 (reg_trie_accepted*)SvPV_nolen(sv_accept_buff );
3143 if (ST.accepted >= bufflen) {
3145 ST.accept_buff =(reg_trie_accepted*)
3146 SvGROW(sv_accept_buff,
3147 bufflen * sizeof(reg_trie_accepted));
3149 SvCUR_set(sv_accept_buff,SvCUR(sv_accept_buff)
3150 + sizeof(reg_trie_accepted));
3153 ST.accept_buff[ST.accepted].wordnum = got_wordnum;
3154 ST.accept_buff[ST.accepted].endpos = uc;
3156 } while (trie->nextword && (got_wordnum= trie->nextword[got_wordnum]));
3160 DEBUG_TRIE_EXECUTE_r({
3161 DUMP_EXEC_POS( (char *)uc, scan, do_utf8 );
3162 PerlIO_printf( Perl_debug_log,
3163 "%*s %sState: %4"UVxf" Accepted: %4"UVxf" ",
3164 2+depth * 2, "", PL_colors[4],
3165 (UV)state, (UV)ST.accepted );
3169 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3170 uscan, len, uvc, charid, foldlen,
3174 (base + charid > trie->uniquecharcount )
3175 && (base + charid - 1 - trie->uniquecharcount
3177 && trie->trans[base + charid - 1 -
3178 trie->uniquecharcount].check == state)
3180 state = trie->trans[base + charid - 1 -
3181 trie->uniquecharcount ].next;
3192 DEBUG_TRIE_EXECUTE_r(
3193 PerlIO_printf( Perl_debug_log,
3194 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3195 charid, uvc, (UV)state, PL_colors[5] );
3202 PerlIO_printf( Perl_debug_log,
3203 "%*s %sgot %"IVdf" possible matches%s\n",
3204 REPORT_CODE_OFF + depth * 2, "",
3205 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3208 goto trie_first_try; /* jump into the fail handler */
3210 case TRIE_next_fail: /* we failed - try next alterative */
3212 REGCP_UNWIND(ST.cp);
3213 for (n = *PL_reglastparen; n > ST.lastparen; n--)
3214 PL_regoffs[n].end = -1;
3215 *PL_reglastparen = n;
3224 ST.lastparen = *PL_reglastparen;
3227 if ( ST.accepted == 1 ) {
3228 /* only one choice left - just continue */
3230 AV *const trie_words
3231 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3232 SV ** const tmp = av_fetch( trie_words,
3233 ST.accept_buff[ 0 ].wordnum-1, 0 );
3234 SV *sv= tmp ? sv_newmortal() : NULL;
3236 PerlIO_printf( Perl_debug_log,
3237 "%*s %sonly one match left: #%d <%s>%s\n",
3238 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3239 ST.accept_buff[ 0 ].wordnum,
3240 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3241 PL_colors[0], PL_colors[1],
3242 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3244 : "not compiled under -Dr",
3247 PL_reginput = (char *)ST.accept_buff[ 0 ].endpos;
3248 /* in this case we free tmps/leave before we call regmatch
3249 as we wont be using accept_buff again. */
3251 locinput = PL_reginput;
3252 nextchr = UCHARAT(locinput);
3253 if ( !ST.jump || !ST.jump[ST.accept_buff[0].wordnum])
3256 scan = ST.me + ST.jump[ST.accept_buff[0].wordnum];
3257 if (!has_cutgroup) {
3262 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3265 continue; /* execute rest of RE */
3268 if ( !ST.accepted-- ) {
3270 PerlIO_printf( Perl_debug_log,
3271 "%*s %sTRIE failed...%s\n",
3272 REPORT_CODE_OFF+depth*2, "",
3283 There are at least two accepting states left. Presumably
3284 the number of accepting states is going to be low,
3285 typically two. So we simply scan through to find the one
3286 with lowest wordnum. Once we find it, we swap the last
3287 state into its place and decrement the size. We then try to
3288 match the rest of the pattern at the point where the word
3289 ends. If we succeed, control just continues along the
3290 regex; if we fail we return here to try the next accepting
3297 for( cur = 1 ; cur <= ST.accepted ; cur++ ) {
3298 DEBUG_TRIE_EXECUTE_r(
3299 PerlIO_printf( Perl_debug_log,
3300 "%*s %sgot %"IVdf" (%d) as best, looking at %"IVdf" (%d)%s\n",
3301 REPORT_CODE_OFF + depth * 2, "", PL_colors[4],
3302 (IV)best, ST.accept_buff[ best ].wordnum, (IV)cur,
3303 ST.accept_buff[ cur ].wordnum, PL_colors[5] );
3306 if (ST.accept_buff[cur].wordnum <
3307 ST.accept_buff[best].wordnum)
3312 AV *const trie_words
3313 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3314 SV ** const tmp = av_fetch( trie_words,
3315 ST.accept_buff[ best ].wordnum - 1, 0 );
3316 regnode *nextop=(!ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) ?
3318 ST.me + ST.jump[ST.accept_buff[best].wordnum];
3319 SV *sv= tmp ? sv_newmortal() : NULL;
3321 PerlIO_printf( Perl_debug_log,
3322 "%*s %strying alternation #%d <%s> at node #%d %s\n",
3323 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3324 ST.accept_buff[best].wordnum,
3325 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3326 PL_colors[0], PL_colors[1],
3327 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3328 ) : "not compiled under -Dr",
3329 REG_NODE_NUM(nextop),
3333 if ( best<ST.accepted ) {
3334 reg_trie_accepted tmp = ST.accept_buff[ best ];
3335 ST.accept_buff[ best ] = ST.accept_buff[ ST.accepted ];
3336 ST.accept_buff[ ST.accepted ] = tmp;
3339 PL_reginput = (char *)ST.accept_buff[ best ].endpos;
3340 if ( !ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) {
3343 scan = ST.me + ST.jump[ST.accept_buff[best].wordnum];
3345 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3350 /* we dont want to throw this away, see bug 57042*/
3351 if (oreplsv != GvSV(PL_replgv))
3352 sv_setsv(oreplsv, GvSV(PL_replgv));
3359 char *s = STRING(scan);
3361 if (do_utf8 != UTF) {
3362 /* The target and the pattern have differing utf8ness. */
3364 const char * const e = s + ln;
3367 /* The target is utf8, the pattern is not utf8. */
3372 if (NATIVE_TO_UNI(*(U8*)s) !=
3373 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3381 /* The target is not utf8, the pattern is utf8. */
3386 if (NATIVE_TO_UNI(*((U8*)l)) !=
3387 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3395 nextchr = UCHARAT(locinput);
3398 /* The target and the pattern have the same utf8ness. */
3399 /* Inline the first character, for speed. */
3400 if (UCHARAT(s) != nextchr)
3402 if (PL_regeol - locinput < ln)
3404 if (ln > 1 && memNE(s, locinput, ln))
3407 nextchr = UCHARAT(locinput);
3411 PL_reg_flags |= RF_tainted;
3414 char * const s = STRING(scan);
3417 if (do_utf8 || UTF) {
3418 /* Either target or the pattern are utf8. */
3419 const char * const l = locinput;
3420 char *e = PL_regeol;
3422 if (ibcmp_utf8(s, 0, ln, (bool)UTF,
3423 l, &e, 0, do_utf8)) {
3424 /* One more case for the sharp s:
3425 * pack("U0U*", 0xDF) =~ /ss/i,
3426 * the 0xC3 0x9F are the UTF-8
3427 * byte sequence for the U+00DF. */
3430 toLOWER(s[0]) == 's' &&
3432 toLOWER(s[1]) == 's' &&
3439 nextchr = UCHARAT(locinput);
3443 /* Neither the target and the pattern are utf8. */
3445 /* Inline the first character, for speed. */
3446 if (UCHARAT(s) != nextchr &&
3447 UCHARAT(s) != ((OP(scan) == EXACTF)
3448 ? PL_fold : PL_fold_locale)[nextchr])
3450 if (PL_regeol - locinput < ln)
3452 if (ln > 1 && (OP(scan) == EXACTF
3453 ? ibcmp(s, locinput, ln)
3454 : ibcmp_locale(s, locinput, ln)))
3457 nextchr = UCHARAT(locinput);
3462 PL_reg_flags |= RF_tainted;
3466 /* was last char in word? */
3468 if (locinput == PL_bostr)
3471 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3473 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3475 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3476 ln = isALNUM_uni(ln);
3477 LOAD_UTF8_CHARCLASS_ALNUM();
3478 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8);
3481 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3482 n = isALNUM_LC_utf8((U8*)locinput);
3486 ln = (locinput != PL_bostr) ?
3487 UCHARAT(locinput - 1) : '\n';
3488 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3490 n = isALNUM(nextchr);
3493 ln = isALNUM_LC(ln);
3494 n = isALNUM_LC(nextchr);
3497 if (((!ln) == (!n)) == (OP(scan) == BOUND ||
3498 OP(scan) == BOUNDL))
3503 STRLEN inclasslen = PL_regeol - locinput;
3505 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, do_utf8))
3507 if (locinput >= PL_regeol)
3509 locinput += inclasslen ? inclasslen : UTF8SKIP(locinput);
3510 nextchr = UCHARAT(locinput);
3515 nextchr = UCHARAT(locinput);
3516 if (!REGINCLASS(rex, scan, (U8*)locinput))
3518 if (!nextchr && locinput >= PL_regeol)
3520 nextchr = UCHARAT(++locinput);
3524 /* If we might have the case of the German sharp s
3525 * in a casefolding Unicode character class. */
3527 if (ANYOF_FOLD_SHARP_S(scan, locinput, PL_regeol)) {
3528 locinput += SHARP_S_SKIP;
3529 nextchr = UCHARAT(locinput);
3534 /* Special char classes - The defines start on line 129 or so */
3535 CCC_TRY_AFF( ALNUM, ALNUML, perl_word, "a", isALNUM_LC_utf8, isALNUM, isALNUM_LC);
3536 CCC_TRY_NEG(NALNUM, NALNUML, perl_word, "a", isALNUM_LC_utf8, isALNUM, isALNUM_LC);
3538 CCC_TRY_AFF( SPACE, SPACEL, perl_space, " ", isSPACE_LC_utf8, isSPACE, isSPACE_LC);
3539 CCC_TRY_NEG(NSPACE, NSPACEL, perl_space, " ", isSPACE_LC_utf8, isSPACE, isSPACE_LC);
3541 CCC_TRY_AFF( DIGIT, DIGITL, posix_digit, "0", isDIGIT_LC_utf8, isDIGIT, isDIGIT_LC);
3542 CCC_TRY_NEG(NDIGIT, NDIGITL, posix_digit, "0", isDIGIT_LC_utf8, isDIGIT, isDIGIT_LC);
3544 case CLUMP: /* Match \X: logical Unicode character. This is defined as
3545 a Unicode extended Grapheme Cluster */
3546 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
3547 extended Grapheme Cluster is:
3550 | Prepend* Begin Extend*
3553 Begin is (Hangul-syllable | ! Control)
3554 Extend is (Grapheme_Extend | Spacing_Mark)
3555 Control is [ GCB_Control CR LF ]
3557 The discussion below shows how the code for CLUMP is derived
3558 from this regex. Note that most of these concepts are from
3559 property values of the Grapheme Cluster Boundary (GCB) property.
3560 No code point can have multiple property values for a given
3561 property. Thus a code point in Prepend can't be in Control, but
3562 it must be in !Control. This is why Control above includes
3563 GCB_Control plus CR plus LF. The latter two are used in the GCB
3564 property separately, and so can't be in GCB_Control, even though
3565 they logically are controls. Control is not the same as gc=cc,
3566 but includes format and other characters as well.
3568 The Unicode definition of Hangul-syllable is:
3570 | (L* ( ( V | LV ) V* | LVT ) T*)
3573 Each of these is a value for the GCB property, and hence must be
3574 disjoint, so the order they are tested is immaterial, so the
3575 above can safely be changed to
3578 | (L* ( LVT | ( V | LV ) V*) T*)
3580 The last two terms can be combined like this:
3582 | (( LVT | ( V | LV ) V*) T*))
3584 And refactored into this:
3585 L* (L | LVT T* | V V* T* | LV V* T*)
3587 That means that if we have seen any L's at all we can quit
3588 there, but if the next character is a LVT, a V or and LV we
3591 There is a subtlety with Prepend* which showed up in testing.
3592 Note that the Begin, and only the Begin is required in:
3593 | Prepend* Begin Extend*
3594 Also, Begin contains '! Control'. A Prepend must be a '!
3595 Control', which means it must be a Begin. What it comes down to
3596 is that if we match Prepend* and then find no suitable Begin
3597 afterwards, that if we backtrack the last Prepend, that one will
3598 be a suitable Begin.
3601 if (locinput >= PL_regeol)
3605 /* Match either CR LF or '.', as all the other possibilities
3607 locinput++; /* Match the . or CR */
3609 && locinput < PL_regeol
3610 && UCHARAT(locinput) == '\n') locinput++;
3614 /* Utf8: See if is ( CR LF ); already know that locinput <
3615 * PL_regeol, so locinput+1 is in bounds */
3616 if (nextchr == '\r' && UCHARAT(locinput + 1) == '\n') {
3620 /* In case have to backtrack to beginning, then match '.' */
3621 char *starting = locinput;
3623 /* In case have to backtrack the last prepend */
3624 char *previous_prepend = 0;
3626 LOAD_UTF8_CHARCLASS_GCB();
3628 /* Match (prepend)* */
3629 while (locinput < PL_regeol
3630 && swash_fetch(PL_utf8_X_prepend,
3631 (U8*)locinput, do_utf8))
3633 previous_prepend = locinput;
3634 locinput += UTF8SKIP(locinput);
3637 /* As noted above, if we matched a prepend character, but
3638 * the next thing won't match, back off the last prepend we
3639 * matched, as it is guaranteed to match the begin */
3640 if (previous_prepend
3641 && (locinput >= PL_regeol
3642 || ! swash_fetch(PL_utf8_X_begin,
3643 (U8*)locinput, do_utf8)))
3645 locinput = previous_prepend;
3648 /* Note that here we know PL_regeol > locinput, as we
3649 * tested that upon input to this switch case, and if we
3650 * moved locinput forward, we tested the result just above
3651 * and it either passed, or we backed off so that it will
3653 if (! swash_fetch(PL_utf8_X_begin, (U8*)locinput, do_utf8)) {
3655 /* Here did not match the required 'Begin' in the
3656 * second term. So just match the very first
3657 * character, the '.' of the final term of the regex */
3658 locinput = starting + UTF8SKIP(starting);
3661 /* Here is the beginning of a character that can have
3662 * an extender. It is either a hangul syllable, or a
3664 if (swash_fetch(PL_utf8_X_non_hangul,
3665 (U8*)locinput, do_utf8))
3668 /* Here not a Hangul syllable, must be a
3669 * ('! * Control') */
3670 locinput += UTF8SKIP(locinput);
3673 /* Here is a Hangul syllable. It can be composed
3674 * of several individual characters. One
3675 * possibility is T+ */
3676 if (swash_fetch(PL_utf8_X_T,
3677 (U8*)locinput, do_utf8))
3679 while (locinput < PL_regeol
3680 && swash_fetch(PL_utf8_X_T,
3681 (U8*)locinput, do_utf8))
3683 locinput += UTF8SKIP(locinput);
3687 /* Here, not T+, but is a Hangul. That means
3688 * it is one of the others: L, LV, LVT or V,
3690 * L* (L | LVT T* | V V* T* | LV V* T*) */
3693 while (locinput < PL_regeol
3694 && swash_fetch(PL_utf8_X_L,
3695 (U8*)locinput, do_utf8))
3697 locinput += UTF8SKIP(locinput);
3700 /* Here, have exhausted L*. If the next
3701 * character is not an LV, LVT nor V, it means
3702 * we had to have at least one L, so matches L+
3703 * in the original equation, we have a complete
3704 * hangul syllable. Are done. */
3706 if (locinput < PL_regeol
3707 && swash_fetch(PL_utf8_X_LV_LVT_V,
3708 (U8*)locinput, do_utf8))
3711 /* Otherwise keep going. Must be LV, LVT
3712 * or V. See if LVT */
3713 if (swash_fetch(PL_utf8_X_LVT,
3714 (U8*)locinput, do_utf8))
3716 locinput += UTF8SKIP(locinput);
3719 /* Must be V or LV. Take it, then
3721 locinput += UTF8SKIP(locinput);
3722 while (locinput < PL_regeol
3723 && swash_fetch(PL_utf8_X_V,
3724 (U8*)locinput, do_utf8))
3726 locinput += UTF8SKIP(locinput);
3730 /* And any of LV, LVT, or V can be followed
3732 while (locinput < PL_regeol
3733 && swash_fetch(PL_utf8_X_T,
3737 locinput += UTF8SKIP(locinput);
3743 /* Match any extender */
3744 while (locinput < PL_regeol
3745 && swash_fetch(PL_utf8_X_extend,
3746 (U8*)locinput, do_utf8))
3748 locinput += UTF8SKIP(locinput);
3752 if (locinput > PL_regeol) sayNO;
3754 nextchr = UCHARAT(locinput);
3761 PL_reg_flags |= RF_tainted;
3766 n = reg_check_named_buff_matched(rex,scan);
3769 type = REF + ( type - NREF );
3776 PL_reg_flags |= RF_tainted;
3780 n = ARG(scan); /* which paren pair */
3783 ln = PL_regoffs[n].start;
3784 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
3785 if (*PL_reglastparen < n || ln == -1)
3786 sayNO; /* Do not match unless seen CLOSEn. */
3787 if (ln == PL_regoffs[n].end)
3791 if (do_utf8 && type != REF) { /* REF can do byte comparison */
3793 const char *e = PL_bostr + PL_regoffs[n].end;
3795 * Note that we can't do the "other character" lookup trick as
3796 * in the 8-bit case (no pun intended) because in Unicode we
3797 * have to map both upper and title case to lower case.
3801 STRLEN ulen1, ulen2;
3802 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
3803 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
3807 toLOWER_utf8((U8*)s, tmpbuf1, &ulen1);
3808 toLOWER_utf8((U8*)l, tmpbuf2, &ulen2);
3809 if (ulen1 != ulen2 || memNE((char *)tmpbuf1, (char *)tmpbuf2, ulen1))