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
78 #ifdef PERL_IN_XSUB_RE
84 #define RF_tainted 1 /* tainted information used? */
85 #define RF_warned 2 /* warned about big count? */
87 #define RF_utf8 8 /* Pattern contains multibyte chars? */
89 #define UTF ((PL_reg_flags & RF_utf8) != 0)
91 #define RS_init 1 /* eval environment created */
92 #define RS_set 2 /* replsv value is set */
98 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) : ANYOF_BITMAP_TEST(p,*(c)))
104 #define CHR_SVLEN(sv) (do_utf8 ? sv_len_utf8(sv) : SvCUR(sv))
105 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
107 #define HOPc(pos,off) \
108 (char *)(PL_reg_match_utf8 \
109 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
111 #define HOPBACKc(pos, off) \
112 (char*)(PL_reg_match_utf8\
113 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
114 : (pos - off >= PL_bostr) \
118 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
119 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
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
123 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
124 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
125 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
126 #define LOAD_UTF8_CHARCLASS_MARK() LOAD_UTF8_CHARCLASS(mark, "\xcd\x86")
128 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
130 /* for use after a quantifier and before an EXACT-like node -- japhy */
131 /* it would be nice to rework regcomp.sym to generate this stuff. sigh */
132 #define JUMPABLE(rn) ( \
134 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
136 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
137 OP(rn) == PLUS || OP(rn) == MINMOD || \
138 OP(rn) == KEEPS || (PL_regkind[OP(rn)] == VERB) || \
139 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
141 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
143 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
146 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
147 we don't need this definition. */
148 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
149 #define IS_TEXTF(rn) ( OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
150 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
153 /* ... so we use this as its faster. */
154 #define IS_TEXT(rn) ( OP(rn)==EXACT )
155 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
156 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
161 Search for mandatory following text node; for lookahead, the text must
162 follow but for lookbehind (rn->flags != 0) we skip to the next step.
164 #define FIND_NEXT_IMPT(rn) STMT_START { \
165 while (JUMPABLE(rn)) { \
166 const OPCODE type = OP(rn); \
167 if (type == SUSPEND || PL_regkind[type] == CURLY) \
168 rn = NEXTOPER(NEXTOPER(rn)); \
169 else if (type == PLUS) \
171 else if (type == IFMATCH) \
172 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
173 else rn += NEXT_OFF(rn); \
178 static void restore_pos(pTHX_ void *arg);
181 S_regcppush(pTHX_ I32 parenfloor)
184 const int retval = PL_savestack_ix;
185 #define REGCP_PAREN_ELEMS 4
186 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
188 GET_RE_DEBUG_FLAGS_DECL;
190 if (paren_elems_to_push < 0)
191 Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
193 #define REGCP_OTHER_ELEMS 7
194 SSGROW(paren_elems_to_push + REGCP_OTHER_ELEMS);
196 for (p = PL_regsize; p > parenfloor; p--) {
197 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
198 SSPUSHINT(PL_regoffs[p].end);
199 SSPUSHINT(PL_regoffs[p].start);
200 SSPUSHPTR(PL_reg_start_tmp[p]);
202 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
203 " saving \\%"UVuf" %"IVdf"(%"IVdf")..%"IVdf"\n",
204 (UV)p, (IV)PL_regoffs[p].start,
205 (IV)(PL_reg_start_tmp[p] - PL_bostr),
206 (IV)PL_regoffs[p].end
209 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
210 SSPUSHPTR(PL_regoffs);
211 SSPUSHINT(PL_regsize);
212 SSPUSHINT(*PL_reglastparen);
213 SSPUSHINT(*PL_reglastcloseparen);
214 SSPUSHPTR(PL_reginput);
215 #define REGCP_FRAME_ELEMS 2
216 /* REGCP_FRAME_ELEMS are part of the REGCP_OTHER_ELEMS and
217 * are needed for the regexp context stack bookkeeping. */
218 SSPUSHINT(paren_elems_to_push + REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
219 SSPUSHINT(SAVEt_REGCONTEXT); /* Magic cookie. */
224 /* These are needed since we do not localize EVAL nodes: */
225 #define REGCP_SET(cp) \
227 PerlIO_printf(Perl_debug_log, \
228 " Setting an EVAL scope, savestack=%"IVdf"\n", \
229 (IV)PL_savestack_ix)); \
232 #define REGCP_UNWIND(cp) \
234 if (cp != PL_savestack_ix) \
235 PerlIO_printf(Perl_debug_log, \
236 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
237 (IV)(cp), (IV)PL_savestack_ix)); \
241 S_regcppop(pTHX_ const regexp *rex)
246 GET_RE_DEBUG_FLAGS_DECL;
248 PERL_ARGS_ASSERT_REGCPPOP;
250 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
252 assert(i == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
253 i = SSPOPINT; /* Parentheses elements to pop. */
254 input = (char *) SSPOPPTR;
255 *PL_reglastcloseparen = SSPOPINT;
256 *PL_reglastparen = SSPOPINT;
257 PL_regsize = SSPOPINT;
258 PL_regoffs=(regexp_paren_pair *) SSPOPPTR;
261 /* Now restore the parentheses context. */
262 for (i -= (REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
263 i > 0; i -= REGCP_PAREN_ELEMS) {
265 U32 paren = (U32)SSPOPINT;
266 PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
267 PL_regoffs[paren].start = SSPOPINT;
269 if (paren <= *PL_reglastparen)
270 PL_regoffs[paren].end = tmps;
272 PerlIO_printf(Perl_debug_log,
273 " restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
274 (UV)paren, (IV)PL_regoffs[paren].start,
275 (IV)(PL_reg_start_tmp[paren] - PL_bostr),
276 (IV)PL_regoffs[paren].end,
277 (paren > *PL_reglastparen ? "(no)" : ""));
281 if (*PL_reglastparen + 1 <= rex->nparens) {
282 PerlIO_printf(Perl_debug_log,
283 " restoring \\%"IVdf"..\\%"IVdf" to undef\n",
284 (IV)(*PL_reglastparen + 1), (IV)rex->nparens);
288 /* It would seem that the similar code in regtry()
289 * already takes care of this, and in fact it is in
290 * a better location to since this code can #if 0-ed out
291 * but the code in regtry() is needed or otherwise tests
292 * requiring null fields (pat.t#187 and split.t#{13,14}
293 * (as of patchlevel 7877) will fail. Then again,
294 * this code seems to be necessary or otherwise
295 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
296 * --jhi updated by dapm */
297 for (i = *PL_reglastparen + 1; i <= rex->nparens; i++) {
299 PL_regoffs[i].start = -1;
300 PL_regoffs[i].end = -1;
306 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
309 * pregexec and friends
312 #ifndef PERL_IN_XSUB_RE
314 - pregexec - match a regexp against a string
317 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
318 char *strbeg, I32 minend, SV *screamer, U32 nosave)
319 /* strend: pointer to null at end of string */
320 /* strbeg: real beginning of string */
321 /* minend: end of match must be >=minend after stringarg. */
322 /* nosave: For optimizations. */
324 PERL_ARGS_ASSERT_PREGEXEC;
327 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
328 nosave ? 0 : REXEC_COPY_STR);
333 * Need to implement the following flags for reg_anch:
335 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
337 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
338 * INTUIT_AUTORITATIVE_ML
339 * INTUIT_ONCE_NOML - Intuit can match in one location only.
342 * Another flag for this function: SECOND_TIME (so that float substrs
343 * with giant delta may be not rechecked).
346 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
348 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
349 Otherwise, only SvCUR(sv) is used to get strbeg. */
351 /* XXXX We assume that strpos is strbeg unless sv. */
353 /* XXXX Some places assume that there is a fixed substring.
354 An update may be needed if optimizer marks as "INTUITable"
355 RExen without fixed substrings. Similarly, it is assumed that
356 lengths of all the strings are no more than minlen, thus they
357 cannot come from lookahead.
358 (Or minlen should take into account lookahead.)
359 NOTE: Some of this comment is not correct. minlen does now take account
360 of lookahead/behind. Further research is required. -- demerphq
364 /* A failure to find a constant substring means that there is no need to make
365 an expensive call to REx engine, thus we celebrate a failure. Similarly,
366 finding a substring too deep into the string means that less calls to
367 regtry() should be needed.
369 REx compiler's optimizer found 4 possible hints:
370 a) Anchored substring;
372 c) Whether we are anchored (beginning-of-line or \G);
373 d) First node (of those at offset 0) which may distingush positions;
374 We use a)b)d) and multiline-part of c), and try to find a position in the
375 string which does not contradict any of them.
378 /* Most of decisions we do here should have been done at compile time.
379 The nodes of the REx which we used for the search should have been
380 deleted from the finite automaton. */
383 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
384 char *strend, const U32 flags, re_scream_pos_data *data)
387 struct regexp *const prog = (struct regexp *)SvANY(rx);
388 register I32 start_shift = 0;
389 /* Should be nonnegative! */
390 register I32 end_shift = 0;
395 const bool do_utf8 = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
397 register char *other_last = NULL; /* other substr checked before this */
398 char *check_at = NULL; /* check substr found at this pos */
399 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
400 RXi_GET_DECL(prog,progi);
402 const char * const i_strpos = strpos;
404 GET_RE_DEBUG_FLAGS_DECL;
406 PERL_ARGS_ASSERT_RE_INTUIT_START;
408 RX_MATCH_UTF8_set(rx,do_utf8);
411 PL_reg_flags |= RF_utf8;
414 debug_start_match(rx, do_utf8, strpos, strend,
415 sv ? "Guessing start of match in sv for"
416 : "Guessing start of match in string for");
419 /* CHR_DIST() would be more correct here but it makes things slow. */
420 if (prog->minlen > strend - strpos) {
421 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
422 "String too short... [re_intuit_start]\n"));
426 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
429 if (!prog->check_utf8 && prog->check_substr)
430 to_utf8_substr(prog);
431 check = prog->check_utf8;
433 if (!prog->check_substr && prog->check_utf8)
434 to_byte_substr(prog);
435 check = prog->check_substr;
437 if (check == &PL_sv_undef) {
438 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
439 "Non-utf8 string cannot match utf8 check string\n"));
442 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
443 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
444 || ( (prog->extflags & RXf_ANCH_BOL)
445 && !multiline ) ); /* Check after \n? */
448 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
449 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
450 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
452 && (strpos != strbeg)) {
453 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
456 if (prog->check_offset_min == prog->check_offset_max &&
457 !(prog->extflags & RXf_CANY_SEEN)) {
458 /* Substring at constant offset from beg-of-str... */
461 s = HOP3c(strpos, prog->check_offset_min, strend);
464 slen = SvCUR(check); /* >= 1 */
466 if ( strend - s > slen || strend - s < slen - 1
467 || (strend - s == slen && strend[-1] != '\n')) {
468 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
471 /* Now should match s[0..slen-2] */
473 if (slen && (*SvPVX_const(check) != *s
475 && memNE(SvPVX_const(check), s, slen)))) {
477 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
481 else if (*SvPVX_const(check) != *s
482 || ((slen = SvCUR(check)) > 1
483 && memNE(SvPVX_const(check), s, slen)))
486 goto success_at_start;
489 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
491 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
492 end_shift = prog->check_end_shift;
495 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
496 - (SvTAIL(check) != 0);
497 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
499 if (end_shift < eshift)
503 else { /* Can match at random position */
506 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
507 end_shift = prog->check_end_shift;
509 /* end shift should be non negative here */
512 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
514 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
515 (IV)end_shift, RX_PRECOMP(prog));
519 /* Find a possible match in the region s..strend by looking for
520 the "check" substring in the region corrected by start/end_shift. */
523 I32 srch_start_shift = start_shift;
524 I32 srch_end_shift = end_shift;
525 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
526 srch_end_shift -= ((strbeg - s) - srch_start_shift);
527 srch_start_shift = strbeg - s;
529 DEBUG_OPTIMISE_MORE_r({
530 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
531 (IV)prog->check_offset_min,
532 (IV)srch_start_shift,
534 (IV)prog->check_end_shift);
537 if (flags & REXEC_SCREAM) {
538 I32 p = -1; /* Internal iterator of scream. */
539 I32 * const pp = data ? data->scream_pos : &p;
541 if (PL_screamfirst[BmRARE(check)] >= 0
542 || ( BmRARE(check) == '\n'
543 && (BmPREVIOUS(check) == SvCUR(check) - 1)
545 s = screaminstr(sv, check,
546 srch_start_shift + (s - strbeg), srch_end_shift, pp, 0);
549 /* we may be pointing at the wrong string */
550 if (s && RXp_MATCH_COPIED(prog))
551 s = strbeg + (s - SvPVX_const(sv));
553 *data->scream_olds = s;
558 if (prog->extflags & RXf_CANY_SEEN) {
559 start_point= (U8*)(s + srch_start_shift);
560 end_point= (U8*)(strend - srch_end_shift);
562 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
563 end_point= HOP3(strend, -srch_end_shift, strbeg);
565 DEBUG_OPTIMISE_MORE_r({
566 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
567 (int)(end_point - start_point),
568 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
572 s = fbm_instr( start_point, end_point,
573 check, multiline ? FBMrf_MULTILINE : 0);
576 /* Update the count-of-usability, remove useless subpatterns,
580 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
581 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
582 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
583 (s ? "Found" : "Did not find"),
584 (check == (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)
585 ? "anchored" : "floating"),
588 (s ? " at offset " : "...\n") );
593 /* Finish the diagnostic message */
594 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
596 /* XXX dmq: first branch is for positive lookbehind...
597 Our check string is offset from the beginning of the pattern.
598 So we need to do any stclass tests offset forward from that
607 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
608 Start with the other substr.
609 XXXX no SCREAM optimization yet - and a very coarse implementation
610 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
611 *always* match. Probably should be marked during compile...
612 Probably it is right to do no SCREAM here...
615 if (do_utf8 ? (prog->float_utf8 && prog->anchored_utf8)
616 : (prog->float_substr && prog->anchored_substr))
618 /* Take into account the "other" substring. */
619 /* XXXX May be hopelessly wrong for UTF... */
622 if (check == (do_utf8 ? prog->float_utf8 : prog->float_substr)) {
625 char * const last = HOP3c(s, -start_shift, strbeg);
627 char * const saved_s = s;
630 t = s - prog->check_offset_max;
631 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
633 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
638 t = HOP3c(t, prog->anchored_offset, strend);
639 if (t < other_last) /* These positions already checked */
641 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
644 /* XXXX It is not documented what units *_offsets are in.
645 We assume bytes, but this is clearly wrong.
646 Meaning this code needs to be carefully reviewed for errors.
650 /* On end-of-str: see comment below. */
651 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
652 if (must == &PL_sv_undef) {
654 DEBUG_r(must = prog->anchored_utf8); /* for debug */
659 HOP3(HOP3(last1, prog->anchored_offset, strend)
660 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
662 multiline ? FBMrf_MULTILINE : 0
665 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
666 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
667 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
668 (s ? "Found" : "Contradicts"),
669 quoted, RE_SV_TAIL(must));
674 if (last1 >= last2) {
675 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
676 ", giving up...\n"));
679 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
680 ", trying floating at offset %ld...\n",
681 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
682 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
683 s = HOP3c(last, 1, strend);
687 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
688 (long)(s - i_strpos)));
689 t = HOP3c(s, -prog->anchored_offset, strbeg);
690 other_last = HOP3c(s, 1, strend);
698 else { /* Take into account the floating substring. */
700 char * const saved_s = s;
703 t = HOP3c(s, -start_shift, strbeg);
705 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
706 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
707 last = HOP3c(t, prog->float_max_offset, strend);
708 s = HOP3c(t, prog->float_min_offset, strend);
711 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
712 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
713 /* fbm_instr() takes into account exact value of end-of-str
714 if the check is SvTAIL(ed). Since false positives are OK,
715 and end-of-str is not later than strend we are OK. */
716 if (must == &PL_sv_undef) {
718 DEBUG_r(must = prog->float_utf8); /* for debug message */
721 s = fbm_instr((unsigned char*)s,
722 (unsigned char*)last + SvCUR(must)
724 must, multiline ? FBMrf_MULTILINE : 0);
726 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
727 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
728 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
729 (s ? "Found" : "Contradicts"),
730 quoted, RE_SV_TAIL(must));
734 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
735 ", giving up...\n"));
738 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
739 ", trying anchored starting at offset %ld...\n",
740 (long)(saved_s + 1 - i_strpos)));
742 s = HOP3c(t, 1, strend);
746 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
747 (long)(s - i_strpos)));
748 other_last = s; /* Fix this later. --Hugo */
758 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
760 DEBUG_OPTIMISE_MORE_r(
761 PerlIO_printf(Perl_debug_log,
762 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
763 (IV)prog->check_offset_min,
764 (IV)prog->check_offset_max,
772 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
774 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
777 /* Fixed substring is found far enough so that the match
778 cannot start at strpos. */
780 if (ml_anch && t[-1] != '\n') {
781 /* Eventually fbm_*() should handle this, but often
782 anchored_offset is not 0, so this check will not be wasted. */
783 /* XXXX In the code below we prefer to look for "^" even in
784 presence of anchored substrings. And we search even
785 beyond the found float position. These pessimizations
786 are historical artefacts only. */
788 while (t < strend - prog->minlen) {
790 if (t < check_at - prog->check_offset_min) {
791 if (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) {
792 /* Since we moved from the found position,
793 we definitely contradict the found anchored
794 substr. Due to the above check we do not
795 contradict "check" substr.
796 Thus we can arrive here only if check substr
797 is float. Redo checking for "other"=="fixed".
800 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
801 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
802 goto do_other_anchored;
804 /* We don't contradict the found floating substring. */
805 /* XXXX Why not check for STCLASS? */
807 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
808 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
811 /* Position contradicts check-string */
812 /* XXXX probably better to look for check-string
813 than for "\n", so one should lower the limit for t? */
814 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
815 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
816 other_last = strpos = s = t + 1;
821 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
822 PL_colors[0], PL_colors[1]));
826 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
827 PL_colors[0], PL_colors[1]));
831 ++BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
834 /* The found string does not prohibit matching at strpos,
835 - no optimization of calling REx engine can be performed,
836 unless it was an MBOL and we are not after MBOL,
837 or a future STCLASS check will fail this. */
839 /* Even in this situation we may use MBOL flag if strpos is offset
840 wrt the start of the string. */
841 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
842 && (strpos != strbeg) && strpos[-1] != '\n'
843 /* May be due to an implicit anchor of m{.*foo} */
844 && !(prog->intflags & PREGf_IMPLICIT))
849 DEBUG_EXECUTE_r( if (ml_anch)
850 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
851 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
854 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
856 prog->check_utf8 /* Could be deleted already */
857 && --BmUSEFUL(prog->check_utf8) < 0
858 && (prog->check_utf8 == prog->float_utf8)
860 prog->check_substr /* Could be deleted already */
861 && --BmUSEFUL(prog->check_substr) < 0
862 && (prog->check_substr == prog->float_substr)
865 /* If flags & SOMETHING - do not do it many times on the same match */
866 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
867 SvREFCNT_dec(do_utf8 ? prog->check_utf8 : prog->check_substr);
868 if (do_utf8 ? prog->check_substr : prog->check_utf8)
869 SvREFCNT_dec(do_utf8 ? prog->check_substr : prog->check_utf8);
870 prog->check_substr = prog->check_utf8 = NULL; /* disable */
871 prog->float_substr = prog->float_utf8 = NULL; /* clear */
872 check = NULL; /* abort */
874 /* XXXX This is a remnant of the old implementation. It
875 looks wasteful, since now INTUIT can use many
877 prog->extflags &= ~RXf_USE_INTUIT;
884 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
885 /* trie stclasses are too expensive to use here, we are better off to
886 leave it to regmatch itself */
887 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
888 /* minlen == 0 is possible if regstclass is \b or \B,
889 and the fixed substr is ''$.
890 Since minlen is already taken into account, s+1 is before strend;
891 accidentally, minlen >= 1 guaranties no false positives at s + 1
892 even for \b or \B. But (minlen? 1 : 0) below assumes that
893 regstclass does not come from lookahead... */
894 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
895 This leaves EXACTF only, which is dealt with in find_byclass(). */
896 const U8* const str = (U8*)STRING(progi->regstclass);
897 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
898 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
901 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
902 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
903 else if (prog->float_substr || prog->float_utf8)
904 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
908 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf"\n",
909 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg)));
912 s = find_byclass(prog, progi->regstclass, s, endpos, NULL);
915 const char *what = NULL;
917 if (endpos == strend) {
918 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
919 "Could not match STCLASS...\n") );
922 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
923 "This position contradicts STCLASS...\n") );
924 if ((prog->extflags & RXf_ANCH) && !ml_anch)
926 /* Contradict one of substrings */
927 if (prog->anchored_substr || prog->anchored_utf8) {
928 if ((do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) == check) {
929 DEBUG_EXECUTE_r( what = "anchored" );
931 s = HOP3c(t, 1, strend);
932 if (s + start_shift + end_shift > strend) {
933 /* XXXX Should be taken into account earlier? */
934 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
935 "Could not match STCLASS...\n") );
940 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
941 "Looking for %s substr starting at offset %ld...\n",
942 what, (long)(s + start_shift - i_strpos)) );
945 /* Have both, check_string is floating */
946 if (t + start_shift >= check_at) /* Contradicts floating=check */
947 goto retry_floating_check;
948 /* Recheck anchored substring, but not floating... */
952 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
953 "Looking for anchored substr starting at offset %ld...\n",
954 (long)(other_last - i_strpos)) );
955 goto do_other_anchored;
957 /* Another way we could have checked stclass at the
958 current position only: */
963 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
964 "Looking for /%s^%s/m starting at offset %ld...\n",
965 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
968 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
970 /* Check is floating subtring. */
971 retry_floating_check:
972 t = check_at - start_shift;
973 DEBUG_EXECUTE_r( what = "floating" );
974 goto hop_and_restart;
977 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
978 "By STCLASS: moving %ld --> %ld\n",
979 (long)(t - i_strpos), (long)(s - i_strpos))
983 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
984 "Does not contradict STCLASS...\n");
989 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
990 PL_colors[4], (check ? "Guessed" : "Giving up"),
991 PL_colors[5], (long)(s - i_strpos)) );
994 fail_finish: /* Substring not found */
995 if (prog->check_substr || prog->check_utf8) /* could be removed already */
996 BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
998 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
999 PL_colors[4], PL_colors[5]));
1003 #define DECL_TRIE_TYPE(scan) \
1004 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1005 trie_type = (scan->flags != EXACT) \
1006 ? (do_utf8 ? trie_utf8_fold : (UTF ? trie_latin_utf8_fold : trie_plain)) \
1007 : (do_utf8 ? trie_utf8 : trie_plain)
1009 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1010 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1011 UV uvc_unfolded = 0; \
1012 switch (trie_type) { \
1013 case trie_utf8_fold: \
1014 if ( foldlen>0 ) { \
1015 uvc_unfolded = uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1020 uvc_unfolded = uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1021 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1022 foldlen -= UNISKIP( uvc ); \
1023 uscan = foldbuf + UNISKIP( uvc ); \
1026 case trie_latin_utf8_fold: \
1027 if ( foldlen>0 ) { \
1028 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1034 uvc = to_uni_fold( *(U8*)uc, foldbuf, &foldlen ); \
1035 foldlen -= UNISKIP( uvc ); \
1036 uscan = foldbuf + UNISKIP( uvc ); \
1040 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1048 charid = trie->charmap[ uvc ]; \
1052 if (widecharmap) { \
1053 SV** const svpp = hv_fetch(widecharmap, \
1054 (char*)&uvc, sizeof(UV), 0); \
1056 charid = (U16)SvIV(*svpp); \
1059 if (!charid && trie_type == trie_utf8_fold && !UTF) { \
1060 charid = trie->charmap[uvc_unfolded]; \
1064 #define REXEC_FBC_EXACTISH_CHECK(CoNd) \
1066 char *my_strend= (char *)strend; \
1069 !ibcmp_utf8(s, &my_strend, 0, do_utf8, \
1070 m, NULL, ln, (bool)UTF)) \
1071 && (!reginfo || regtry(reginfo, &s)) ) \
1074 U8 foldbuf[UTF8_MAXBYTES_CASE+1]; \
1075 uvchr_to_utf8(tmpbuf, c); \
1076 f = to_utf8_fold(tmpbuf, foldbuf, &foldlen); \
1078 && (f == c1 || f == c2) \
1080 !ibcmp_utf8(s, &my_strend, 0, do_utf8,\
1081 m, NULL, ln, (bool)UTF)) \
1082 && (!reginfo || regtry(reginfo, &s)) ) \
1088 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1092 && (ln == 1 || !(OP(c) == EXACTF \
1094 : ibcmp_locale(s, m, ln))) \
1095 && (!reginfo || regtry(reginfo, &s)) ) \
1101 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1103 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1109 #define REXEC_FBC_SCAN(CoDe) \
1111 while (s < strend) { \
1117 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1118 REXEC_FBC_UTF8_SCAN( \
1120 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1129 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1132 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1141 #define REXEC_FBC_TRYIT \
1142 if ((!reginfo || regtry(reginfo, &s))) \
1145 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1147 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1150 REXEC_FBC_CLASS_SCAN(CoNd); \
1154 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1157 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1160 REXEC_FBC_CLASS_SCAN(CoNd); \
1164 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1165 PL_reg_flags |= RF_tainted; \
1167 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1170 REXEC_FBC_CLASS_SCAN(CoNd); \
1174 #define DUMP_EXEC_POS(li,s,doutf8) \
1175 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1177 /* We know what class REx starts with. Try to find this position... */
1178 /* if reginfo is NULL, its a dryrun */
1179 /* annoyingly all the vars in this routine have different names from their counterparts
1180 in regmatch. /grrr */
1183 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1184 const char *strend, regmatch_info *reginfo)
1187 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1191 register STRLEN uskip;
1195 register I32 tmp = 1; /* Scratch variable? */
1196 register const bool do_utf8 = PL_reg_match_utf8;
1197 RXi_GET_DECL(prog,progi);
1199 PERL_ARGS_ASSERT_FIND_BYCLASS;
1201 /* We know what class it must start with. */
1205 REXEC_FBC_UTF8_CLASS_SCAN((ANYOF_FLAGS(c) & ANYOF_UNICODE) ||
1206 !UTF8_IS_INVARIANT((U8)s[0]) ?
1207 reginclass(prog, c, (U8*)s, 0, do_utf8) :
1208 REGINCLASS(prog, c, (U8*)s));
1211 while (s < strend) {
1214 if (REGINCLASS(prog, c, (U8*)s) ||
1215 (ANYOF_FOLD_SHARP_S(c, s, strend) &&
1216 /* The assignment of 2 is intentional:
1217 * for the folded sharp s, the skip is 2. */
1218 (skip = SHARP_S_SKIP))) {
1219 if (tmp && (!reginfo || regtry(reginfo, &s)))
1232 if (tmp && (!reginfo || regtry(reginfo, &s)))
1240 ln = STR_LEN(c); /* length to match in octets/bytes */
1241 lnc = (I32) ln; /* length to match in characters */
1243 STRLEN ulen1, ulen2;
1245 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
1246 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
1247 /* used by commented-out code below */
1248 /*const U32 uniflags = UTF8_ALLOW_DEFAULT;*/
1250 /* XXX: Since the node will be case folded at compile
1251 time this logic is a little odd, although im not
1252 sure that its actually wrong. --dmq */
1254 c1 = to_utf8_lower((U8*)m, tmpbuf1, &ulen1);
1255 c2 = to_utf8_upper((U8*)m, tmpbuf2, &ulen2);
1257 /* XXX: This is kinda strange. to_utf8_XYZ returns the
1258 codepoint of the first character in the converted
1259 form, yet originally we did the extra step.
1260 No tests fail by commenting this code out however
1261 so Ive left it out. -- dmq.
1263 c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXBYTES_CASE,
1265 c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXBYTES_CASE,
1270 while (sm < ((U8 *) m + ln)) {
1285 c2 = PL_fold_locale[c1];
1287 e = HOP3c(strend, -((I32)lnc), s);
1289 if (!reginfo && e < s)
1290 e = s; /* Due to minlen logic of intuit() */
1292 /* The idea in the EXACTF* cases is to first find the
1293 * first character of the EXACTF* node and then, if
1294 * necessary, case-insensitively compare the full
1295 * text of the node. The c1 and c2 are the first
1296 * characters (though in Unicode it gets a bit
1297 * more complicated because there are more cases
1298 * than just upper and lower: one needs to use
1299 * the so-called folding case for case-insensitive
1300 * matching (called "loose matching" in Unicode).
1301 * ibcmp_utf8() will do just that. */
1303 if (do_utf8 || UTF) {
1305 U8 tmpbuf [UTF8_MAXBYTES+1];
1308 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1310 /* Upper and lower of 1st char are equal -
1311 * probably not a "letter". */
1314 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1319 REXEC_FBC_EXACTISH_CHECK(c == c1);
1325 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1331 /* Handle some of the three Greek sigmas cases.
1332 * Note that not all the possible combinations
1333 * are handled here: some of them are handled
1334 * by the standard folding rules, and some of
1335 * them (the character class or ANYOF cases)
1336 * are handled during compiletime in
1337 * regexec.c:S_regclass(). */
1338 if (c == (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA ||
1339 c == (UV)UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA)
1340 c = (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA;
1342 REXEC_FBC_EXACTISH_CHECK(c == c1 || c == c2);
1347 /* Neither pattern nor string are UTF8 */
1349 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1351 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1355 PL_reg_flags |= RF_tainted;
1362 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1363 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1365 tmp = ((OP(c) == BOUND ?
1366 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1367 LOAD_UTF8_CHARCLASS_ALNUM();
1368 REXEC_FBC_UTF8_SCAN(
1369 if (tmp == !(OP(c) == BOUND ?
1370 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1371 isALNUM_LC_utf8((U8*)s)))
1379 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1380 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1383 !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
1389 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s)))
1393 PL_reg_flags |= RF_tainted;
1400 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1401 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1403 tmp = ((OP(c) == NBOUND ?
1404 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1405 LOAD_UTF8_CHARCLASS_ALNUM();
1406 REXEC_FBC_UTF8_SCAN(
1407 if (tmp == !(OP(c) == NBOUND ?
1408 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1409 isALNUM_LC_utf8((U8*)s)))
1411 else REXEC_FBC_TRYIT;
1415 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1416 tmp = ((OP(c) == NBOUND ?
1417 isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1420 !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
1422 else REXEC_FBC_TRYIT;
1425 if ((!prog->minlen && !tmp) && (!reginfo || regtry(reginfo, &s)))
1429 REXEC_FBC_CSCAN_PRELOAD(
1430 LOAD_UTF8_CHARCLASS_ALNUM(),
1431 swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8),
1435 REXEC_FBC_CSCAN_TAINT(
1436 isALNUM_LC_utf8((U8*)s),
1440 REXEC_FBC_CSCAN_PRELOAD(
1441 LOAD_UTF8_CHARCLASS_ALNUM(),
1442 !swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8),
1446 REXEC_FBC_CSCAN_TAINT(
1447 !isALNUM_LC_utf8((U8*)s),
1451 REXEC_FBC_CSCAN_PRELOAD(
1452 LOAD_UTF8_CHARCLASS_SPACE(),
1453 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8),
1457 REXEC_FBC_CSCAN_TAINT(
1458 *s == ' ' || isSPACE_LC_utf8((U8*)s),
1462 REXEC_FBC_CSCAN_PRELOAD(
1463 LOAD_UTF8_CHARCLASS_SPACE(),
1464 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8)),
1468 REXEC_FBC_CSCAN_TAINT(
1469 !(*s == ' ' || isSPACE_LC_utf8((U8*)s)),
1473 REXEC_FBC_CSCAN_PRELOAD(
1474 LOAD_UTF8_CHARCLASS_DIGIT(),
1475 swash_fetch(PL_utf8_digit,(U8*)s, do_utf8),
1479 REXEC_FBC_CSCAN_TAINT(
1480 isDIGIT_LC_utf8((U8*)s),
1484 REXEC_FBC_CSCAN_PRELOAD(
1485 LOAD_UTF8_CHARCLASS_DIGIT(),
1486 !swash_fetch(PL_utf8_digit,(U8*)s, do_utf8),
1490 REXEC_FBC_CSCAN_TAINT(
1491 !isDIGIT_LC_utf8((U8*)s),
1497 is_LNBREAK_latin1(s)
1507 !is_VERTWS_latin1(s)
1512 is_HORIZWS_latin1(s)
1516 !is_HORIZWS_utf8(s),
1517 !is_HORIZWS_latin1(s)
1523 /* what trie are we using right now */
1525 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1527 = (reg_trie_data*)progi->data->data[ aho->trie ];
1528 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1530 const char *last_start = strend - trie->minlen;
1532 const char *real_start = s;
1534 STRLEN maxlen = trie->maxlen;
1536 U8 **points; /* map of where we were in the input string
1537 when reading a given char. For ASCII this
1538 is unnecessary overhead as the relationship
1539 is always 1:1, but for Unicode, especially
1540 case folded Unicode this is not true. */
1541 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1545 GET_RE_DEBUG_FLAGS_DECL;
1547 /* We can't just allocate points here. We need to wrap it in
1548 * an SV so it gets freed properly if there is a croak while
1549 * running the match */
1552 sv_points=newSV(maxlen * sizeof(U8 *));
1553 SvCUR_set(sv_points,
1554 maxlen * sizeof(U8 *));
1555 SvPOK_on(sv_points);
1556 sv_2mortal(sv_points);
1557 points=(U8**)SvPV_nolen(sv_points );
1558 if ( trie_type != trie_utf8_fold
1559 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1562 bitmap=(U8*)trie->bitmap;
1564 bitmap=(U8*)ANYOF_BITMAP(c);
1566 /* this is the Aho-Corasick algorithm modified a touch
1567 to include special handling for long "unknown char"
1568 sequences. The basic idea being that we use AC as long
1569 as we are dealing with a possible matching char, when
1570 we encounter an unknown char (and we have not encountered
1571 an accepting state) we scan forward until we find a legal
1573 AC matching is basically that of trie matching, except
1574 that when we encounter a failing transition, we fall back
1575 to the current states "fail state", and try the current char
1576 again, a process we repeat until we reach the root state,
1577 state 1, or a legal transition. If we fail on the root state
1578 then we can either terminate if we have reached an accepting
1579 state previously, or restart the entire process from the beginning
1583 while (s <= last_start) {
1584 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1592 U8 *uscan = (U8*)NULL;
1593 U8 *leftmost = NULL;
1595 U32 accepted_word= 0;
1599 while ( state && uc <= (U8*)strend ) {
1601 U32 word = aho->states[ state ].wordnum;
1605 DEBUG_TRIE_EXECUTE_r(
1606 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1607 dump_exec_pos( (char *)uc, c, strend, real_start,
1608 (char *)uc, do_utf8 );
1609 PerlIO_printf( Perl_debug_log,
1610 " Scanning for legal start char...\n");
1613 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1618 if (uc >(U8*)last_start) break;
1622 U8 *lpos= points[ (pointpos - trie->wordlen[word-1] ) % maxlen ];
1623 if (!leftmost || lpos < leftmost) {
1624 DEBUG_r(accepted_word=word);
1630 points[pointpos++ % maxlen]= uc;
1631 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1632 uscan, len, uvc, charid, foldlen,
1634 DEBUG_TRIE_EXECUTE_r({
1635 dump_exec_pos( (char *)uc, c, strend, real_start,
1637 PerlIO_printf(Perl_debug_log,
1638 " Charid:%3u CP:%4"UVxf" ",
1644 word = aho->states[ state ].wordnum;
1646 base = aho->states[ state ].trans.base;
1648 DEBUG_TRIE_EXECUTE_r({
1650 dump_exec_pos( (char *)uc, c, strend, real_start,
1652 PerlIO_printf( Perl_debug_log,
1653 "%sState: %4"UVxf", word=%"UVxf,
1654 failed ? " Fail transition to " : "",
1655 (UV)state, (UV)word);
1660 (base + charid > trie->uniquecharcount )
1661 && (base + charid - 1 - trie->uniquecharcount
1663 && trie->trans[base + charid - 1 -
1664 trie->uniquecharcount].check == state
1665 && (tmp=trie->trans[base + charid - 1 -
1666 trie->uniquecharcount ].next))
1668 DEBUG_TRIE_EXECUTE_r(
1669 PerlIO_printf( Perl_debug_log," - legal\n"));
1674 DEBUG_TRIE_EXECUTE_r(
1675 PerlIO_printf( Perl_debug_log," - fail\n"));
1677 state = aho->fail[state];
1681 /* we must be accepting here */
1682 DEBUG_TRIE_EXECUTE_r(
1683 PerlIO_printf( Perl_debug_log," - accepting\n"));
1692 if (!state) state = 1;
1695 if ( aho->states[ state ].wordnum ) {
1696 U8 *lpos = points[ (pointpos - trie->wordlen[aho->states[ state ].wordnum-1]) % maxlen ];
1697 if (!leftmost || lpos < leftmost) {
1698 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
1703 s = (char*)leftmost;
1704 DEBUG_TRIE_EXECUTE_r({
1706 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
1707 (UV)accepted_word, (IV)(s - real_start)
1710 if (!reginfo || regtry(reginfo, &s)) {
1716 DEBUG_TRIE_EXECUTE_r({
1717 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
1720 DEBUG_TRIE_EXECUTE_r(
1721 PerlIO_printf( Perl_debug_log,"No match.\n"));
1730 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1740 - regexec_flags - match a regexp against a string
1743 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
1744 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1745 /* strend: pointer to null at end of string */
1746 /* strbeg: real beginning of string */
1747 /* minend: end of match must be >=minend after stringarg. */
1748 /* data: May be used for some additional optimizations.
1749 Currently its only used, with a U32 cast, for transmitting
1750 the ganch offset when doing a /g match. This will change */
1751 /* nosave: For optimizations. */
1754 struct regexp *const prog = (struct regexp *)SvANY(rx);
1755 /*register*/ char *s;
1756 register regnode *c;
1757 /*register*/ char *startpos = stringarg;
1758 I32 minlen; /* must match at least this many chars */
1759 I32 dontbother = 0; /* how many characters not to try at end */
1760 I32 end_shift = 0; /* Same for the end. */ /* CC */
1761 I32 scream_pos = -1; /* Internal iterator of scream. */
1762 char *scream_olds = NULL;
1763 const bool do_utf8 = (bool)DO_UTF8(sv);
1765 RXi_GET_DECL(prog,progi);
1766 regmatch_info reginfo; /* create some info to pass to regtry etc */
1767 regexp_paren_pair *swap = NULL;
1768 GET_RE_DEBUG_FLAGS_DECL;
1770 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
1771 PERL_UNUSED_ARG(data);
1773 /* Be paranoid... */
1774 if (prog == NULL || startpos == NULL) {
1775 Perl_croak(aTHX_ "NULL regexp parameter");
1779 multiline = prog->extflags & RXf_PMf_MULTILINE;
1780 reginfo.prog = rx; /* Yes, sorry that this is confusing. */
1782 RX_MATCH_UTF8_set(rx, do_utf8);
1784 debug_start_match(rx, do_utf8, startpos, strend,
1788 minlen = prog->minlen;
1790 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
1791 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1792 "String too short [regexec_flags]...\n"));
1797 /* Check validity of program. */
1798 if (UCHARAT(progi->program) != REG_MAGIC) {
1799 Perl_croak(aTHX_ "corrupted regexp program");
1803 PL_reg_eval_set = 0;
1807 PL_reg_flags |= RF_utf8;
1809 /* Mark beginning of line for ^ and lookbehind. */
1810 reginfo.bol = startpos; /* XXX not used ??? */
1814 /* Mark end of line for $ (and such) */
1817 /* see how far we have to get to not match where we matched before */
1818 reginfo.till = startpos+minend;
1820 /* If there is a "must appear" string, look for it. */
1823 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
1825 if (flags & REXEC_IGNOREPOS){ /* Means: check only at start */
1826 reginfo.ganch = startpos + prog->gofs;
1827 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1828 "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
1829 } else if (sv && SvTYPE(sv) >= SVt_PVMG
1831 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
1832 && mg->mg_len >= 0) {
1833 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
1834 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1835 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
1837 if (prog->extflags & RXf_ANCH_GPOS) {
1838 if (s > reginfo.ganch)
1840 s = reginfo.ganch - prog->gofs;
1841 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1842 "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
1848 reginfo.ganch = strbeg + PTR2UV(data);
1849 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1850 "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
1852 } else { /* pos() not defined */
1853 reginfo.ganch = strbeg;
1854 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1855 "GPOS: reginfo.ganch = strbeg\n"));
1858 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
1859 /* We have to be careful. If the previous successful match
1860 was from this regex we don't want a subsequent partially
1861 successful match to clobber the old results.
1862 So when we detect this possibility we add a swap buffer
1863 to the re, and switch the buffer each match. If we fail
1864 we switch it back, otherwise we leave it swapped.
1867 /* do we need a save destructor here for eval dies? */
1868 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
1870 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
1871 re_scream_pos_data d;
1873 d.scream_olds = &scream_olds;
1874 d.scream_pos = &scream_pos;
1875 s = re_intuit_start(rx, sv, s, strend, flags, &d);
1877 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
1878 goto phooey; /* not present */
1884 /* Simplest case: anchored match need be tried only once. */
1885 /* [unless only anchor is BOL and multiline is set] */
1886 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
1887 if (s == startpos && regtry(®info, &startpos))
1889 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
1890 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
1895 dontbother = minlen - 1;
1896 end = HOP3c(strend, -dontbother, strbeg) - 1;
1897 /* for multiline we only have to try after newlines */
1898 if (prog->check_substr || prog->check_utf8) {
1902 if (regtry(®info, &s))
1907 if (prog->extflags & RXf_USE_INTUIT) {
1908 s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
1919 if (*s++ == '\n') { /* don't need PL_utf8skip here */
1920 if (regtry(®info, &s))
1927 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
1929 /* the warning about reginfo.ganch being used without intialization
1930 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
1931 and we only enter this block when the same bit is set. */
1932 char *tmp_s = reginfo.ganch - prog->gofs;
1934 if (tmp_s >= strbeg && regtry(®info, &tmp_s))
1939 /* Messy cases: unanchored match. */
1940 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
1941 /* we have /x+whatever/ */
1942 /* it must be a one character string (XXXX Except UTF?) */
1947 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1948 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1949 ch = SvPVX_const(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)[0];
1954 DEBUG_EXECUTE_r( did_match = 1 );
1955 if (regtry(®info, &s)) goto got_it;
1957 while (s < strend && *s == ch)
1965 DEBUG_EXECUTE_r( did_match = 1 );
1966 if (regtry(®info, &s)) goto got_it;
1968 while (s < strend && *s == ch)
1973 DEBUG_EXECUTE_r(if (!did_match)
1974 PerlIO_printf(Perl_debug_log,
1975 "Did not find anchored character...\n")
1978 else if (prog->anchored_substr != NULL
1979 || prog->anchored_utf8 != NULL
1980 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
1981 && prog->float_max_offset < strend - s)) {
1986 char *last1; /* Last position checked before */
1990 if (prog->anchored_substr || prog->anchored_utf8) {
1991 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1992 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1993 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
1994 back_max = back_min = prog->anchored_offset;
1996 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
1997 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1998 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
1999 back_max = prog->float_max_offset;
2000 back_min = prog->float_min_offset;
2004 if (must == &PL_sv_undef)
2005 /* could not downgrade utf8 check substring, so must fail */
2011 last = HOP3c(strend, /* Cannot start after this */
2012 -(I32)(CHR_SVLEN(must)
2013 - (SvTAIL(must) != 0) + back_min), strbeg);
2016 last1 = HOPc(s, -1);
2018 last1 = s - 1; /* bogus */
2020 /* XXXX check_substr already used to find "s", can optimize if
2021 check_substr==must. */
2023 dontbother = end_shift;
2024 strend = HOPc(strend, -dontbother);
2025 while ( (s <= last) &&
2026 ((flags & REXEC_SCREAM)
2027 ? (s = screaminstr(sv, must, HOP3c(s, back_min, (back_min<0 ? strbeg : strend)) - strbeg,
2028 end_shift, &scream_pos, 0))
2029 : (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2030 (unsigned char*)strend, must,
2031 multiline ? FBMrf_MULTILINE : 0))) ) {
2032 /* we may be pointing at the wrong string */
2033 if ((flags & REXEC_SCREAM) && RXp_MATCH_COPIED(prog))
2034 s = strbeg + (s - SvPVX_const(sv));
2035 DEBUG_EXECUTE_r( did_match = 1 );
2036 if (HOPc(s, -back_max) > last1) {
2037 last1 = HOPc(s, -back_min);
2038 s = HOPc(s, -back_max);
2041 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2043 last1 = HOPc(s, -back_min);
2047 while (s <= last1) {
2048 if (regtry(®info, &s))
2054 while (s <= last1) {
2055 if (regtry(®info, &s))
2061 DEBUG_EXECUTE_r(if (!did_match) {
2062 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
2063 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2064 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2065 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2066 ? "anchored" : "floating"),
2067 quoted, RE_SV_TAIL(must));
2071 else if ( (c = progi->regstclass) ) {
2073 const OPCODE op = OP(progi->regstclass);
2074 /* don't bother with what can't match */
2075 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2076 strend = HOPc(strend, -(minlen - 1));
2079 SV * const prop = sv_newmortal();
2080 regprop(prog, prop, c);
2082 RE_PV_QUOTED_DECL(quoted,do_utf8,PERL_DEBUG_PAD_ZERO(1),
2084 PerlIO_printf(Perl_debug_log,
2085 "Matching stclass %.*s against %s (%d chars)\n",
2086 (int)SvCUR(prop), SvPVX_const(prop),
2087 quoted, (int)(strend - s));
2090 if (find_byclass(prog, c, s, strend, ®info))
2092 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2096 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2101 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
2102 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2103 float_real = do_utf8 ? prog->float_utf8 : prog->float_substr;
2105 if (flags & REXEC_SCREAM) {
2106 last = screaminstr(sv, float_real, s - strbeg,
2107 end_shift, &scream_pos, 1); /* last one */
2109 last = scream_olds; /* Only one occurrence. */
2110 /* we may be pointing at the wrong string */
2111 else if (RXp_MATCH_COPIED(prog))
2112 s = strbeg + (s - SvPVX_const(sv));
2116 const char * const little = SvPV_const(float_real, len);
2118 if (SvTAIL(float_real)) {
2119 if (memEQ(strend - len + 1, little, len - 1))
2120 last = strend - len + 1;
2121 else if (!multiline)
2122 last = memEQ(strend - len, little, len)
2123 ? strend - len : NULL;
2129 last = rninstr(s, strend, little, little + len);
2131 last = strend; /* matching "$" */
2136 PerlIO_printf(Perl_debug_log,
2137 "%sCan't trim the tail, match fails (should not happen)%s\n",
2138 PL_colors[4], PL_colors[5]));
2139 goto phooey; /* Should not happen! */
2141 dontbother = strend - last + prog->float_min_offset;
2143 if (minlen && (dontbother < minlen))
2144 dontbother = minlen - 1;
2145 strend -= dontbother; /* this one's always in bytes! */
2146 /* We don't know much -- general case. */
2149 if (regtry(®info, &s))
2158 if (regtry(®info, &s))
2160 } while (s++ < strend);
2169 RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2171 if (PL_reg_eval_set)
2172 restore_pos(aTHX_ prog);
2173 if (RXp_PAREN_NAMES(prog))
2174 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2176 /* make sure $`, $&, $', and $digit will work later */
2177 if ( !(flags & REXEC_NOT_FIRST) ) {
2178 RX_MATCH_COPY_FREE(rx);
2179 if (flags & REXEC_COPY_STR) {
2180 const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2181 #ifdef PERL_OLD_COPY_ON_WRITE
2183 || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2185 PerlIO_printf(Perl_debug_log,
2186 "Copy on write: regexp capture, type %d\n",
2189 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2190 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2191 assert (SvPOKp(prog->saved_copy));
2195 RX_MATCH_COPIED_on(rx);
2196 s = savepvn(strbeg, i);
2202 prog->subbeg = strbeg;
2203 prog->sublen = PL_regeol - strbeg; /* strend may have been modified */
2210 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2211 PL_colors[4], PL_colors[5]));
2212 if (PL_reg_eval_set)
2213 restore_pos(aTHX_ prog);
2215 /* we failed :-( roll it back */
2216 Safefree(prog->offs);
2225 - regtry - try match at specific point
2227 STATIC I32 /* 0 failure, 1 success */
2228 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2232 REGEXP *const rx = reginfo->prog;
2233 regexp *const prog = (struct regexp *)SvANY(rx);
2234 RXi_GET_DECL(prog,progi);
2235 GET_RE_DEBUG_FLAGS_DECL;
2237 PERL_ARGS_ASSERT_REGTRY;
2239 reginfo->cutpoint=NULL;
2241 if ((prog->extflags & RXf_EVAL_SEEN) && !PL_reg_eval_set) {
2244 PL_reg_eval_set = RS_init;
2245 DEBUG_EXECUTE_r(DEBUG_s(
2246 PerlIO_printf(Perl_debug_log, " setting stack tmpbase at %"IVdf"\n",
2247 (IV)(PL_stack_sp - PL_stack_base));
2250 cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2251 /* Otherwise OP_NEXTSTATE will free whatever on stack now. */
2253 /* Apparently this is not needed, judging by wantarray. */
2254 /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2255 cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2258 /* Make $_ available to executed code. */
2259 if (reginfo->sv != DEFSV) {
2261 DEFSV_set(reginfo->sv);
2264 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2265 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2266 /* prepare for quick setting of pos */
2267 #ifdef PERL_OLD_COPY_ON_WRITE
2268 if (SvIsCOW(reginfo->sv))
2269 sv_force_normal_flags(reginfo->sv, 0);
2271 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2272 &PL_vtbl_mglob, NULL, 0);
2276 PL_reg_oldpos = mg->mg_len;
2277 SAVEDESTRUCTOR_X(restore_pos, prog);
2279 if (!PL_reg_curpm) {
2280 Newxz(PL_reg_curpm, 1, PMOP);
2283 SV* const repointer = &PL_sv_undef;
2284 /* this regexp is also owned by the new PL_reg_curpm, which
2285 will try to free it. */
2286 av_push(PL_regex_padav, repointer);
2287 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2288 PL_regex_pad = AvARRAY(PL_regex_padav);
2293 /* It seems that non-ithreads works both with and without this code.
2294 So for efficiency reasons it seems best not to have the code
2295 compiled when it is not needed. */
2296 /* This is safe against NULLs: */
2297 ReREFCNT_dec(PM_GETRE(PL_reg_curpm));
2298 /* PM_reg_curpm owns a reference to this regexp. */
2301 PM_SETRE(PL_reg_curpm, rx);
2302 PL_reg_oldcurpm = PL_curpm;
2303 PL_curpm = PL_reg_curpm;
2304 if (RXp_MATCH_COPIED(prog)) {
2305 /* Here is a serious problem: we cannot rewrite subbeg,
2306 since it may be needed if this match fails. Thus
2307 $` inside (?{}) could fail... */
2308 PL_reg_oldsaved = prog->subbeg;
2309 PL_reg_oldsavedlen = prog->sublen;
2310 #ifdef PERL_OLD_COPY_ON_WRITE
2311 PL_nrs = prog->saved_copy;
2313 RXp_MATCH_COPIED_off(prog);
2316 PL_reg_oldsaved = NULL;
2317 prog->subbeg = PL_bostr;
2318 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2320 DEBUG_EXECUTE_r(PL_reg_starttry = *startpos);
2321 prog->offs[0].start = *startpos - PL_bostr;
2322 PL_reginput = *startpos;
2323 PL_reglastparen = &prog->lastparen;
2324 PL_reglastcloseparen = &prog->lastcloseparen;
2325 prog->lastparen = 0;
2326 prog->lastcloseparen = 0;
2328 PL_regoffs = prog->offs;
2329 if (PL_reg_start_tmpl <= prog->nparens) {
2330 PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2331 if(PL_reg_start_tmp)
2332 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2334 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2337 /* XXXX What this code is doing here?!!! There should be no need
2338 to do this again and again, PL_reglastparen should take care of
2341 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2342 * Actually, the code in regcppop() (which Ilya may be meaning by
2343 * PL_reglastparen), is not needed at all by the test suite
2344 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2345 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2346 * Meanwhile, this code *is* needed for the
2347 * above-mentioned test suite tests to succeed. The common theme
2348 * on those tests seems to be returning null fields from matches.
2349 * --jhi updated by dapm */
2351 if (prog->nparens) {
2352 regexp_paren_pair *pp = PL_regoffs;
2354 for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2362 if (regmatch(reginfo, progi->program + 1)) {
2363 PL_regoffs[0].end = PL_reginput - PL_bostr;
2366 if (reginfo->cutpoint)
2367 *startpos= reginfo->cutpoint;
2368 REGCP_UNWIND(lastcp);
2373 #define sayYES goto yes
2374 #define sayNO goto no
2375 #define sayNO_SILENT goto no_silent
2377 /* we dont use STMT_START/END here because it leads to
2378 "unreachable code" warnings, which are bogus, but distracting. */
2379 #define CACHEsayNO \
2380 if (ST.cache_mask) \
2381 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2384 /* this is used to determine how far from the left messages like
2385 'failed...' are printed. It should be set such that messages
2386 are inline with the regop output that created them.
2388 #define REPORT_CODE_OFF 32
2391 /* Make sure there is a test for this +1 options in re_tests */
2392 #define TRIE_INITAL_ACCEPT_BUFFLEN 4;
2394 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2395 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2397 #define SLAB_FIRST(s) (&(s)->states[0])
2398 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2400 /* grab a new slab and return the first slot in it */
2402 STATIC regmatch_state *
2405 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2408 regmatch_slab *s = PL_regmatch_slab->next;
2410 Newx(s, 1, regmatch_slab);
2411 s->prev = PL_regmatch_slab;
2413 PL_regmatch_slab->next = s;
2415 PL_regmatch_slab = s;
2416 return SLAB_FIRST(s);
2420 /* push a new state then goto it */
2422 #define PUSH_STATE_GOTO(state, node) \
2424 st->resume_state = state; \
2427 /* push a new state with success backtracking, then goto it */
2429 #define PUSH_YES_STATE_GOTO(state, node) \
2431 st->resume_state = state; \
2432 goto push_yes_state;
2438 regmatch() - main matching routine
2440 This is basically one big switch statement in a loop. We execute an op,
2441 set 'next' to point the next op, and continue. If we come to a point which
2442 we may need to backtrack to on failure such as (A|B|C), we push a
2443 backtrack state onto the backtrack stack. On failure, we pop the top
2444 state, and re-enter the loop at the state indicated. If there are no more
2445 states to pop, we return failure.
2447 Sometimes we also need to backtrack on success; for example /A+/, where
2448 after successfully matching one A, we need to go back and try to
2449 match another one; similarly for lookahead assertions: if the assertion
2450 completes successfully, we backtrack to the state just before the assertion
2451 and then carry on. In these cases, the pushed state is marked as
2452 'backtrack on success too'. This marking is in fact done by a chain of
2453 pointers, each pointing to the previous 'yes' state. On success, we pop to
2454 the nearest yes state, discarding any intermediate failure-only states.
2455 Sometimes a yes state is pushed just to force some cleanup code to be
2456 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2457 it to free the inner regex.
2459 Note that failure backtracking rewinds the cursor position, while
2460 success backtracking leaves it alone.
2462 A pattern is complete when the END op is executed, while a subpattern
2463 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2464 ops trigger the "pop to last yes state if any, otherwise return true"
2467 A common convention in this function is to use A and B to refer to the two
2468 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2469 the subpattern to be matched possibly multiple times, while B is the entire
2470 rest of the pattern. Variable and state names reflect this convention.
2472 The states in the main switch are the union of ops and failure/success of
2473 substates associated with with that op. For example, IFMATCH is the op
2474 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2475 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2476 successfully matched A and IFMATCH_A_fail is a state saying that we have
2477 just failed to match A. Resume states always come in pairs. The backtrack
2478 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2479 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2480 on success or failure.
2482 The struct that holds a backtracking state is actually a big union, with
2483 one variant for each major type of op. The variable st points to the
2484 top-most backtrack struct. To make the code clearer, within each
2485 block of code we #define ST to alias the relevant union.
2487 Here's a concrete example of a (vastly oversimplified) IFMATCH
2493 #define ST st->u.ifmatch
2495 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2496 ST.foo = ...; // some state we wish to save
2498 // push a yes backtrack state with a resume value of
2499 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2501 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2504 case IFMATCH_A: // we have successfully executed A; now continue with B
2506 bar = ST.foo; // do something with the preserved value
2509 case IFMATCH_A_fail: // A failed, so the assertion failed
2510 ...; // do some housekeeping, then ...
2511 sayNO; // propagate the failure
2518 For any old-timers reading this who are familiar with the old recursive
2519 approach, the code above is equivalent to:
2521 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2530 ...; // do some housekeeping, then ...
2531 sayNO; // propagate the failure
2534 The topmost backtrack state, pointed to by st, is usually free. If you
2535 want to claim it, populate any ST.foo fields in it with values you wish to
2536 save, then do one of
2538 PUSH_STATE_GOTO(resume_state, node);
2539 PUSH_YES_STATE_GOTO(resume_state, node);
2541 which sets that backtrack state's resume value to 'resume_state', pushes a
2542 new free entry to the top of the backtrack stack, then goes to 'node'.
2543 On backtracking, the free slot is popped, and the saved state becomes the
2544 new free state. An ST.foo field in this new top state can be temporarily
2545 accessed to retrieve values, but once the main loop is re-entered, it
2546 becomes available for reuse.
2548 Note that the depth of the backtrack stack constantly increases during the
2549 left-to-right execution of the pattern, rather than going up and down with
2550 the pattern nesting. For example the stack is at its maximum at Z at the
2551 end of the pattern, rather than at X in the following:
2553 /(((X)+)+)+....(Y)+....Z/
2555 The only exceptions to this are lookahead/behind assertions and the cut,
2556 (?>A), which pop all the backtrack states associated with A before
2559 Bascktrack state structs are allocated in slabs of about 4K in size.
2560 PL_regmatch_state and st always point to the currently active state,
2561 and PL_regmatch_slab points to the slab currently containing
2562 PL_regmatch_state. The first time regmatch() is called, the first slab is
2563 allocated, and is never freed until interpreter destruction. When the slab
2564 is full, a new one is allocated and chained to the end. At exit from
2565 regmatch(), slabs allocated since entry are freed.
2570 #define DEBUG_STATE_pp(pp) \
2572 DUMP_EXEC_POS(locinput, scan, do_utf8); \
2573 PerlIO_printf(Perl_debug_log, \
2574 " %*s"pp" %s%s%s%s%s\n", \
2576 PL_reg_name[st->resume_state], \
2577 ((st==yes_state||st==mark_state) ? "[" : ""), \
2578 ((st==yes_state) ? "Y" : ""), \
2579 ((st==mark_state) ? "M" : ""), \
2580 ((st==yes_state||st==mark_state) ? "]" : "") \
2585 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2590 S_debug_start_match(pTHX_ const REGEXP *prog, const bool do_utf8,
2591 const char *start, const char *end, const char *blurb)
2593 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2595 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2600 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2601 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2603 RE_PV_QUOTED_DECL(s1, do_utf8, PERL_DEBUG_PAD_ZERO(1),
2604 start, end - start, 60);
2606 PerlIO_printf(Perl_debug_log,
2607 "%s%s REx%s %s against %s\n",
2608 PL_colors[4], blurb, PL_colors[5], s0, s1);
2610 if (do_utf8||utf8_pat)
2611 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2612 utf8_pat ? "pattern" : "",
2613 utf8_pat && do_utf8 ? " and " : "",
2614 do_utf8 ? "string" : ""
2620 S_dump_exec_pos(pTHX_ const char *locinput,
2621 const regnode *scan,
2622 const char *loc_regeol,
2623 const char *loc_bostr,
2624 const char *loc_reg_starttry,
2627 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
2628 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2629 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
2630 /* The part of the string before starttry has one color
2631 (pref0_len chars), between starttry and current
2632 position another one (pref_len - pref0_len chars),
2633 after the current position the third one.
2634 We assume that pref0_len <= pref_len, otherwise we
2635 decrease pref0_len. */
2636 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
2637 ? (5 + taill) - l : locinput - loc_bostr;
2640 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
2642 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2644 pref0_len = pref_len - (locinput - loc_reg_starttry);
2645 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
2646 l = ( loc_regeol - locinput > (5 + taill) - pref_len
2647 ? (5 + taill) - pref_len : loc_regeol - locinput);
2648 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2652 if (pref0_len > pref_len)
2653 pref0_len = pref_len;
2655 const int is_uni = (do_utf8 && OP(scan) != CANY) ? 1 : 0;
2657 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
2658 (locinput - pref_len),pref0_len, 60, 4, 5);
2660 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
2661 (locinput - pref_len + pref0_len),
2662 pref_len - pref0_len, 60, 2, 3);
2664 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
2665 locinput, loc_regeol - locinput, 10, 0, 1);
2667 const STRLEN tlen=len0+len1+len2;
2668 PerlIO_printf(Perl_debug_log,
2669 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
2670 (IV)(locinput - loc_bostr),
2673 (docolor ? "" : "> <"),
2675 (int)(tlen > 19 ? 0 : 19 - tlen),
2682 /* reg_check_named_buff_matched()
2683 * Checks to see if a named buffer has matched. The data array of
2684 * buffer numbers corresponding to the buffer is expected to reside
2685 * in the regexp->data->data array in the slot stored in the ARG() of
2686 * node involved. Note that this routine doesn't actually care about the
2687 * name, that information is not preserved from compilation to execution.
2688 * Returns the index of the leftmost defined buffer with the given name
2689 * or 0 if non of the buffers matched.
2692 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
2695 RXi_GET_DECL(rex,rexi);
2696 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
2697 I32 *nums=(I32*)SvPVX(sv_dat);
2699 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
2701 for ( n=0; n<SvIVX(sv_dat); n++ ) {
2702 if ((I32)*PL_reglastparen >= nums[n] &&
2703 PL_regoffs[nums[n]].end != -1)
2712 /* free all slabs above current one - called during LEAVE_SCOPE */
2715 S_clear_backtrack_stack(pTHX_ void *p)
2717 regmatch_slab *s = PL_regmatch_slab->next;
2722 PL_regmatch_slab->next = NULL;
2724 regmatch_slab * const osl = s;
2731 #define SETREX(Re1,Re2) \
2732 if (PL_reg_eval_set) PM_SETRE((PL_reg_curpm), (Re2)); \
2735 STATIC I32 /* 0 failure, 1 success */
2736 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
2738 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2742 register const bool do_utf8 = PL_reg_match_utf8;
2743 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2744 REGEXP *rex_sv = reginfo->prog;
2745 regexp *rex = (struct regexp *)SvANY(rex_sv);
2746 RXi_GET_DECL(rex,rexi);
2748 /* the current state. This is a cached copy of PL_regmatch_state */
2749 register regmatch_state *st;
2750 /* cache heavy used fields of st in registers */
2751 register regnode *scan;
2752 register regnode *next;
2753 register U32 n = 0; /* general value; init to avoid compiler warning */
2754 register I32 ln = 0; /* len or last; init to avoid compiler warning */
2755 register char *locinput = PL_reginput;
2756 register I32 nextchr; /* is always set to UCHARAT(locinput) */
2758 bool result = 0; /* return value of S_regmatch */
2759 int depth = 0; /* depth of backtrack stack */
2760 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
2761 const U32 max_nochange_depth =
2762 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
2763 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
2764 regmatch_state *yes_state = NULL; /* state to pop to on success of
2766 /* mark_state piggy backs on the yes_state logic so that when we unwind
2767 the stack on success we can update the mark_state as we go */
2768 regmatch_state *mark_state = NULL; /* last mark state we have seen */
2769 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
2770 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
2772 bool no_final = 0; /* prevent failure from backtracking? */
2773 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
2774 char *startpoint = PL_reginput;
2775 SV *popmark = NULL; /* are we looking for a mark? */
2776 SV *sv_commit = NULL; /* last mark name seen in failure */
2777 SV *sv_yes_mark = NULL; /* last mark name we have seen
2778 during a successfull match */
2779 U32 lastopen = 0; /* last open we saw */
2780 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
2781 SV* const oreplsv = GvSV(PL_replgv);
2782 /* these three flags are set by various ops to signal information to
2783 * the very next op. They have a useful lifetime of exactly one loop
2784 * iteration, and are not preserved or restored by state pushes/pops
2786 bool sw = 0; /* the condition value in (?(cond)a|b) */
2787 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
2788 int logical = 0; /* the following EVAL is:
2792 or the following IFMATCH/UNLESSM is:
2793 false: plain (?=foo)
2794 true: used as a condition: (?(?=foo))
2797 GET_RE_DEBUG_FLAGS_DECL;
2800 PERL_ARGS_ASSERT_REGMATCH;
2802 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
2803 PerlIO_printf(Perl_debug_log,"regmatch start\n");
2805 /* on first ever call to regmatch, allocate first slab */
2806 if (!PL_regmatch_slab) {
2807 Newx(PL_regmatch_slab, 1, regmatch_slab);
2808 PL_regmatch_slab->prev = NULL;
2809 PL_regmatch_slab->next = NULL;
2810 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2813 oldsave = PL_savestack_ix;
2814 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
2815 SAVEVPTR(PL_regmatch_slab);
2816 SAVEVPTR(PL_regmatch_state);
2818 /* grab next free state slot */
2819 st = ++PL_regmatch_state;
2820 if (st > SLAB_LAST(PL_regmatch_slab))
2821 st = PL_regmatch_state = S_push_slab(aTHX);
2823 /* Note that nextchr is a byte even in UTF */
2824 nextchr = UCHARAT(locinput);
2826 while (scan != NULL) {
2829 SV * const prop = sv_newmortal();
2830 regnode *rnext=regnext(scan);
2831 DUMP_EXEC_POS( locinput, scan, do_utf8 );
2832 regprop(rex, prop, scan);
2834 PerlIO_printf(Perl_debug_log,
2835 "%3"IVdf":%*s%s(%"IVdf")\n",
2836 (IV)(scan - rexi->program), depth*2, "",
2838 (PL_regkind[OP(scan)] == END || !rnext) ?
2839 0 : (IV)(rnext - rexi->program));
2842 next = scan + NEXT_OFF(scan);
2845 state_num = OP(scan);
2847 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
2850 assert(PL_reglastparen == &rex->lastparen);
2851 assert(PL_reglastcloseparen == &rex->lastcloseparen);
2852 assert(PL_regoffs == rex->offs);
2854 switch (state_num) {
2856 if (locinput == PL_bostr)
2858 /* reginfo->till = reginfo->bol; */
2863 if (locinput == PL_bostr ||
2864 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
2870 if (locinput == PL_bostr)
2874 if (locinput == reginfo->ganch)
2879 /* update the startpoint */
2880 st->u.keeper.val = PL_regoffs[0].start;
2881 PL_reginput = locinput;
2882 PL_regoffs[0].start = locinput - PL_bostr;
2883 PUSH_STATE_GOTO(KEEPS_next, next);
2885 case KEEPS_next_fail:
2886 /* rollback the start point change */
2887 PL_regoffs[0].start = st->u.keeper.val;
2893 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2898 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2900 if (PL_regeol - locinput > 1)
2904 if (PL_regeol != locinput)
2908 if (!nextchr && locinput >= PL_regeol)
2911 locinput += PL_utf8skip[nextchr];
2912 if (locinput > PL_regeol)
2914 nextchr = UCHARAT(locinput);
2917 nextchr = UCHARAT(++locinput);
2920 if (!nextchr && locinput >= PL_regeol)
2922 nextchr = UCHARAT(++locinput);
2925 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
2928 locinput += PL_utf8skip[nextchr];
2929 if (locinput > PL_regeol)
2931 nextchr = UCHARAT(locinput);
2934 nextchr = UCHARAT(++locinput);
2938 #define ST st->u.trie
2940 /* In this case the charclass data is available inline so
2941 we can fail fast without a lot of extra overhead.
2943 if (scan->flags == EXACT || !do_utf8) {
2944 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
2946 PerlIO_printf(Perl_debug_log,
2947 "%*s %sfailed to match trie start class...%s\n",
2948 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
2957 /* what type of TRIE am I? (utf8 makes this contextual) */
2958 DECL_TRIE_TYPE(scan);
2960 /* what trie are we using right now */
2961 reg_trie_data * const trie
2962 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
2963 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
2964 U32 state = trie->startstate;
2966 if (trie->bitmap && trie_type != trie_utf8_fold &&
2967 !TRIE_BITMAP_TEST(trie,*locinput)
2969 if (trie->states[ state ].wordnum) {
2971 PerlIO_printf(Perl_debug_log,
2972 "%*s %smatched empty string...%s\n",
2973 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
2978 PerlIO_printf(Perl_debug_log,
2979 "%*s %sfailed to match trie start class...%s\n",
2980 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
2987 U8 *uc = ( U8* )locinput;
2991 U8 *uscan = (U8*)NULL;
2993 SV *sv_accept_buff = NULL;
2994 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2996 ST.accepted = 0; /* how many accepting states we have seen */
2998 ST.jump = trie->jump;
3001 traverse the TRIE keeping track of all accepting states
3002 we transition through until we get to a failing node.
3005 while ( state && uc <= (U8*)PL_regeol ) {
3006 U32 base = trie->states[ state ].trans.base;
3009 /* We use charid to hold the wordnum as we don't use it
3010 for charid until after we have done the wordnum logic.
3011 We define an alias just so that the wordnum logic reads
3014 #define got_wordnum charid
3015 got_wordnum = trie->states[ state ].wordnum;
3017 if ( got_wordnum ) {
3018 if ( ! ST.accepted ) {
3020 SAVETMPS; /* XXX is this necessary? dmq */
3021 bufflen = TRIE_INITAL_ACCEPT_BUFFLEN;
3022 sv_accept_buff=newSV(bufflen *
3023 sizeof(reg_trie_accepted) - 1);
3024 SvCUR_set(sv_accept_buff, 0);
3025 SvPOK_on(sv_accept_buff);
3026 sv_2mortal(sv_accept_buff);
3029 (reg_trie_accepted*)SvPV_nolen(sv_accept_buff );
3032 if (ST.accepted >= bufflen) {
3034 ST.accept_buff =(reg_trie_accepted*)
3035 SvGROW(sv_accept_buff,
3036 bufflen * sizeof(reg_trie_accepted));
3038 SvCUR_set(sv_accept_buff,SvCUR(sv_accept_buff)
3039 + sizeof(reg_trie_accepted));
3042 ST.accept_buff[ST.accepted].wordnum = got_wordnum;
3043 ST.accept_buff[ST.accepted].endpos = uc;
3045 } while (trie->nextword && (got_wordnum= trie->nextword[got_wordnum]));
3049 DEBUG_TRIE_EXECUTE_r({
3050 DUMP_EXEC_POS( (char *)uc, scan, do_utf8 );
3051 PerlIO_printf( Perl_debug_log,
3052 "%*s %sState: %4"UVxf" Accepted: %4"UVxf" ",
3053 2+depth * 2, "", PL_colors[4],
3054 (UV)state, (UV)ST.accepted );
3058 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3059 uscan, len, uvc, charid, foldlen,
3063 (base + charid > trie->uniquecharcount )
3064 && (base + charid - 1 - trie->uniquecharcount
3066 && trie->trans[base + charid - 1 -
3067 trie->uniquecharcount].check == state)
3069 state = trie->trans[base + charid - 1 -
3070 trie->uniquecharcount ].next;
3081 DEBUG_TRIE_EXECUTE_r(
3082 PerlIO_printf( Perl_debug_log,
3083 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3084 charid, uvc, (UV)state, PL_colors[5] );
3091 PerlIO_printf( Perl_debug_log,
3092 "%*s %sgot %"IVdf" possible matches%s\n",
3093 REPORT_CODE_OFF + depth * 2, "",
3094 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3097 goto trie_first_try; /* jump into the fail handler */
3099 case TRIE_next_fail: /* we failed - try next alterative */
3101 REGCP_UNWIND(ST.cp);
3102 for (n = *PL_reglastparen; n > ST.lastparen; n--)
3103 PL_regoffs[n].end = -1;
3104 *PL_reglastparen = n;
3113 ST.lastparen = *PL_reglastparen;
3116 if ( ST.accepted == 1 ) {
3117 /* only one choice left - just continue */
3119 AV *const trie_words
3120 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3121 SV ** const tmp = av_fetch( trie_words,
3122 ST.accept_buff[ 0 ].wordnum-1, 0 );
3123 SV *sv= tmp ? sv_newmortal() : NULL;
3125 PerlIO_printf( Perl_debug_log,
3126 "%*s %sonly one match left: #%d <%s>%s\n",
3127 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3128 ST.accept_buff[ 0 ].wordnum,
3129 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3130 PL_colors[0], PL_colors[1],
3131 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3133 : "not compiled under -Dr",
3136 PL_reginput = (char *)ST.accept_buff[ 0 ].endpos;
3137 /* in this case we free tmps/leave before we call regmatch
3138 as we wont be using accept_buff again. */
3140 locinput = PL_reginput;
3141 nextchr = UCHARAT(locinput);
3142 if ( !ST.jump || !ST.jump[ST.accept_buff[0].wordnum])
3145 scan = ST.me + ST.jump[ST.accept_buff[0].wordnum];
3146 if (!has_cutgroup) {
3151 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3154 continue; /* execute rest of RE */
3157 if ( !ST.accepted-- ) {
3159 PerlIO_printf( Perl_debug_log,
3160 "%*s %sTRIE failed...%s\n",
3161 REPORT_CODE_OFF+depth*2, "",
3172 There are at least two accepting states left. Presumably
3173 the number of accepting states is going to be low,
3174 typically two. So we simply scan through to find the one
3175 with lowest wordnum. Once we find it, we swap the last
3176 state into its place and decrement the size. We then try to
3177 match the rest of the pattern at the point where the word
3178 ends. If we succeed, control just continues along the
3179 regex; if we fail we return here to try the next accepting
3186 for( cur = 1 ; cur <= ST.accepted ; cur++ ) {
3187 DEBUG_TRIE_EXECUTE_r(
3188 PerlIO_printf( Perl_debug_log,
3189 "%*s %sgot %"IVdf" (%d) as best, looking at %"IVdf" (%d)%s\n",
3190 REPORT_CODE_OFF + depth * 2, "", PL_colors[4],
3191 (IV)best, ST.accept_buff[ best ].wordnum, (IV)cur,
3192 ST.accept_buff[ cur ].wordnum, PL_colors[5] );
3195 if (ST.accept_buff[cur].wordnum <
3196 ST.accept_buff[best].wordnum)
3201 AV *const trie_words
3202 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3203 SV ** const tmp = av_fetch( trie_words,
3204 ST.accept_buff[ best ].wordnum - 1, 0 );
3205 regnode *nextop=(!ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) ?
3207 ST.me + ST.jump[ST.accept_buff[best].wordnum];
3208 SV *sv= tmp ? sv_newmortal() : NULL;
3210 PerlIO_printf( Perl_debug_log,
3211 "%*s %strying alternation #%d <%s> at node #%d %s\n",
3212 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3213 ST.accept_buff[best].wordnum,
3214 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3215 PL_colors[0], PL_colors[1],
3216 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3217 ) : "not compiled under -Dr",
3218 REG_NODE_NUM(nextop),
3222 if ( best<ST.accepted ) {
3223 reg_trie_accepted tmp = ST.accept_buff[ best ];
3224 ST.accept_buff[ best ] = ST.accept_buff[ ST.accepted ];
3225 ST.accept_buff[ ST.accepted ] = tmp;
3228 PL_reginput = (char *)ST.accept_buff[ best ].endpos;
3229 if ( !ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) {
3232 scan = ST.me + ST.jump[ST.accept_buff[best].wordnum];
3234 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3239 /* we dont want to throw this away, see bug 57042*/
3240 if (oreplsv != GvSV(PL_replgv))
3241 sv_setsv(oreplsv, GvSV(PL_replgv));
3248 char *s = STRING(scan);
3250 if (do_utf8 != UTF) {
3251 /* The target and the pattern have differing utf8ness. */
3253 const char * const e = s + ln;
3256 /* The target is utf8, the pattern is not utf8. */
3261 if (NATIVE_TO_UNI(*(U8*)s) !=
3262 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3270 /* The target is not utf8, the pattern is utf8. */
3275 if (NATIVE_TO_UNI(*((U8*)l)) !=
3276 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3284 nextchr = UCHARAT(locinput);
3287 /* The target and the pattern have the same utf8ness. */
3288 /* Inline the first character, for speed. */
3289 if (UCHARAT(s) != nextchr)
3291 if (PL_regeol - locinput < ln)
3293 if (ln > 1 && memNE(s, locinput, ln))
3296 nextchr = UCHARAT(locinput);
3300 PL_reg_flags |= RF_tainted;
3303 char * const s = STRING(scan);
3306 if (do_utf8 || UTF) {
3307 /* Either target or the pattern are utf8. */
3308 const char * const l = locinput;
3309 char *e = PL_regeol;
3311 if (ibcmp_utf8(s, 0, ln, (bool)UTF,
3312 l, &e, 0, do_utf8)) {
3313 /* One more case for the sharp s:
3314 * pack("U0U*", 0xDF) =~ /ss/i,
3315 * the 0xC3 0x9F are the UTF-8
3316 * byte sequence for the U+00DF. */
3319 toLOWER(s[0]) == 's' &&
3321 toLOWER(s[1]) == 's' &&
3328 nextchr = UCHARAT(locinput);
3332 /* Neither the target and the pattern are utf8. */
3334 /* Inline the first character, for speed. */
3335 if (UCHARAT(s) != nextchr &&
3336 UCHARAT(s) != ((OP(scan) == EXACTF)
3337 ? PL_fold : PL_fold_locale)[nextchr])
3339 if (PL_regeol - locinput < ln)
3341 if (ln > 1 && (OP(scan) == EXACTF
3342 ? ibcmp(s, locinput, ln)
3343 : ibcmp_locale(s, locinput, ln)))
3346 nextchr = UCHARAT(locinput);
3351 STRLEN inclasslen = PL_regeol - locinput;
3353 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, do_utf8))
3355 if (locinput >= PL_regeol)
3357 locinput += inclasslen ? inclasslen : UTF8SKIP(locinput);
3358 nextchr = UCHARAT(locinput);
3363 nextchr = UCHARAT(locinput);
3364 if (!REGINCLASS(rex, scan, (U8*)locinput))
3366 if (!nextchr && locinput >= PL_regeol)
3368 nextchr = UCHARAT(++locinput);
3372 /* If we might have the case of the German sharp s
3373 * in a casefolding Unicode character class. */
3375 if (ANYOF_FOLD_SHARP_S(scan, locinput, PL_regeol)) {
3376 locinput += SHARP_S_SKIP;
3377 nextchr = UCHARAT(locinput);
3383 PL_reg_flags |= RF_tainted;
3389 LOAD_UTF8_CHARCLASS_ALNUM();
3390 if (!(OP(scan) == ALNUM
3391 ? (bool)swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
3392 : isALNUM_LC_utf8((U8*)locinput)))
3396 locinput += PL_utf8skip[nextchr];
3397 nextchr = UCHARAT(locinput);
3400 if (!(OP(scan) == ALNUM
3401 ? isALNUM(nextchr) : isALNUM_LC(nextchr)))
3403 nextchr = UCHARAT(++locinput);
3406 PL_reg_flags |= RF_tainted;
3409 if (!nextchr && locinput >= PL_regeol)
3412 LOAD_UTF8_CHARCLASS_ALNUM();
3413 if (OP(scan) == NALNUM
3414 ? (bool)swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
3415 : isALNUM_LC_utf8((U8*)locinput))
3419 locinput += PL_utf8skip[nextchr];
3420 nextchr = UCHARAT(locinput);
3423 if (OP(scan) == NALNUM
3424 ? isALNUM(nextchr) : isALNUM_LC(nextchr))
3426 nextchr = UCHARAT(++locinput);
3430 PL_reg_flags |= RF_tainted;
3434 /* was last char in word? */
3436 if (locinput == PL_bostr)
3439 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3441 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3443 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3444 ln = isALNUM_uni(ln);
3445 LOAD_UTF8_CHARCLASS_ALNUM();
3446 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8);
3449 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3450 n = isALNUM_LC_utf8((U8*)locinput);
3454 ln = (locinput != PL_bostr) ?
3455 UCHARAT(locinput - 1) : '\n';
3456 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3458 n = isALNUM(nextchr);
3461 ln = isALNUM_LC(ln);
3462 n = isALNUM_LC(nextchr);
3465 if (((!ln) == (!n)) == (OP(scan) == BOUND ||
3466 OP(scan) == BOUNDL))
3470 PL_reg_flags |= RF_tainted;
3476 if (UTF8_IS_CONTINUED(nextchr)) {
3477 LOAD_UTF8_CHARCLASS_SPACE();
3478 if (!(OP(scan) == SPACE
3479 ? (bool)swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
3480 : isSPACE_LC_utf8((U8*)locinput)))
3484 locinput += PL_utf8skip[nextchr];
3485 nextchr = UCHARAT(locinput);
3488 if (!(OP(scan) == SPACE
3489 ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
3491 nextchr = UCHARAT(++locinput);
3494 if (!(OP(scan) == SPACE
3495 ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
3497 nextchr = UCHARAT(++locinput);
3501 PL_reg_flags |= RF_tainted;
3504 if (!nextchr && locinput >= PL_regeol)
3507 LOAD_UTF8_CHARCLASS_SPACE();
3508 if (OP(scan) == NSPACE
3509 ? (bool)swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
3510 : isSPACE_LC_utf8((U8*)locinput))
3514 locinput += PL_utf8skip[nextchr];
3515 nextchr = UCHARAT(locinput);
3518 if (OP(scan) == NSPACE
3519 ? isSPACE(nextchr) : isSPACE_LC(nextchr))
3521 nextchr = UCHARAT(++locinput);
3524 PL_reg_flags |= RF_tainted;
3530 LOAD_UTF8_CHARCLASS_DIGIT();
3531 if (!(OP(scan) == DIGIT
3532 ? (bool)swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
3533 : isDIGIT_LC_utf8((U8*)locinput)))
3537 locinput += PL_utf8skip[nextchr];
3538 nextchr = UCHARAT(locinput);
3541 if (!(OP(scan) == DIGIT
3542 ? isDIGIT(nextchr) : isDIGIT_LC(nextchr)))
3544 nextchr = UCHARAT(++locinput);
3547 PL_reg_flags |= RF_tainted;
3550 if (!nextchr && locinput >= PL_regeol)
3553 LOAD_UTF8_CHARCLASS_DIGIT();
3554 if (OP(scan) == NDIGIT
3555 ? (bool)swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
3556 : isDIGIT_LC_utf8((U8*)locinput))
3560 locinput += PL_utf8skip[nextchr];
3561 nextchr = UCHARAT(locinput);
3564 if (OP(scan) == NDIGIT
3565 ? isDIGIT(nextchr) : isDIGIT_LC(nextchr))
3567 nextchr = UCHARAT(++locinput);
3570 if (locinput >= PL_regeol)
3573 LOAD_UTF8_CHARCLASS_MARK();
3574 if (swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3576 locinput += PL_utf8skip[nextchr];
3577 while (locinput < PL_regeol &&
3578 swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3579 locinput += UTF8SKIP(locinput);
3580 if (locinput > PL_regeol)
3585 nextchr = UCHARAT(locinput);
3592 PL_reg_flags |= RF_tainted;
3597 n = reg_check_named_buff_matched(rex,scan);
3600 type = REF + ( type - NREF );
3607 PL_reg_flags |= RF_tainted;
3611 n = ARG(scan); /* which paren pair */
3614 ln = PL_regoffs[n].start;
3615 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
3616 if (*PL_reglastparen < n || ln == -1)
3617 sayNO; /* Do not match unless seen CLOSEn. */
3618 if (ln == PL_regoffs[n].end)
3622 if (do_utf8 && type != REF) { /* REF can do byte comparison */
3624 const char *e = PL_bostr + PL_regoffs[n].end;
3626 * Note that we can't do the "other character" lookup trick as
3627 * in the 8-bit case (no pun intended) because in Unicode we
3628 * have to map both upper and title case to lower case.
3632 STRLEN ulen1, ulen2;
3633 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
3634 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
3638 toLOWER_utf8((U8*)s, tmpbuf1, &ulen1);
3639 toLOWER_utf8((U8*)l, tmpbuf2, &ulen2);
3640 if (ulen1 != ulen2 || memNE((char *)tmpbuf1, (char *)tmpbuf2, ulen1))
3647 nextchr = UCHARAT(locinput);
3651 /* Inline the first character, for speed. */
3652 if (UCHARAT(s) != nextchr &&
3654 (UCHARAT(s) != (type == REFF
3655 ? PL_fold : PL_fold_locale)[nextchr])))
3657 ln = PL_regoffs[n].end - ln;
3658 if (locinput + ln > PL_regeol)
3660 if (ln > 1 && (type == REF
3661 ? memNE(s, locinput, ln)
3663 ? ibcmp(s, locinput, ln)
3664 : ibcmp_locale(s, locinput, ln))))
3667 nextchr = UCHARAT(locinput);
3677 #define ST st->u.eval
3682 regexp_internal *rei;
3683 regnode *startpoint;
3686 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
3687 if (cur_eval && cur_eval->locinput==locinput) {
3688 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
3689 Perl_croak(aTHX_ "Infinite recursion in regex");
3690 if ( ++nochange_depth > max_nochange_depth )
3692 "Pattern subroutine nesting without pos change"
3693 " exceeded limit in regex");
3700 (void)ReREFCNT_inc(rex_sv);
3701 if (OP(scan)==GOSUB) {
3702 startpoint = scan + ARG2L(scan);
3703 ST.close_paren = ARG(scan);
3705 startpoint = rei->program+1;
3708 goto eval_recurse_doit;
3710 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
3711 if (cur_eval && cur_eval->locinput==locinput) {
3712 if ( ++nochange_depth > max_nochange_depth )
3713 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
3718 /* execute the code in the {...} */
3720 SV ** const before = SP;
3721 OP_4tree * const oop = PL_op;
3722 COP * const ocurcop = PL_curcop;
3724 char *saved_regeol = PL_regeol;
3727 PL_op = (OP_4tree*)rexi->data->data[n];
3728 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
3729 " re_eval 0x%"UVxf"\n", PTR2UV(PL_op)) );
3730 PAD_SAVE_LOCAL(old_comppad, (PAD*)rexi->data->data[n + 2]);
3731 PL_regoffs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
3734 SV *sv_mrk = get_sv("REGMARK", 1);
3735 sv_setsv(sv_mrk, sv_yes_mark);
3738 CALLRUNOPS(aTHX); /* Scalar context. */
3741 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
3748 PAD_RESTORE_LOCAL(old_comppad);
3749 PL_curcop = ocurcop;
3750 PL_regeol = saved_regeol;
3753 sv_setsv(save_scalar(PL_replgv), ret);
3757 if (logical == 2) { /* Postponed subexpression: /(??{...})/ */
3760 /* extract RE object from returned value; compiling if
3766 SV *const sv = SvRV(ret);
3768 if (SvTYPE(sv) == SVt_REGEXP) {
3770 } else if (SvSMAGICAL(sv)) {
3771 mg = mg_find(sv, PERL_MAGIC_qr);
3774 } else if (SvTYPE(ret) == SVt_REGEXP) {
3776 } else if (SvSMAGICAL(ret)) {
3777 if (SvGMAGICAL(ret)) {
3778 /* I don't believe that there is ever qr magic
3780 assert(!mg_find(ret, PERL_MAGIC_qr));
3781 sv_unmagic(ret, PERL_MAGIC_qr);
3784 mg = mg_find(ret, PERL_MAGIC_qr);
3785 /* testing suggests mg only ends up non-NULL for
3786 scalars who were upgraded and compiled in the
3787 else block below. In turn, this is only
3788 triggered in the "postponed utf8 string" tests
3794 rx = (REGEXP *) mg->mg_obj; /*XXX:dmq*/
3798 rx = reg_temp_copy(rx);
3802 const I32 osize = PL_regsize;
3805 assert (SvUTF8(ret));
3806 } else if (SvUTF8(ret)) {
3807 /* Not doing UTF-8, despite what the SV says. Is
3808 this only if we're trapped in use 'bytes'? */
3809 /* Make a copy of the octet sequence, but without
3810 the flag on, as the compiler now honours the
3811 SvUTF8 flag on ret. */
3813 const char *const p = SvPV(ret, len);
3814 ret = newSVpvn_flags(p, len, SVs_TEMP);
3816 rx = CALLREGCOMP(ret, pm_flags);
3818 & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
3820 /* This isn't a first class regexp. Instead, it's
3821 caching a regexp onto an existing, Perl visible
3823 sv_magic(ret, MUTABLE_SV(rx), PERL_MAGIC_qr, 0, 0);
3828 re = (struct regexp *)SvANY(rx);
3830 RXp_MATCH_COPIED_off(re);
3831 re->subbeg = rex->subbeg;
3832 re->sublen = rex->sublen;
3835 debug_start_match(re_sv, do_utf8, locinput, PL_regeol,
3836 "Matching embedded");
3838 startpoint = rei->program + 1;
3839 ST.close_paren = 0; /* only used for GOSUB */
3840 /* borrowed from regtry */
3841 if (PL_reg_start_tmpl <= re->nparens) {
3842 PL_reg_start_tmpl = re->nparens*3/2 + 3;
3843 if(PL_reg_start_tmp)
3844 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
3846 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
3849 eval_recurse_doit: /* Share code with GOSUB below this line */
3850 /* run the pattern returned from (??{...}) */
3851 ST.cp = regcppush(0); /* Save *all* the positions. */
3852 REGCP_SET(ST.lastcp);
3854 PL_regoffs = re->offs; /* essentially NOOP on GOSUB */
3856 /* see regtry, specifically PL_reglast(?:close)?paren is a pointer! (i dont know why) :dmq */
3857 PL_reglastparen = &re->lastparen;
3858 PL_reglastcloseparen = &re->lastcloseparen;
3860 re->lastcloseparen = 0;
3862 PL_reginput = locinput;
3865 /* XXXX This is too dramatic a measure... */
3868 ST.toggle_reg_flags = PL_reg_flags;
3870 PL_reg_flags |= RF_utf8;
3872 PL_reg_flags &= ~RF_utf8;
3873 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
3875 ST.prev_rex = rex_sv;
3876 ST.prev_curlyx = cur_curlyx;
3877 SETREX(rex_sv,re_sv);
3882 ST.prev_eval = cur_eval;
3884 /* now continue from first node in postoned RE */
3885 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
3888 /* logical is 1, /(?(?{...})X|Y)/ */
3889 sw = (bool)SvTRUE(ret);
3894 case EVAL_AB: /* cleanup after a successful (??{A})B */
3895 /* note: this is called twice; first after popping B, then A */
3896 PL_reg_flags ^= ST.toggle_reg_flags;
3897 ReREFCNT_dec(rex_sv);
3898 SETREX(rex_sv,ST.prev_rex);
3899 rex = (struct regexp *)SvANY(rex_sv);
3900 rexi = RXi_GET(rex);
3902 cur_eval = ST.prev_eval;
3903 cur_curlyx = ST.prev_curlyx;
3905 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
3906 PL_reglastparen = &rex->lastparen;
3907 PL_reglastcloseparen = &rex->lastcloseparen;
3908 /* also update PL_regoffs */
3909 PL_regoffs = rex->offs;
3911 /* XXXX This is too dramatic a measure... */
3913 if ( nochange_depth )
3918 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
3919 /* note: this is called twice; first after popping B, then A */
3920 PL_reg_flags ^= ST.toggle_reg_flags;
3921 ReREFCNT_dec(rex_sv);
3922 SETREX(rex_sv,ST.prev_rex);
3923 rex = (struct regexp *)SvANY(rex_sv);
3924 rexi = RXi_GET(rex);
3925 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
3926 PL_reglastparen = &rex->lastparen;
3927 PL_reglastcloseparen = &rex->lastcloseparen;
3929 PL_reginput = locinput;
3930 REGCP_UNWIND(ST.lastcp);
3932 cur_eval = ST.prev_eval;
3933 cur_curlyx = ST.prev_curlyx;
3934 /* XXXX This is too dramatic a measure... */
3936 if ( nochange_depth )
3942 n = ARG(scan); /* which paren pair */
3943 PL_reg_start_tmp[n] = locinput;
3949 n = ARG(scan); /* which paren pair */
3950 PL_regoffs[n].start = PL_reg_start_tmp[n] - PL_bostr;
3951 PL_regoffs[n].end = locinput - PL_bostr;
3952 /*if (n > PL_regsize)
3954 if (n > *PL_reglastparen)
3955 *PL_reglastparen = n;
3956 *PL_reglastcloseparen = n;
3957 if (cur_eval && cur_eval->u.eval.close_paren == n) {
3965 cursor && OP(cursor)!=END;
3966 cursor=regnext(cursor))
3968 if ( OP(cursor)==CLOSE ){
3970 if ( n <= lastopen ) {
3972 = PL_reg_start_tmp[n] - PL_bostr;
3973 PL_regoffs[n].end = locinput - PL_bostr;
3974 /*if (n > PL_regsize)
3976 if (n > *PL_reglastparen)
3977 *PL_reglastparen = n;
3978 *PL_reglastcloseparen = n;
3979 if ( n == ARG(scan) || (cur_eval &&
3980 cur_eval->u.eval.close_paren == n))
3989 n = ARG(scan); /* which paren pair */
3990 sw = (bool)(*PL_reglastparen >= n && PL_regoffs[n].end != -1);
3993 /* reg_check_named_buff_matched returns 0 for no match */
3994 sw = (bool)(0 < reg_check_named_buff_matched(rex,scan));
3998 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
4004 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4006 next = NEXTOPER(NEXTOPER(scan));
4008 next = scan + ARG(scan);
4009 if (OP(next) == IFTHEN) /* Fake one. */
4010 next = NEXTOPER(NEXTOPER(next));
4014 logical = scan->flags;
4017 /*******************************************************************
4019 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
4020 pattern, where A and B are subpatterns. (For simple A, CURLYM or
4021 STAR/PLUS/CURLY/CURLYN are used instead.)
4023 A*B is compiled as <CURLYX><A><WHILEM><B>
4025 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
4026 state, which contains the current count, initialised to -1. It also sets
4027 cur_curlyx to point to this state, with any previous value saved in the
4030 CURLYX then jumps straight to the WHILEM op, rather than executing A,
4031 since the pattern may possibly match zero times (i.e. it's a while {} loop
4032 rather than a do {} while loop).
4034 Each entry to WHILEM represents a successful match of A. The count in the
4035 CURLYX block is incremented, another WHILEM state is pushed, and execution
4036 passes to A or B depending on greediness and the current count.
4038 For example, if matching against the string a1a2a3b (where the aN are
4039 substrings that match /A/), then the match progresses as follows: (the
4040 pushed states are interspersed with the bits of strings matched so far):
4043 <CURLYX cnt=0><WHILEM>
4044 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
4045 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
4046 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
4047 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
4049 (Contrast this with something like CURLYM, which maintains only a single
4053 a1 <CURLYM cnt=1> a2
4054 a1 a2 <CURLYM cnt=2> a3
4055 a1 a2 a3 <CURLYM cnt=3> b
4058 Each WHILEM state block marks a point to backtrack to upon partial failure
4059 of A or B, and also contains some minor state data related to that
4060 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
4061 overall state, such as the count, and pointers to the A and B ops.
4063 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4064 must always point to the *current* CURLYX block, the rules are:
4066 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4067 and set cur_curlyx to point the new block.
4069 When popping the CURLYX block after a successful or unsuccessful match,
4070 restore the previous cur_curlyx.
4072 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4073 to the outer one saved in the CURLYX block.
4075 When popping the WHILEM block after a successful or unsuccessful B match,
4076 restore the previous cur_curlyx.
4078 Here's an example for the pattern (AI* BI)*BO
4079 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4082 curlyx backtrack stack
4083 ------ ---------------
4085 CO <CO prev=NULL> <WO>
4086 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4087 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4088 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4090 At this point the pattern succeeds, and we work back down the stack to
4091 clean up, restoring as we go:
4093 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4094 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4095 CO <CO prev=NULL> <WO>
4098 *******************************************************************/
4100 #define ST st->u.curlyx
4102 case CURLYX: /* start of /A*B/ (for complex A) */
4104 /* No need to save/restore up to this paren */
4105 I32 parenfloor = scan->flags;
4107 assert(next); /* keep Coverity happy */
4108 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4111 /* XXXX Probably it is better to teach regpush to support
4112 parenfloor > PL_regsize... */
4113 if (parenfloor > (I32)*PL_reglastparen)
4114 parenfloor = *PL_reglastparen; /* Pessimization... */
4116 ST.prev_curlyx= cur_curlyx;
4118 ST.cp = PL_savestack_ix;
4120 /* these fields contain the state of the current curly.
4121 * they are accessed by subsequent WHILEMs */
4122 ST.parenfloor = parenfloor;
4123 ST.min = ARG1(scan);
4124 ST.max = ARG2(scan);
4125 ST.A = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
4129 ST.count = -1; /* this will be updated by WHILEM */
4130 ST.lastloc = NULL; /* this will be updated by WHILEM */
4132 PL_reginput = locinput;
4133 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4137 case CURLYX_end: /* just finished matching all of A*B */
4138 cur_curlyx = ST.prev_curlyx;
4142 case CURLYX_end_fail: /* just failed to match all of A*B */
4144 cur_curlyx = ST.prev_curlyx;
4150 #define ST st->u.whilem
4152 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
4154 /* see the discussion above about CURLYX/WHILEM */
4156 assert(cur_curlyx); /* keep Coverity happy */
4157 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4158 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4159 ST.cache_offset = 0;
4162 PL_reginput = locinput;
4164 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4165 "%*s whilem: matched %ld out of %ld..%ld\n",
4166 REPORT_CODE_OFF+depth*2, "", (long)n,
4167 (long)cur_curlyx->u.curlyx.min,
4168 (long)cur_curlyx->u.curlyx.max)
4171 /* First just match a string of min A's. */
4173 if (n < cur_curlyx->u.curlyx.min) {
4174 cur_curlyx->u.curlyx.lastloc = locinput;
4175 PUSH_STATE_GOTO(WHILEM_A_pre, cur_curlyx->u.curlyx.A);
4179 /* If degenerate A matches "", assume A done. */
4181 if (locinput == cur_curlyx->u.curlyx.lastloc) {
4182 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4183 "%*s whilem: empty match detected, trying continuation...\n",
4184 REPORT_CODE_OFF+depth*2, "")
4186 goto do_whilem_B_max;
4189 /* super-linear cache processing */
4193 if (!PL_reg_maxiter) {
4194 /* start the countdown: Postpone detection until we
4195 * know the match is not *that* much linear. */
4196 PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4197 /* possible overflow for long strings and many CURLYX's */
4198 if (PL_reg_maxiter < 0)
4199 PL_reg_maxiter = I32_MAX;
4200 PL_reg_leftiter = PL_reg_maxiter;
4203 if (PL_reg_leftiter-- == 0) {
4204 /* initialise cache */
4205 const I32 size = (PL_reg_maxiter + 7)/8;
4206 if (PL_reg_poscache) {
4207 if ((I32)PL_reg_poscache_size < size) {
4208 Renew(PL_reg_poscache, size, char);
4209 PL_reg_poscache_size = size;
4211 Zero(PL_reg_poscache, size, char);
4214 PL_reg_poscache_size = size;
4215 Newxz(PL_reg_poscache, size, char);
4217 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4218 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4219 PL_colors[4], PL_colors[5])
4223 if (PL_reg_leftiter < 0) {
4224 /* have we already failed at this position? */
4226 offset = (scan->flags & 0xf) - 1
4227 + (locinput - PL_bostr) * (scan->flags>>4);
4228 mask = 1 << (offset % 8);
4230 if (PL_reg_poscache[offset] & mask) {
4231 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4232 "%*s whilem: (cache) already tried at this position...\n",
4233 REPORT_CODE_OFF+depth*2, "")
4235 sayNO; /* cache records failure */
4237 ST.cache_offset = offset;
4238 ST.cache_mask = mask;
4242 /* Prefer B over A for minimal matching. */
4244 if (cur_curlyx->u.curlyx.minmod) {
4245 ST.save_curlyx = cur_curlyx;
4246 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4247 ST.cp = regcppush(ST.save_curlyx->u.curlyx.parenfloor);
4248 REGCP_SET(ST.lastcp);
4249 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4253 /* Prefer A over B for maximal matching. */
4255 if (n < cur_curlyx->u.curlyx.max) { /* More greed allowed? */
4256 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4257 cur_curlyx->u.curlyx.lastloc = locinput;
4258 REGCP_SET(ST.lastcp);
4259 PUSH_STATE_GOTO(WHILEM_A_max, cur_curlyx->u.curlyx.A);
4262 goto do_whilem_B_max;
4266 case WHILEM_B_min: /* just matched B in a minimal match */
4267 case WHILEM_B_max: /* just matched B in a maximal match */
4268 cur_curlyx = ST.save_curlyx;
4272 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4273 cur_curlyx = ST.save_curlyx;
4274 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4275 cur_curlyx->u.curlyx.count--;
4279 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4280 REGCP_UNWIND(ST.lastcp);
4283 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
4284 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4285 cur_curlyx->u.curlyx.count--;
4289 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
4290 REGCP_UNWIND(ST.lastcp);
4291 regcppop(rex); /* Restore some previous $<digit>s? */
4292 PL_reginput = locinput;
4293 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4294 "%*s whilem: failed, trying continuation...\n",
4295 REPORT_CODE_OFF+depth*2, "")
4298 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4299 && ckWARN(WARN_REGEXP)
4300 && !(PL_reg_flags & RF_warned))
4302 PL_reg_flags |= RF_warned;
4303 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
4304 "Complex regular subexpression recursion",
4309 ST.save_curlyx = cur_curlyx;
4310 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4311 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
4314 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
4315 cur_curlyx = ST.save_curlyx;
4316 REGCP_UNWIND(ST.lastcp);
4319 if (cur_curlyx->u.curlyx.count >= cur_curlyx->u.curlyx.max) {
4320 /* Maximum greed exceeded */
4321 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4322 && ckWARN(WARN_REGEXP)
4323 && !(PL_reg_flags & RF_warned))
4325 PL_reg_flags |= RF_warned;
4326 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
4327 "%s limit (%d) exceeded",
4328 "Complex regular subexpression recursion",
4331 cur_curlyx->u.curlyx.count--;
4335 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4336 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
4338 /* Try grabbing another A and see if it helps. */
4339 PL_reginput = locinput;
4340 cur_curlyx->u.curlyx.lastloc = locinput;
4341 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4342 REGCP_SET(ST.lastcp);
4343 PUSH_STATE_GOTO(WHILEM_A_min, ST.save_curlyx->u.curlyx.A);
4347 #define ST st->u.branch
4349 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
4350 next = scan + ARG(scan);
4353 scan = NEXTOPER(scan);
4356 case BRANCH: /* /(...|A|...)/ */
4357 scan = NEXTOPER(scan); /* scan now points to inner node */
4358 ST.lastparen = *PL_reglastparen;
4359 ST.next_branch = next;
4361 PL_reginput = locinput;
4363 /* Now go into the branch */
4365 PUSH_YES_STATE_GOTO(BRANCH_next, scan);
4367 PUSH_STATE_GOTO(BRANCH_next, scan);
4371 PL_reginput = locinput;
4372 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
4373 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4374 PUSH_STATE_GOTO(CUTGROUP_next,next);
4376 case CUTGROUP_next_fail:
4379 if (st->u.mark.mark_name)
4380 sv_commit = st->u.mark.mark_name;
4386 case BRANCH_next_fail: /* that branch failed; try the next, if any */
4391 REGCP_UNWIND(ST.cp);
4392 for (n = *PL_reglastparen; n > ST.lastparen; n--)
4393 PL_regoffs[n].end = -1;
4394 *PL_reglastparen = n;
4395 /*dmq: *PL_reglastcloseparen = n; */
4396 scan = ST.next_branch;
4397 /* no more branches? */
4398 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
4400 PerlIO_printf( Perl_debug_log,
4401 "%*s %sBRANCH failed...%s\n",
4402 REPORT_CODE_OFF+depth*2, "",
4408 continue; /* execute next BRANCH[J] op */
4416 #define ST st->u.curlym
4418 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
4420 /* This is an optimisation of CURLYX that enables us to push
4421 * only a single backtracking state, no matter how many matches
4422 * there are in {m,n}. It relies on the pattern being constant
4423 * length, with no parens to influence future backrefs
4427 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4429 /* if paren positive, emulate an OPEN/CLOSE around A */
4431 U32 paren = ST.me->flags;
4432 if (paren > PL_regsize)
4434 if (paren > *PL_reglastparen)
4435 *PL_reglastparen = paren;
4436 scan += NEXT_OFF(scan); /* Skip former OPEN. */
4444 ST.c1 = CHRTEST_UNINIT;
4447 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
4450 curlym_do_A: /* execute the A in /A{m,n}B/ */
4451 PL_reginput = locinput;
4452 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
4455 case CURLYM_A: /* we've just matched an A */
4456 locinput = st->locinput;
4457 nextchr = UCHARAT(locinput);
4460 /* after first match, determine A's length: u.curlym.alen */
4461 if (ST.count == 1) {
4462 if (PL_reg_match_utf8) {
4464 while (s < PL_reginput) {
4470 ST.alen = PL_reginput - locinput;
4473 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
4476 PerlIO_printf(Perl_debug_log,
4477 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
4478 (int)(REPORT_CODE_OFF+(depth*2)), "",
4479 (IV) ST.count, (IV)ST.alen)
4482 locinput = PL_reginput;
4484 if (cur_eval && cur_eval->u.eval.close_paren &&
4485 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4489 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
4490 if ( max == REG_INFTY || ST.count < max )
4491 goto curlym_do_A; /* try to match another A */
4493 goto curlym_do_B; /* try to match B */
4495 case CURLYM_A_fail: /* just failed to match an A */
4496 REGCP_UNWIND(ST.cp);
4498 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
4499 || (cur_eval && cur_eval->u.eval.close_paren &&
4500 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
4503 curlym_do_B: /* execute the B in /A{m,n}B/ */
4504 PL_reginput = locinput;
4505 if (ST.c1 == CHRTEST_UNINIT) {
4506 /* calculate c1 and c2 for possible match of 1st char
4507 * following curly */
4508 ST.c1 = ST.c2 = CHRTEST_VOID;
4509 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
4510 regnode *text_node = ST.B;
4511 if (! HAS_TEXT(text_node))
4512 FIND_NEXT_IMPT(text_node);
4515 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
4517 But the former is redundant in light of the latter.
4519 if this changes back then the macro for
4520 IS_TEXT and friends need to change.
4522 if (PL_regkind[OP(text_node)] == EXACT)
4525 ST.c1 = (U8)*STRING(text_node);
4527 (IS_TEXTF(text_node))
4529 : (IS_TEXTFL(text_node))
4530 ? PL_fold_locale[ST.c1]
4537 PerlIO_printf(Perl_debug_log,
4538 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
4539 (int)(REPORT_CODE_OFF+(depth*2)),
4542 if (ST.c1 != CHRTEST_VOID
4543 && UCHARAT(PL_reginput) != ST.c1
4544 && UCHARAT(PL_reginput) != ST.c2)
4546 /* simulate B failing */
4548 PerlIO_printf(Perl_debug_log,
4549 "%*s CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
4550 (int)(REPORT_CODE_OFF+(depth*2)),"",
4553 state_num = CURLYM_B_fail;
4554 goto reenter_switch;
4558 /* mark current A as captured */
4559 I32 paren = ST.me->flags;
4561 PL_regoffs[paren].start
4562 = HOPc(PL_reginput, -ST.alen) - PL_bostr;
4563 PL_regoffs[paren].end = PL_reginput - PL_bostr;
4564 /*dmq: *PL_reglastcloseparen = paren; */
4567 PL_regoffs[paren].end = -1;
4568 if (cur_eval && cur_eval->u.eval.close_paren &&
4569 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4578 PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
4581 case CURLYM_B_fail: /* just failed to match a B */
4582 REGCP_UNWIND(ST.cp);
4584 I32 max = ARG2(ST.me);
4585 if (max != REG_INFTY && ST.count == max)
4587 goto curlym_do_A; /* try to match a further A */
4589 /* backtrack one A */
4590 if (ST.count == ARG1(ST.me) /* min */)
4593 locinput = HOPc(locinput, -ST.alen);
4594 goto curlym_do_B; /* try to match B */
4597 #define ST st->u.curly
4599 #define CURLY_SETPAREN(paren, success) \
4602 PL_regoffs[paren].start = HOPc(locinput, -1) - PL_bostr; \
4603 PL_regoffs[paren].end = locinput - PL_bostr; \
4604 *PL_reglastcloseparen = paren; \
4607 PL_regoffs[paren].end = -1; \
4610 case STAR: /* /A*B/ where A is width 1 */
4614 scan = NEXTOPER(scan);
4616 case PLUS: /* /A+B/ where A is width 1 */
4620 scan = NEXTOPER(scan);
4622 case CURLYN: /* /(A){m,n}B/ where A is width 1 */
4623 ST.paren = scan->flags; /* Which paren to set */
4624 if (ST.paren > PL_regsize)
4625 PL_regsize = ST.paren;
4626 if (ST.paren > *PL_reglastparen)
4627 *PL_reglastparen = ST.paren;
4628 ST.min = ARG1(scan); /* min to match */
4629 ST.max = ARG2(scan); /* max to match */
4630 if (cur_eval && cur_eval->u.eval.close_paren &&
4631 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4635 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
4637 case CURLY: /* /A{m,n}B/ where A is width 1 */
4639 ST.min = ARG1(scan); /* min to match */
4640 ST.max = ARG2(scan); /* max to match */
4641 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4644 * Lookahead to avoid useless match attempts
4645 * when we know what character comes next.
4647 * Used to only do .*x and .*?x, but now it allows
4648 * for )'s, ('s and (?{ ... })'s to be in the way
4649 * of the quantifier and the EXACT-like node. -- japhy
4652 if (ST.min > ST.max) /* XXX make this a compile-time check? */
4654 if (HAS_TEXT(next) || JUMPABLE(next)) {
4656 regnode *text_node = next;
4658 if (! HAS_TEXT(text_node))
4659 FIND_NEXT_IMPT(text_node);
4661 if (! HAS_TEXT(text_node))
4662 ST.c1 = ST.c2 = CHRTEST_VOID;
4664 if ( PL_regkind[OP(text_node)] != EXACT ) {
4665 ST.c1 = ST.c2 = CHRTEST_VOID;
4666 goto assume_ok_easy;
4669 s = (U8*)STRING(text_node);
4671 /* Currently we only get here when
4673 PL_rekind[OP(text_node)] == EXACT
4675 if this changes back then the macro for IS_TEXT and
4676 friends need to change. */
4679 if (IS_TEXTF(text_node))
4680 ST.c2 = PL_fold[ST.c1];
4681 else if (IS_TEXTFL(text_node))
4682 ST.c2 = PL_fold_locale[ST.c1];
4685 if (IS_TEXTF(text_node)) {
4686 STRLEN ulen1, ulen2;
4687 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
4688 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
4690 to_utf8_lower((U8*)s, tmpbuf1, &ulen1);
4691 to_utf8_upper((U8*)s, tmpbuf2, &ulen2);
4693 ST.c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXLEN, 0,
4695 0 : UTF8_ALLOW_ANY);
4696 ST.c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXLEN, 0,
4698 0 : UTF8_ALLOW_ANY);
4700 ST.c1 = utf8n_to_uvuni(tmpbuf1, UTF8_MAXBYTES, 0,
4702 ST.c2 = utf8n_to_uvuni(tmpbuf2, UTF8_MAXBYTES, 0,
4707 ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
4714 ST.c1 = ST.c2 = CHRTEST_VOID;
4719 PL_reginput = locinput;
4722 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
4725 locinput = PL_reginput;
4727 if (ST.c1 == CHRTEST_VOID)
4728 goto curly_try_B_min;
4730 ST.oldloc = locinput;
4732 /* set ST.maxpos to the furthest point along the
4733 * string that could possibly match */
4734 if (ST.max == REG_INFTY) {
4735 ST.maxpos = PL_regeol - 1;
4737 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
4741 int m = ST.max - ST.min;
4742 for (ST.maxpos = locinput;
4743 m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
4744 ST.maxpos += UTF8SKIP(ST.maxpos);
4747 ST.maxpos = locinput + ST.max - ST.min;
4748 if (ST.maxpos >= PL_regeol)
4749 ST.maxpos = PL_regeol - 1;
4751 goto curly_try_B_min_known;
4755 ST.count = regrepeat(rex, ST.A, ST.max, depth);
4756 locinput = PL_reginput;
4757 if (ST.count < ST.min)
4759 if ((ST.count > ST.min)
4760 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
4762 /* A{m,n} must come at the end of the string, there's
4763 * no point in backing off ... */
4765 /* ...except that $ and \Z can match before *and* after
4766 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
4767 We may back off by one in this case. */
4768 if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
4772 goto curly_try_B_max;
4777 case CURLY_B_min_known_fail:
4778 /* failed to find B in a non-greedy match where c1,c2 valid */
4779 if (ST.paren && ST.count)
4780 PL_regoffs[ST.paren].end = -1;
4782 PL_reginput = locinput; /* Could be reset... */
4783 REGCP_UNWIND(ST.cp);
4784 /* Couldn't or didn't -- move forward. */
4785 ST.oldloc = locinput;
4787 locinput += UTF8SKIP(locinput);
4791 curly_try_B_min_known:
4792 /* find the next place where 'B' could work, then call B */
4796 n = (ST.oldloc == locinput) ? 0 : 1;
4797 if (ST.c1 == ST.c2) {
4799 /* set n to utf8_distance(oldloc, locinput) */
4800 while (locinput <= ST.maxpos &&
4801 utf8n_to_uvchr((U8*)locinput,
4802 UTF8_MAXBYTES, &len,
4803 uniflags) != (UV)ST.c1) {
4809 /* set n to utf8_distance(oldloc, locinput) */
4810 while (locinput <= ST.maxpos) {
4812 const UV c = utf8n_to_uvchr((U8*)locinput,
4813 UTF8_MAXBYTES, &len,
4815 if (c == (UV)ST.c1 || c == (UV)ST.c2)
4823 if (ST.c1 == ST.c2) {
4824 while (locinput <= ST.maxpos &&
4825 UCHARAT(locinput) != ST.c1)
4829 while (locinput <= ST.maxpos
4830 && UCHARAT(locinput) != ST.c1
4831 && UCHARAT(locinput) != ST.c2)
4834 n = locinput - ST.oldloc;
4836 if (locinput > ST.maxpos)
4838 /* PL_reginput == oldloc now */
4841 if (regrepeat(rex, ST.A, n, depth) < n)
4844 PL_reginput = locinput;
4845 CURLY_SETPAREN(ST.paren, ST.count);
4846 if (cur_eval && cur_eval->u.eval.close_paren &&
4847 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4850 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
4855 case CURLY_B_min_fail:
4856 /* failed to find B in a non-greedy match where c1,c2 invalid */
4857 if (ST.paren && ST.count)
4858 PL_regoffs[ST.paren].end = -1;
4860 REGCP_UNWIND(ST.cp);
4861 /* failed -- move forward one */
4862 PL_reginput = locinput;
4863 if (regrepeat(rex, ST.A, 1, depth)) {
4865 locinput = PL_reginput;
4866 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
4867 ST.count > 0)) /* count overflow ? */
4870 CURLY_SETPAREN(ST.paren, ST.count);
4871 if (cur_eval && cur_eval->u.eval.close_paren &&
4872 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4875 PUSH_STATE_GOTO(CURLY_B_min, ST.B);
4883 /* a successful greedy match: now try to match B */
4884 if (cur_eval && cur_eval->u.eval.close_paren &&
4885 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4890 if (ST.c1 != CHRTEST_VOID)
4891 c = do_utf8 ? utf8n_to_uvchr((U8*)PL_reginput,
4892 UTF8_MAXBYTES, 0, uniflags)
4893 : (UV) UCHARAT(PL_reginput);
4894 /* If it could work, try it. */
4895 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
4896 CURLY_SETPAREN(ST.paren, ST.count);
4897 PUSH_STATE_GOTO(CURLY_B_max, ST.B);
4902 case CURLY_B_max_fail:
4903 /* failed to find B in a greedy match */
4904 if (ST.paren && ST.count)
4905 PL_regoffs[ST.paren].end = -1;
4907 REGCP_UNWIND(ST.cp);
4909 if (--ST.count < ST.min)
4911 PL_reginput = locinput = HOPc(locinput, -1);
4912 goto curly_try_B_max;
4919 /* we've just finished A in /(??{A})B/; now continue with B */
4921 st->u.eval.toggle_reg_flags
4922 = cur_eval->u.eval.toggle_reg_flags;
4923 PL_reg_flags ^= st->u.eval.toggle_reg_flags;
4925 st->u.eval.prev_rex = rex_sv; /* inner */
4926 SETREX(rex_sv,cur_eval->u.eval.prev_rex);
4927 rex = (struct regexp *)SvANY(rex_sv);
4928 rexi = RXi_GET(rex);
4929 cur_curlyx = cur_eval->u.eval.prev_curlyx;
4930 ReREFCNT_inc(rex_sv);
4931 st->u.eval.cp = regcppush(0); /* Save *all* the positions. */
4933 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
4934 PL_reglastparen = &rex->lastparen;
4935 PL_reglastcloseparen = &rex->lastcloseparen;
4937 REGCP_SET(st->u.eval.lastcp);
4938 PL_reginput = locinput;
4940 /* Restore parens of the outer rex without popping the
4942 tmpix = PL_savestack_ix;
4943 PL_savestack_ix = cur_eval->u.eval.lastcp;
4945 PL_savestack_ix = tmpix;
4947 st->u.eval.prev_eval = cur_eval;
4948 cur_eval = cur_eval->u.eval.prev_eval;
4950 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
4951 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
4952 if ( nochange_depth )
4955 PUSH_YES_STATE_GOTO(EVAL_AB,
4956 st->u.eval.prev_eval->u.eval.B); /* match B */
4959 if (locinput < reginfo->till) {
4960 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4961 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
4963 (long)(locinput - PL_reg_starttry),
4964 (long)(reginfo->till - PL_reg_starttry),
4967 sayNO_SILENT; /* Cannot match: too short. */
4969 PL_reginput = locinput; /* put where regtry can find it */
4970 sayYES; /* Success! */
4972 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
4974 PerlIO_printf(Perl_debug_log,
4975 "%*s %ssubpattern success...%s\n",
4976 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
4977 PL_reginput = locinput; /* put where regtry can find it */
4978 sayYES; /* Success! */
4981 #define ST st->u.ifmatch
4983 case SUSPEND: /* (?>A) */
4985 PL_reginput = locinput;
4988 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
4990 goto ifmatch_trivial_fail_test;
4992 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
4994 ifmatch_trivial_fail_test:
4996 char * const s = HOPBACKc(locinput, scan->flags);
5001 sw = 1 - (bool)ST.wanted;
5005 next = scan + ARG(scan);
5013 PL_reginput = locinput;
5017 ST.logical = logical;
5018 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
5020 /* execute body of (?...A) */
5021 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
5024 case IFMATCH_A_fail: /* body of (?...A) failed */
5025 ST.wanted = !ST.wanted;
5028 case IFMATCH_A: /* body of (?...A) succeeded */
5030 sw = (bool)ST.wanted;
5032 else if (!ST.wanted)
5035 if (OP(ST.me) == SUSPEND)
5036 locinput = PL_reginput;
5038 locinput = PL_reginput = st->locinput;
5039 nextchr = UCHARAT(locinput);
5041 scan = ST.me + ARG(ST.me);
5044 continue; /* execute B */
5049 next = scan + ARG(scan);
5054 reginfo->cutpoint = PL_regeol;
5057 PL_reginput = locinput;
5059 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5060 PUSH_STATE_GOTO(COMMIT_next,next);
5062 case COMMIT_next_fail:
5069 #define ST st->u.mark
5071 ST.prev_mark = mark_state;
5072 ST.mark_name = sv_commit = sv_yes_mark
5073 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5075 ST.mark_loc = PL_reginput = locinput;
5076 PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5078 case MARKPOINT_next:
5079 mark_state = ST.prev_mark;
5082 case MARKPOINT_next_fail:
5083 if (popmark && sv_eq(ST.mark_name,popmark))
5085 if (ST.mark_loc > startpoint)
5086 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5087 popmark = NULL; /* we found our mark */
5088 sv_commit = ST.mark_name;
5091 PerlIO_printf(Perl_debug_log,
5092 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
5093 REPORT_CODE_OFF+depth*2, "",
5094 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5097 mark_state = ST.prev_mark;
5098 sv_yes_mark = mark_state ?
5099 mark_state->u.mark.mark_name : NULL;
5103 PL_reginput = locinput;
5105 /* (*SKIP) : if we fail we cut here*/
5106 ST.mark_name = NULL;
5107 ST.mark_loc = locinput;
5108 PUSH_STATE_GOTO(SKIP_next,next);
5110 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5111 otherwise do nothing. Meaning we need to scan
5113 regmatch_state *cur = mark_state;
5114 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5117 if ( sv_eq( cur->u.mark.mark_name,
5120 ST.mark_name = find;
5121 PUSH_STATE_GOTO( SKIP_next, next );
5123 cur = cur->u.mark.prev_mark;
5126 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5128 case SKIP_next_fail:
5130 /* (*CUT:NAME) - Set up to search for the name as we
5131 collapse the stack*/
5132 popmark = ST.mark_name;
5134 /* (*CUT) - No name, we cut here.*/
5135 if (ST.mark_loc > startpoint)
5136 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5137 /* but we set sv_commit to latest mark_name if there
5138 is one so they can test to see how things lead to this
5141 sv_commit=mark_state->u.mark.mark_name;
5149 if ( n == (U32)what_len_TRICKYFOLD(locinput,do_utf8,ln) ) {
5151 } else if ( 0xDF == n && !do_utf8 && !UTF ) {
5154 U8 folded[UTF8_MAXBYTES_CASE+1];
5156 const char * const l = locinput;
5157 char *e = PL_regeol;
5158 to_uni_fold(n, folded, &foldlen);
5160 if (ibcmp_utf8((const char*) folded, 0, foldlen, 1,
5161 l, &e, 0, do_utf8)) {
5166 nextchr = UCHARAT(locinput);
5169 if ((n=is_LNBREAK(locinput,do_utf8))) {
5171 nextchr = UCHARAT(locinput);
5176 #define CASE_CLASS(nAmE) \
5178 if ((n=is_##nAmE(locinput,do_utf8))) { \
5180 nextchr = UCHARAT(locinput); \
5185 if ((n=is_##nAmE(locinput,do_utf8))) { \
5188 locinput += UTF8SKIP(locinput); \
5189 nextchr = UCHARAT(locinput); \
5194 CASE_CLASS(HORIZWS);
5198 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5199 PTR2UV(scan), OP(scan));
5200 Perl_croak(aTHX_ "regexp memory corruption");
5204 /* switch break jumps here */
5205 scan = next; /* prepare to execute the next op and ... */
5206 continue; /* ... jump back to the top, reusing st */
5210 /* push a state that backtracks on success */
5211 st->u.yes.prev_yes_state = yes_state;
5215 /* push a new regex state, then continue at scan */
5217 regmatch_state *newst;
5220 regmatch_state *cur = st;
5221 regmatch_state *curyes = yes_state;
5223 regmatch_slab *slab = PL_regmatch_slab;
5224 for (;curd > -1;cur--,curd--) {
5225 if (cur < SLAB_FIRST(slab)) {
5227 cur = SLAB_LAST(slab);
5229 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5230 REPORT_CODE_OFF + 2 + depth * 2,"",
5231 curd, PL_reg_name[cur->resume_state],
5232 (curyes == cur) ? "yes" : ""
5235 curyes = cur->u.yes.prev_yes_state;
5238 DEBUG_STATE_pp("push")
5241 st->locinput = locinput;
5243 if (newst > SLAB_LAST(PL_regmatch_slab))
5244 newst = S_push_slab(aTHX);
5245 PL_regmatch_state = newst;
5247 locinput = PL_reginput;
5248 nextchr = UCHARAT(locinput);
5256 * We get here only if there's trouble -- normally "case END" is
5257 * the terminating point.
5259 Perl_croak(aTHX_ "corrupted regexp pointers");
5265 /* we have successfully completed a subexpression, but we must now
5266 * pop to the state marked by yes_state and continue from there */
5267 assert(st != yes_state);
5269 while (st != yes_state) {
5271 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5272 PL_regmatch_slab = PL_regmatch_slab->prev;
5273 st = SLAB_LAST(PL_regmatch_slab);
5277 DEBUG_STATE_pp("pop (no final)");
5279 DEBUG_STATE_pp("pop (yes)");
5285 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5286 || yes_state > SLAB_LAST(PL_regmatch_slab))
5288 /* not in this slab, pop slab */
5289 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5290 PL_regmatch_slab = PL_regmatch_slab->prev;
5291 st = SLAB_LAST(PL_regmatch_slab);
5293 depth -= (st - yes_state);
5296 yes_state = st->u.yes.prev_yes_state;
5297 PL_regmatch_state = st;
5300 locinput= st->locinput;
5301 nextchr = UCHARAT(locinput);
5303 state_num = st->resume_state + no_final;
5304 goto reenter_switch;
5307 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
5308 PL_colors[4], PL_colors[5]));
5310 if (PL_reg_eval_set) {
5311 /* each successfully executed (?{...}) block does the equivalent of
5312 * local $^R = do {...}
5313 * When popping the save stack, all these locals would be undone;
5314 * bypass this by setting the outermost saved $^R to the latest
5316 if (oreplsv != GvSV(PL_replgv))
5317 sv_setsv(oreplsv, GvSV(PL_replgv));
5324 PerlIO_printf(Perl_debug_log,
5325 "%*s %sfailed...%s\n",
5326 REPORT_CODE_OFF+depth*2, "",
5327 PL_colors[4], PL_colors[5])
5339 /* there's a previous state to backtrack to */
5341 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5342 PL_regmatch_slab = PL_regmatch_slab->prev;
5343 st = SLAB_LAST(PL_regmatch_slab);
5345 PL_regmatch_state = st;
5346 locinput= st->locinput;
5347 nextchr = UCHARAT(locinput);
5349 DEBUG_STATE_pp("pop");
5351 if (yes_state == st)
5352 yes_state = st->u.yes.prev_yes_state;
5354 state_num = st->resume_state + 1; /* failure = success + 1 */
5355 goto reenter_switch;
5360 if (rex->intflags & PREGf_VERBARG_SEEN) {
5361 SV *sv_err = get_sv("REGERROR", 1);
5362 SV *sv_mrk = get_sv("REGMARK", 1);
5364 sv_commit = &PL_sv_no;
5366 sv_yes_mark = &PL_sv_yes;
5369 sv_commit = &PL_sv_yes;
5370 sv_yes_mark = &PL_sv_no;
5372 sv_setsv(sv_err, sv_commit);
5373 sv_setsv(sv_mrk, sv_yes_mark);
5376 /* clean up; in particular, free all slabs above current one */
5377 LEAVE_SCOPE(oldsave);
5383 - regrepeat - repeatedly match something simple, report how many
5386 * [This routine now assumes that it will only match on things of length 1.
5387 * That was true before, but now we assume scan - reginput is the count,
5388 * rather than incrementing count on every character. [Er, except utf8.]]
5391 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
5394 register char *scan;
5396 register char *loceol = PL_regeol;
5397 register I32 hardcount = 0;
5398 register bool do_utf8 = PL_reg_match_utf8;
5400 PERL_UNUSED_ARG(depth);
5403 PERL_ARGS_ASSERT_REGREPEAT;
5406 if (max == REG_INFTY)
5408 else if (max < loceol - scan)
5409 loceol = scan + max;
5414 while (scan < loceol && hardcount < max && *scan != '\n') {
5415 scan += UTF8SKIP(scan);
5419 while (scan < loceol && *scan != '\n')
5426 while (scan < loceol && hardcount < max) {
5427 scan += UTF8SKIP(scan);
5437 case EXACT: /* length of string is 1 */
5439 while (scan < loceol && UCHARAT(scan) == c)
5442 case EXACTF: /* length of string is 1 */
5444 while (scan < loceol &&
5445 (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold[c]))
5448 case EXACTFL: /* length of string is 1 */
5449 PL_reg_flags |= RF_tainted;
5451 while (scan < loceol &&
5452 (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold_locale[c]))
5458 while (hardcount < max && scan < loceol &&
5459 reginclass(prog, p, (U8*)scan, 0, do_utf8)) {
5460 scan += UTF8SKIP(scan);
5464 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
5471 LOAD_UTF8_CHARCLASS_ALNUM();
5472 while (hardcount < max && scan < loceol &&
5473 swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
5474 scan += UTF8SKIP(scan);
5478 while (scan < loceol && isALNUM(*scan))
5483 PL_reg_flags |= RF_tainted;
5486 while (hardcount < max && scan < loceol &&
5487 isALNUM_LC_utf8((U8*)scan)) {
5488 scan += UTF8SKIP(scan);
5492 while (scan < loceol && isALNUM_LC(*scan))
5499 LOAD_UTF8_CHARCLASS_ALNUM();
5500 while (hardcount < max && scan < loceol &&
5501 !swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
5502 scan += UTF8SKIP(scan);
5506 while (scan < loceol && !isALNUM(*scan))
5511 PL_reg_flags |= RF_tainted;
5514 while (hardcount < max && scan < loceol &&
5515 !isALNUM_LC_utf8((U8*)scan)) {
5516 scan += UTF8SKIP(scan);
5520 while (scan < loceol && !isALNUM_LC(*scan))
5527 LOAD_UTF8_CHARCLASS_SPACE();
5528 while (hardcount < max && scan < loceol &&
5530 swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
5531 scan += UTF8SKIP(scan);
5535 while (scan < loceol && isSPACE(*scan))
5540 PL_reg_flags |= RF_tainted;
5543 while (hardcount < max && scan < loceol &&
5544 (*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
5545 scan += UTF8SKIP(scan);
5549 while (scan < loceol && isSPACE_LC(*scan))
5556 LOAD_UTF8_CHARCLASS_SPACE();
5557 while (hardcount < max && scan < loceol &&
5559 swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
5560 scan += UTF8SKIP(scan);
5564 while (scan < loceol && !isSPACE(*scan))
5569 PL_reg_flags |= RF_tainted;
5572 while (hardcount < max && scan < loceol &&
5573 !(*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
5574 scan += UTF8SKIP(scan);
5578 while (scan < loceol && !isSPACE_LC(*scan))
5585 LOAD_UTF8_CHARCLASS_DIGIT();
5586 while (hardcount < max && scan < loceol &&
5587 swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
5588 scan += UTF8SKIP(scan);
5592 while (scan < loceol && isDIGIT(*scan))
5599 LOAD_UTF8_CHARCLASS_DIGIT();
5600 while (hardcount < max && scan < loceol &&
5601 !swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
5602 scan += UTF8SKIP(scan);
5606 while (scan < loceol && !isDIGIT(*scan))
5612 while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
5618 LNBREAK can match two latin chars, which is ok,
5619 because we have a null terminated string, but we
5620 have to use hardcount in this situation
5622 while (scan < loceol && (c=is_LNBREAK_latin1(scan))) {
5631 while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
5636 while (scan < loceol && is_HORIZWS_latin1(scan))
5643 while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
5644 scan += UTF8SKIP(scan);
5648 while (scan < loceol && !is_HORIZWS_latin1(scan))
5656 while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
5661 while (scan < loceol && is_VERTWS_latin1(scan))
5669 while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
5670 scan += UTF8SKIP(scan);
5674 while (scan < loceol && !is_VERTWS_latin1(scan))
5680 default: /* Called on something of 0 width. */
5681 break; /* So match right here or not at all. */
5687 c = scan - PL_reginput;
5691 GET_RE_DEBUG_FLAGS_DECL;
5693 SV * const prop = sv_newmortal();
5694 regprop(prog, prop, p);
5695 PerlIO_printf(Perl_debug_log,
5696 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
5697 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
5705 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
5707 - regclass_swash - prepare the utf8 swash
5711 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
5717 RXi_GET_DECL(prog,progi);
5718 const struct reg_data * const data = prog ? progi->data : NULL;
5720 PERL_ARGS_ASSERT_REGCLASS_SWASH;
5722 if (data && data->count) {
5723 const U32 n = ARG(node);
5725 if (data->what[n] == 's') {
5726 SV * const rv = MUTABLE_SV(data->data[n]);
5727 AV * const av = MUTABLE_AV(SvRV(rv));
5728 SV **const ary = AvARRAY(av);
5731 /* See the end of regcomp.c:S_regclass() for
5732 * documentation of these array elements. */
5735 a = SvROK(ary[1]) ? &ary[1] : NULL;
5736 b = SvTYPE(ary[2]) == SVt_PVAV ? &ary[2] : NULL;
5740 else if (si && doinit) {
5741 sw = swash_init("utf8", "", si, 1, 0);
5742 (void)av_store(av, 1, sw);
5759 - reginclass - determine if a character falls into a character class
5761 The n is the ANYOF regnode, the p is the target string, lenp
5762 is pointer to the maximum length of how far to go in the p
5763 (if the lenp is zero, UTF8SKIP(p) is used),
5764 do_utf8 tells whether the target string is in UTF-8.
5769 S_reginclass(pTHX_ const regexp *prog, register const regnode *n, register const U8* p, STRLEN* lenp, register bool do_utf8)
5772 const char flags = ANYOF_FLAGS(n);
5778 PERL_ARGS_ASSERT_REGINCLASS;
5780 if (do_utf8 && !UTF8_IS_INVARIANT(c)) {
5781 c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &len,
5782 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV) | UTF8_CHECK_ONLY);
5783 /* see [perl #37836] for UTF8_ALLOW_ANYUV */
5784 if (len == (STRLEN)-1)
5785 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
5788 plen = lenp ? *lenp : UNISKIP(NATIVE_TO_UNI(c));
5789 if (do_utf8 || (flags & ANYOF_UNICODE)) {
5792 if (do_utf8 && !ANYOF_RUNTIME(n)) {
5793 if (len != (STRLEN)-1 && c < 256 && ANYOF_BITMAP_TEST(n, c))
5796 if (!match && do_utf8 && (flags & ANYOF_UNICODE_ALL) && c >= 256)
5800 SV * const sw = regclass_swash(prog, n, TRUE, 0, (SV**)&av);
5808 utf8_p = bytes_to_utf8(p, &len);
5810 if (swash_fetch(sw, utf8_p, 1))
5812 else if (flags & ANYOF_FOLD) {
5813 if (!match && lenp && av) {
5815 for (i = 0; i <= av_len(av); i++) {
5816 SV* const sv = *av_fetch(av, i, FALSE);
5818 const char * const s = SvPV_const(sv, len);
5819 if (len <= plen && memEQ(s, (char*)utf8_p, len)) {
5827 U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5830 to_utf8_fold(utf8_p, tmpbuf, &tmplen);
5831 if (swash_fetch(sw, tmpbuf, 1))
5836 /* If we allocated a string above, free it */
5837 if (! do_utf8) Safefree(utf8_p);
5840 if (match && lenp && *lenp == 0)
5841 *lenp = UNISKIP(NATIVE_TO_UNI(c));
5843 if (!match && c < 256) {
5844 if (ANYOF_BITMAP_TEST(n, c))
5846 else if (flags & ANYOF_FOLD) {
5849 if (flags & ANYOF_LOCALE) {
5850 PL_reg_flags |= RF_tainted;
5851 f = PL_fold_locale[c];
5855 if (f != c && ANYOF_BITMAP_TEST(n, f))
5859 if (!match && (flags & ANYOF_CLASS)) {
5860 PL_reg_flags |= RF_tainted;
5862 (ANYOF_CLASS_TEST(n, ANYOF_ALNUM) && isALNUM_LC(c)) ||
5863 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM) && !isALNUM_LC(c)) ||
5864 (ANYOF_CLASS_TEST(n, ANYOF_SPACE) && isSPACE_LC(c)) ||
5865 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE) && !isSPACE_LC(c)) ||
5866 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT) && isDIGIT_LC(c)) ||
5867 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT) && !isDIGIT_LC(c)) ||
5868 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC) && isALNUMC_LC(c)) ||
5869 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
5870 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA) && isALPHA_LC(c)) ||
5871 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA) && !isALPHA_LC(c)) ||
5872 (ANYOF_CLASS_TEST(n, ANYOF_ASCII) && isASCII(c)) ||
5873 (ANYOF_CLASS_TEST(n, ANYOF_NASCII) && !isASCII(c)) ||
5874 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL) && isCNTRL_LC(c)) ||
5875 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL) && !isCNTRL_LC(c)) ||
5876 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH) && isGRAPH_LC(c)) ||
5877 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH) && !isGRAPH_LC(c)) ||
5878 (ANYOF_CLASS_TEST(n, ANYOF_LOWER) && isLOWER_LC(c)) ||
5879 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER) && !isLOWER_LC(c)) ||
5880 (ANYOF_CLASS_TEST(n, ANYOF_PRINT) && isPRINT_LC(c)) ||
5881 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT) && !isPRINT_LC(c)) ||
5882 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT) && isPUNCT_LC(c)) ||
5883 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT) && !isPUNCT_LC(c)) ||
5884 (ANYOF_CLASS_TEST(n, ANYOF_UPPER) && isUPPER_LC(c)) ||
5885 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER) && !isUPPER_LC(c)) ||
5886 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT) && isXDIGIT(c)) ||
5887 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c)) ||
5888 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC) && isPSXSPC(c)) ||
5889 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c)) ||
5890 (ANYOF_CLASS_TEST(n, ANYOF_BLANK) && isBLANK(c)) ||
5891 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK) && !isBLANK(c))
5892 ) /* How's that for a conditional? */
5899 return (flags & ANYOF_INVERT) ? !match : match;
5903 S_reghop3(U8 *s, I32 off, const U8* lim)
5907 PERL_ARGS_ASSERT_REGHOP3;
5910 while (off-- && s < lim) {
5911 /* XXX could check well-formedness here */
5916 while (off++ && s > lim) {
5918 if (UTF8_IS_CONTINUED(*s)) {
5919 while (s > lim && UTF8_IS_CONTINUATION(*s))
5922 /* XXX could check well-formedness here */
5929 /* there are a bunch of places where we use two reghop3's that should
5930 be replaced with this routine. but since thats not done yet
5931 we ifdef it out - dmq
5934 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
5938 PERL_ARGS_ASSERT_REGHOP4;
5941 while (off-- && s < rlim) {
5942 /* XXX could check well-formedness here */
5947 while (off++ && s > llim) {
5949 if (UTF8_IS_CONTINUED(*s)) {
5950 while (s > llim && UTF8_IS_CONTINUATION(*s))
5953 /* XXX could check well-formedness here */
5961 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
5965 PERL_ARGS_ASSERT_REGHOPMAYBE3;
5968 while (off-- && s < lim) {
5969 /* XXX could check well-formedness here */
5976 while (off++ && s > lim) {
5978 if (UTF8_IS_CONTINUED(*s)) {
5979 while (s > lim && UTF8_IS_CONTINUATION(*s))
5982 /* XXX could check well-formedness here */
5991 restore_pos(pTHX_ void *arg)
5994 regexp * const rex = (regexp *)arg;
5995 if (PL_reg_eval_set) {
5996 if (PL_reg_oldsaved) {
5997 rex->subbeg = PL_reg_oldsaved;
5998 rex->sublen = PL_reg_oldsavedlen;
5999 #ifdef PERL_OLD_COPY_ON_WRITE
6000 rex->saved_copy = PL_nrs;
6002 RXp_MATCH_COPIED_on(rex);
6004 PL_reg_magic->mg_len = PL_reg_oldpos;
6005 PL_reg_eval_set = 0;
6006 PL_curpm = PL_reg_oldcurpm;
6011 S_to_utf8_substr(pTHX_ register regexp *prog)
6015 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
6018 if (prog->substrs->data[i].substr
6019 && !prog->substrs->data[i].utf8_substr) {
6020 SV* const sv = newSVsv(prog->substrs->data[i].substr);
6021 prog->substrs->data[i].utf8_substr = sv;
6022 sv_utf8_upgrade(sv);
6023 if (SvVALID(prog->substrs->data[i].substr)) {
6024 const U8 flags = BmFLAGS(prog->substrs->data[i].substr);
6025 if (flags & FBMcf_TAIL) {
6026 /* Trim the trailing \n that fbm_compile added last
6028 SvCUR_set(sv, SvCUR(sv) - 1);
6029 /* Whilst this makes the SV technically "invalid" (as its
6030 buffer is no longer followed by "\0") when fbm_compile()
6031 adds the "\n" back, a "\0" is restored. */
6033 fbm_compile(sv, flags);
6035 if (prog->substrs->data[i].substr == prog->check_substr)
6036 prog->check_utf8 = sv;
6042 S_to_byte_substr(pTHX_ register regexp *prog)
6047 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
6050 if (prog->substrs->data[i].utf8_substr
6051 && !prog->substrs->data[i].substr) {
6052 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
6053 if (sv_utf8_downgrade(sv, TRUE)) {
6054 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
6056 = BmFLAGS(prog->substrs->data[i].utf8_substr);
6057 if (flags & FBMcf_TAIL) {
6058 /* Trim the trailing \n that fbm_compile added last
6060 SvCUR_set(sv, SvCUR(sv) - 1);
6062 fbm_compile(sv, flags);
6068 prog->substrs->data[i].substr = sv;
6069 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
6070 prog->check_substr = sv;
6077 * c-indentation-style: bsd
6079 * indent-tabs-mode: t
6082 * ex: set ts=8 sts=4 sw=4 noet: