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
75 #undef PERL_IN_XSUB_RE
76 #define PERL_IN_XSUB_RE 1
79 #undef PERL_IN_XSUB_RE
81 #ifdef PERL_IN_XSUB_RE
87 #define RF_tainted 1 /* tainted information used? */
88 #define RF_warned 2 /* warned about big count? */
90 #define RF_utf8 8 /* Pattern contains multibyte chars? */
92 #define UTF ((PL_reg_flags & RF_utf8) != 0)
94 #define RS_init 1 /* eval environment created */
95 #define RS_set 2 /* replsv value is set */
101 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) : ANYOF_BITMAP_TEST(p,*(c)))
107 #define CHR_SVLEN(sv) (do_utf8 ? sv_len_utf8(sv) : SvCUR(sv))
108 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
110 #define HOPc(pos,off) \
111 (char *)(PL_reg_match_utf8 \
112 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
114 #define HOPBACKc(pos, off) \
115 (char*)(PL_reg_match_utf8\
116 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
117 : (pos - off >= PL_bostr) \
121 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
122 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
124 #define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
125 if (!CAT2(PL_utf8_,class)) { bool ok; ENTER; save_re_context(); ok=CAT2(is_utf8_,class)((const U8*)str); assert(ok); LEAVE; } } STMT_END
126 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
127 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
128 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
129 #define LOAD_UTF8_CHARCLASS_MARK() LOAD_UTF8_CHARCLASS(mark, "\xcd\x86")
131 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
133 /* for use after a quantifier and before an EXACT-like node -- japhy */
134 /* it would be nice to rework regcomp.sym to generate this stuff. sigh */
135 #define JUMPABLE(rn) ( \
137 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
139 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
140 OP(rn) == PLUS || OP(rn) == MINMOD || \
141 OP(rn) == KEEPS || (PL_regkind[OP(rn)] == VERB) || \
142 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
144 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
146 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
149 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
150 we don't need this definition. */
151 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
152 #define IS_TEXTF(rn) ( OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
153 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
156 /* ... so we use this as its faster. */
157 #define IS_TEXT(rn) ( OP(rn)==EXACT )
158 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
159 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
164 Search for mandatory following text node; for lookahead, the text must
165 follow but for lookbehind (rn->flags != 0) we skip to the next step.
167 #define FIND_NEXT_IMPT(rn) STMT_START { \
168 while (JUMPABLE(rn)) { \
169 const OPCODE type = OP(rn); \
170 if (type == SUSPEND || PL_regkind[type] == CURLY) \
171 rn = NEXTOPER(NEXTOPER(rn)); \
172 else if (type == PLUS) \
174 else if (type == IFMATCH) \
175 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
176 else rn += NEXT_OFF(rn); \
181 static void restore_pos(pTHX_ void *arg);
184 S_regcppush(pTHX_ I32 parenfloor)
187 const int retval = PL_savestack_ix;
188 #define REGCP_PAREN_ELEMS 4
189 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
191 GET_RE_DEBUG_FLAGS_DECL;
193 if (paren_elems_to_push < 0)
194 Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
196 #define REGCP_OTHER_ELEMS 7
197 SSGROW(paren_elems_to_push + REGCP_OTHER_ELEMS);
199 for (p = PL_regsize; p > parenfloor; p--) {
200 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
201 SSPUSHINT(PL_regoffs[p].end);
202 SSPUSHINT(PL_regoffs[p].start);
203 SSPUSHPTR(PL_reg_start_tmp[p]);
205 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
206 " saving \\%"UVuf" %"IVdf"(%"IVdf")..%"IVdf"\n",
207 (UV)p, (IV)PL_regoffs[p].start,
208 (IV)(PL_reg_start_tmp[p] - PL_bostr),
209 (IV)PL_regoffs[p].end
212 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
213 SSPUSHPTR(PL_regoffs);
214 SSPUSHINT(PL_regsize);
215 SSPUSHINT(*PL_reglastparen);
216 SSPUSHINT(*PL_reglastcloseparen);
217 SSPUSHPTR(PL_reginput);
218 #define REGCP_FRAME_ELEMS 2
219 /* REGCP_FRAME_ELEMS are part of the REGCP_OTHER_ELEMS and
220 * are needed for the regexp context stack bookkeeping. */
221 SSPUSHINT(paren_elems_to_push + REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
222 SSPUSHINT(SAVEt_REGCONTEXT); /* Magic cookie. */
227 /* These are needed since we do not localize EVAL nodes: */
228 #define REGCP_SET(cp) \
230 PerlIO_printf(Perl_debug_log, \
231 " Setting an EVAL scope, savestack=%"IVdf"\n", \
232 (IV)PL_savestack_ix)); \
235 #define REGCP_UNWIND(cp) \
237 if (cp != PL_savestack_ix) \
238 PerlIO_printf(Perl_debug_log, \
239 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
240 (IV)(cp), (IV)PL_savestack_ix)); \
244 S_regcppop(pTHX_ const regexp *rex)
249 GET_RE_DEBUG_FLAGS_DECL;
251 PERL_ARGS_ASSERT_REGCPPOP;
253 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
255 assert(i == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
256 i = SSPOPINT; /* Parentheses elements to pop. */
257 input = (char *) SSPOPPTR;
258 *PL_reglastcloseparen = SSPOPINT;
259 *PL_reglastparen = SSPOPINT;
260 PL_regsize = SSPOPINT;
261 PL_regoffs=(regexp_paren_pair *) SSPOPPTR;
264 /* Now restore the parentheses context. */
265 for (i -= (REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
266 i > 0; i -= REGCP_PAREN_ELEMS) {
268 U32 paren = (U32)SSPOPINT;
269 PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
270 PL_regoffs[paren].start = SSPOPINT;
272 if (paren <= *PL_reglastparen)
273 PL_regoffs[paren].end = tmps;
275 PerlIO_printf(Perl_debug_log,
276 " restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
277 (UV)paren, (IV)PL_regoffs[paren].start,
278 (IV)(PL_reg_start_tmp[paren] - PL_bostr),
279 (IV)PL_regoffs[paren].end,
280 (paren > *PL_reglastparen ? "(no)" : ""));
284 if (*PL_reglastparen + 1 <= rex->nparens) {
285 PerlIO_printf(Perl_debug_log,
286 " restoring \\%"IVdf"..\\%"IVdf" to undef\n",
287 (IV)(*PL_reglastparen + 1), (IV)rex->nparens);
291 /* It would seem that the similar code in regtry()
292 * already takes care of this, and in fact it is in
293 * a better location to since this code can #if 0-ed out
294 * but the code in regtry() is needed or otherwise tests
295 * requiring null fields (pat.t#187 and split.t#{13,14}
296 * (as of patchlevel 7877) will fail. Then again,
297 * this code seems to be necessary or otherwise
298 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
299 * --jhi updated by dapm */
300 for (i = *PL_reglastparen + 1; i <= rex->nparens; i++) {
302 PL_regoffs[i].start = -1;
303 PL_regoffs[i].end = -1;
309 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
312 * pregexec and friends
315 #ifndef PERL_IN_XSUB_RE
317 - pregexec - match a regexp against a string
320 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
321 char *strbeg, I32 minend, SV *screamer, U32 nosave)
322 /* strend: pointer to null at end of string */
323 /* strbeg: real beginning of string */
324 /* minend: end of match must be >=minend after stringarg. */
325 /* nosave: For optimizations. */
327 PERL_ARGS_ASSERT_PREGEXEC;
330 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
331 nosave ? 0 : REXEC_COPY_STR);
336 * Need to implement the following flags for reg_anch:
338 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
340 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
341 * INTUIT_AUTORITATIVE_ML
342 * INTUIT_ONCE_NOML - Intuit can match in one location only.
345 * Another flag for this function: SECOND_TIME (so that float substrs
346 * with giant delta may be not rechecked).
349 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
351 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
352 Otherwise, only SvCUR(sv) is used to get strbeg. */
354 /* XXXX We assume that strpos is strbeg unless sv. */
356 /* XXXX Some places assume that there is a fixed substring.
357 An update may be needed if optimizer marks as "INTUITable"
358 RExen without fixed substrings. Similarly, it is assumed that
359 lengths of all the strings are no more than minlen, thus they
360 cannot come from lookahead.
361 (Or minlen should take into account lookahead.)
362 NOTE: Some of this comment is not correct. minlen does now take account
363 of lookahead/behind. Further research is required. -- demerphq
367 /* A failure to find a constant substring means that there is no need to make
368 an expensive call to REx engine, thus we celebrate a failure. Similarly,
369 finding a substring too deep into the string means that less calls to
370 regtry() should be needed.
372 REx compiler's optimizer found 4 possible hints:
373 a) Anchored substring;
375 c) Whether we are anchored (beginning-of-line or \G);
376 d) First node (of those at offset 0) which may distingush positions;
377 We use a)b)d) and multiline-part of c), and try to find a position in the
378 string which does not contradict any of them.
381 /* Most of decisions we do here should have been done at compile time.
382 The nodes of the REx which we used for the search should have been
383 deleted from the finite automaton. */
386 Perl_re_intuit_start(pTHX_ REGEXP * const prog, SV *sv, char *strpos,
387 char *strend, const U32 flags, re_scream_pos_data *data)
390 register I32 start_shift = 0;
391 /* Should be nonnegative! */
392 register I32 end_shift = 0;
397 const bool do_utf8 = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
399 register char *other_last = NULL; /* other substr checked before this */
400 char *check_at = NULL; /* check substr found at this pos */
401 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
402 RXi_GET_DECL(prog,progi);
404 const char * const i_strpos = strpos;
406 GET_RE_DEBUG_FLAGS_DECL;
408 PERL_ARGS_ASSERT_RE_INTUIT_START;
410 RX_MATCH_UTF8_set(prog,do_utf8);
413 PL_reg_flags |= RF_utf8;
416 debug_start_match(prog, do_utf8, strpos, strend,
417 sv ? "Guessing start of match in sv for"
418 : "Guessing start of match in string for");
421 /* CHR_DIST() would be more correct here but it makes things slow. */
422 if (prog->minlen > strend - strpos) {
423 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
424 "String too short... [re_intuit_start]\n"));
428 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
431 if (!prog->check_utf8 && prog->check_substr)
432 to_utf8_substr(prog);
433 check = prog->check_utf8;
435 if (!prog->check_substr && prog->check_utf8)
436 to_byte_substr(prog);
437 check = prog->check_substr;
439 if (check == &PL_sv_undef) {
440 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
441 "Non-utf8 string cannot match utf8 check string\n"));
444 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
445 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
446 || ( (prog->extflags & RXf_ANCH_BOL)
447 && !multiline ) ); /* Check after \n? */
450 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
451 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
452 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
454 && (strpos != strbeg)) {
455 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
458 if (prog->check_offset_min == prog->check_offset_max &&
459 !(prog->extflags & RXf_CANY_SEEN)) {
460 /* Substring at constant offset from beg-of-str... */
463 s = HOP3c(strpos, prog->check_offset_min, strend);
466 slen = SvCUR(check); /* >= 1 */
468 if ( strend - s > slen || strend - s < slen - 1
469 || (strend - s == slen && strend[-1] != '\n')) {
470 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
473 /* Now should match s[0..slen-2] */
475 if (slen && (*SvPVX_const(check) != *s
477 && memNE(SvPVX_const(check), s, slen)))) {
479 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
483 else if (*SvPVX_const(check) != *s
484 || ((slen = SvCUR(check)) > 1
485 && memNE(SvPVX_const(check), s, slen)))
488 goto success_at_start;
491 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
493 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
494 end_shift = prog->check_end_shift;
497 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
498 - (SvTAIL(check) != 0);
499 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
501 if (end_shift < eshift)
505 else { /* Can match at random position */
508 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
509 end_shift = prog->check_end_shift;
511 /* end shift should be non negative here */
514 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
516 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
517 (IV)end_shift, RX_PRECOMP(prog));
521 /* Find a possible match in the region s..strend by looking for
522 the "check" substring in the region corrected by start/end_shift. */
525 I32 srch_start_shift = start_shift;
526 I32 srch_end_shift = end_shift;
527 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
528 srch_end_shift -= ((strbeg - s) - srch_start_shift);
529 srch_start_shift = strbeg - s;
531 DEBUG_OPTIMISE_MORE_r({
532 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
533 (IV)prog->check_offset_min,
534 (IV)srch_start_shift,
536 (IV)prog->check_end_shift);
539 if (flags & REXEC_SCREAM) {
540 I32 p = -1; /* Internal iterator of scream. */
541 I32 * const pp = data ? data->scream_pos : &p;
543 if (PL_screamfirst[BmRARE(check)] >= 0
544 || ( BmRARE(check) == '\n'
545 && (BmPREVIOUS(check) == SvCUR(check) - 1)
547 s = screaminstr(sv, check,
548 srch_start_shift + (s - strbeg), srch_end_shift, pp, 0);
551 /* we may be pointing at the wrong string */
552 if (s && RXp_MATCH_COPIED(prog))
553 s = strbeg + (s - SvPVX_const(sv));
555 *data->scream_olds = s;
560 if (prog->extflags & RXf_CANY_SEEN) {
561 start_point= (U8*)(s + srch_start_shift);
562 end_point= (U8*)(strend - srch_end_shift);
564 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
565 end_point= HOP3(strend, -srch_end_shift, strbeg);
567 DEBUG_OPTIMISE_MORE_r({
568 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
569 (int)(end_point - start_point),
570 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
574 s = fbm_instr( start_point, end_point,
575 check, multiline ? FBMrf_MULTILINE : 0);
578 /* Update the count-of-usability, remove useless subpatterns,
582 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
583 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
584 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
585 (s ? "Found" : "Did not find"),
586 (check == (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)
587 ? "anchored" : "floating"),
590 (s ? " at offset " : "...\n") );
595 /* Finish the diagnostic message */
596 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
598 /* XXX dmq: first branch is for positive lookbehind...
599 Our check string is offset from the beginning of the pattern.
600 So we need to do any stclass tests offset forward from that
609 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
610 Start with the other substr.
611 XXXX no SCREAM optimization yet - and a very coarse implementation
612 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
613 *always* match. Probably should be marked during compile...
614 Probably it is right to do no SCREAM here...
617 if (do_utf8 ? (prog->float_utf8 && prog->anchored_utf8)
618 : (prog->float_substr && prog->anchored_substr))
620 /* Take into account the "other" substring. */
621 /* XXXX May be hopelessly wrong for UTF... */
624 if (check == (do_utf8 ? prog->float_utf8 : prog->float_substr)) {
627 char * const last = HOP3c(s, -start_shift, strbeg);
629 char * const saved_s = s;
632 t = s - prog->check_offset_max;
633 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
635 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
640 t = HOP3c(t, prog->anchored_offset, strend);
641 if (t < other_last) /* These positions already checked */
643 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
646 /* XXXX It is not documented what units *_offsets are in.
647 We assume bytes, but this is clearly wrong.
648 Meaning this code needs to be carefully reviewed for errors.
652 /* On end-of-str: see comment below. */
653 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
654 if (must == &PL_sv_undef) {
656 DEBUG_r(must = prog->anchored_utf8); /* for debug */
661 HOP3(HOP3(last1, prog->anchored_offset, strend)
662 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
664 multiline ? FBMrf_MULTILINE : 0
667 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
668 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
669 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
670 (s ? "Found" : "Contradicts"),
671 quoted, RE_SV_TAIL(must));
676 if (last1 >= last2) {
677 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
678 ", giving up...\n"));
681 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
682 ", trying floating at offset %ld...\n",
683 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
684 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
685 s = HOP3c(last, 1, strend);
689 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
690 (long)(s - i_strpos)));
691 t = HOP3c(s, -prog->anchored_offset, strbeg);
692 other_last = HOP3c(s, 1, strend);
700 else { /* Take into account the floating substring. */
702 char * const saved_s = s;
705 t = HOP3c(s, -start_shift, strbeg);
707 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
708 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
709 last = HOP3c(t, prog->float_max_offset, strend);
710 s = HOP3c(t, prog->float_min_offset, strend);
713 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
714 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
715 /* fbm_instr() takes into account exact value of end-of-str
716 if the check is SvTAIL(ed). Since false positives are OK,
717 and end-of-str is not later than strend we are OK. */
718 if (must == &PL_sv_undef) {
720 DEBUG_r(must = prog->float_utf8); /* for debug message */
723 s = fbm_instr((unsigned char*)s,
724 (unsigned char*)last + SvCUR(must)
726 must, multiline ? FBMrf_MULTILINE : 0);
728 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
729 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
730 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
731 (s ? "Found" : "Contradicts"),
732 quoted, RE_SV_TAIL(must));
736 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
737 ", giving up...\n"));
740 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
741 ", trying anchored starting at offset %ld...\n",
742 (long)(saved_s + 1 - i_strpos)));
744 s = HOP3c(t, 1, strend);
748 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
749 (long)(s - i_strpos)));
750 other_last = s; /* Fix this later. --Hugo */
760 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
762 DEBUG_OPTIMISE_MORE_r(
763 PerlIO_printf(Perl_debug_log,
764 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
765 (IV)prog->check_offset_min,
766 (IV)prog->check_offset_max,
774 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
776 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
779 /* Fixed substring is found far enough so that the match
780 cannot start at strpos. */
782 if (ml_anch && t[-1] != '\n') {
783 /* Eventually fbm_*() should handle this, but often
784 anchored_offset is not 0, so this check will not be wasted. */
785 /* XXXX In the code below we prefer to look for "^" even in
786 presence of anchored substrings. And we search even
787 beyond the found float position. These pessimizations
788 are historical artefacts only. */
790 while (t < strend - prog->minlen) {
792 if (t < check_at - prog->check_offset_min) {
793 if (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) {
794 /* Since we moved from the found position,
795 we definitely contradict the found anchored
796 substr. Due to the above check we do not
797 contradict "check" substr.
798 Thus we can arrive here only if check substr
799 is float. Redo checking for "other"=="fixed".
802 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
803 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
804 goto do_other_anchored;
806 /* We don't contradict the found floating substring. */
807 /* XXXX Why not check for STCLASS? */
809 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
810 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
813 /* Position contradicts check-string */
814 /* XXXX probably better to look for check-string
815 than for "\n", so one should lower the limit for t? */
816 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
817 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
818 other_last = strpos = s = t + 1;
823 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
824 PL_colors[0], PL_colors[1]));
828 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
829 PL_colors[0], PL_colors[1]));
833 ++BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
836 /* The found string does not prohibit matching at strpos,
837 - no optimization of calling REx engine can be performed,
838 unless it was an MBOL and we are not after MBOL,
839 or a future STCLASS check will fail this. */
841 /* Even in this situation we may use MBOL flag if strpos is offset
842 wrt the start of the string. */
843 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
844 && (strpos != strbeg) && strpos[-1] != '\n'
845 /* May be due to an implicit anchor of m{.*foo} */
846 && !(prog->intflags & PREGf_IMPLICIT))
851 DEBUG_EXECUTE_r( if (ml_anch)
852 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
853 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
856 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
858 prog->check_utf8 /* Could be deleted already */
859 && --BmUSEFUL(prog->check_utf8) < 0
860 && (prog->check_utf8 == prog->float_utf8)
862 prog->check_substr /* Could be deleted already */
863 && --BmUSEFUL(prog->check_substr) < 0
864 && (prog->check_substr == prog->float_substr)
867 /* If flags & SOMETHING - do not do it many times on the same match */
868 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
869 SvREFCNT_dec(do_utf8 ? prog->check_utf8 : prog->check_substr);
870 if (do_utf8 ? prog->check_substr : prog->check_utf8)
871 SvREFCNT_dec(do_utf8 ? prog->check_substr : prog->check_utf8);
872 prog->check_substr = prog->check_utf8 = NULL; /* disable */
873 prog->float_substr = prog->float_utf8 = NULL; /* clear */
874 check = NULL; /* abort */
876 /* XXXX This is a remnant of the old implementation. It
877 looks wasteful, since now INTUIT can use many
879 prog->extflags &= ~RXf_USE_INTUIT;
886 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
887 /* trie stclasses are too expensive to use here, we are better off to
888 leave it to regmatch itself */
889 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
890 /* minlen == 0 is possible if regstclass is \b or \B,
891 and the fixed substr is ''$.
892 Since minlen is already taken into account, s+1 is before strend;
893 accidentally, minlen >= 1 guaranties no false positives at s + 1
894 even for \b or \B. But (minlen? 1 : 0) below assumes that
895 regstclass does not come from lookahead... */
896 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
897 This leaves EXACTF only, which is dealt with in find_byclass(). */
898 const U8* const str = (U8*)STRING(progi->regstclass);
899 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
900 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
903 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
904 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
905 else if (prog->float_substr || prog->float_utf8)
906 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
910 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf"\n",
911 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg)));
914 s = find_byclass(prog, progi->regstclass, s, endpos, NULL);
917 const char *what = NULL;
919 if (endpos == strend) {
920 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
921 "Could not match STCLASS...\n") );
924 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
925 "This position contradicts STCLASS...\n") );
926 if ((prog->extflags & RXf_ANCH) && !ml_anch)
928 /* Contradict one of substrings */
929 if (prog->anchored_substr || prog->anchored_utf8) {
930 if ((do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) == check) {
931 DEBUG_EXECUTE_r( what = "anchored" );
933 s = HOP3c(t, 1, strend);
934 if (s + start_shift + end_shift > strend) {
935 /* XXXX Should be taken into account earlier? */
936 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
937 "Could not match STCLASS...\n") );
942 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
943 "Looking for %s substr starting at offset %ld...\n",
944 what, (long)(s + start_shift - i_strpos)) );
947 /* Have both, check_string is floating */
948 if (t + start_shift >= check_at) /* Contradicts floating=check */
949 goto retry_floating_check;
950 /* Recheck anchored substring, but not floating... */
954 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
955 "Looking for anchored substr starting at offset %ld...\n",
956 (long)(other_last - i_strpos)) );
957 goto do_other_anchored;
959 /* Another way we could have checked stclass at the
960 current position only: */
965 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
966 "Looking for /%s^%s/m starting at offset %ld...\n",
967 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
970 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
972 /* Check is floating subtring. */
973 retry_floating_check:
974 t = check_at - start_shift;
975 DEBUG_EXECUTE_r( what = "floating" );
976 goto hop_and_restart;
979 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
980 "By STCLASS: moving %ld --> %ld\n",
981 (long)(t - i_strpos), (long)(s - i_strpos))
985 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
986 "Does not contradict STCLASS...\n");
991 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
992 PL_colors[4], (check ? "Guessed" : "Giving up"),
993 PL_colors[5], (long)(s - i_strpos)) );
996 fail_finish: /* Substring not found */
997 if (prog->check_substr || prog->check_utf8) /* could be removed already */
998 BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1000 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1001 PL_colors[4], PL_colors[5]));
1005 #define DECL_TRIE_TYPE(scan) \
1006 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1007 trie_type = (scan->flags != EXACT) \
1008 ? (do_utf8 ? trie_utf8_fold : (UTF ? trie_latin_utf8_fold : trie_plain)) \
1009 : (do_utf8 ? trie_utf8 : trie_plain)
1011 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1012 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1013 UV uvc_unfolded = 0; \
1014 switch (trie_type) { \
1015 case trie_utf8_fold: \
1016 if ( foldlen>0 ) { \
1017 uvc_unfolded = uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1022 uvc_unfolded = uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1023 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1024 foldlen -= UNISKIP( uvc ); \
1025 uscan = foldbuf + UNISKIP( uvc ); \
1028 case trie_latin_utf8_fold: \
1029 if ( foldlen>0 ) { \
1030 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1036 uvc = to_uni_fold( *(U8*)uc, foldbuf, &foldlen ); \
1037 foldlen -= UNISKIP( uvc ); \
1038 uscan = foldbuf + UNISKIP( uvc ); \
1042 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1050 charid = trie->charmap[ uvc ]; \
1054 if (widecharmap) { \
1055 SV** const svpp = hv_fetch(widecharmap, \
1056 (char*)&uvc, sizeof(UV), 0); \
1058 charid = (U16)SvIV(*svpp); \
1061 if (!charid && trie_type == trie_utf8_fold && !UTF) { \
1062 charid = trie->charmap[uvc_unfolded]; \
1066 #define REXEC_FBC_EXACTISH_CHECK(CoNd) \
1068 char *my_strend= (char *)strend; \
1071 !ibcmp_utf8(s, &my_strend, 0, do_utf8, \
1072 m, NULL, ln, (bool)UTF)) \
1073 && (!reginfo || regtry(reginfo, &s)) ) \
1076 U8 foldbuf[UTF8_MAXBYTES_CASE+1]; \
1077 uvchr_to_utf8(tmpbuf, c); \
1078 f = to_utf8_fold(tmpbuf, foldbuf, &foldlen); \
1080 && (f == c1 || f == c2) \
1082 !ibcmp_utf8(s, &my_strend, 0, do_utf8,\
1083 m, NULL, ln, (bool)UTF)) \
1084 && (!reginfo || regtry(reginfo, &s)) ) \
1090 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1094 && (ln == 1 || !(OP(c) == EXACTF \
1096 : ibcmp_locale(s, m, ln))) \
1097 && (!reginfo || regtry(reginfo, &s)) ) \
1103 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1105 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1111 #define REXEC_FBC_SCAN(CoDe) \
1113 while (s < strend) { \
1119 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1120 REXEC_FBC_UTF8_SCAN( \
1122 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1131 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1134 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1143 #define REXEC_FBC_TRYIT \
1144 if ((!reginfo || regtry(reginfo, &s))) \
1147 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1149 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1152 REXEC_FBC_CLASS_SCAN(CoNd); \
1156 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1159 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1162 REXEC_FBC_CLASS_SCAN(CoNd); \
1166 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1167 PL_reg_flags |= RF_tainted; \
1169 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1172 REXEC_FBC_CLASS_SCAN(CoNd); \
1176 #define DUMP_EXEC_POS(li,s,doutf8) \
1177 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1179 /* We know what class REx starts with. Try to find this position... */
1180 /* if reginfo is NULL, its a dryrun */
1181 /* annoyingly all the vars in this routine have different names from their counterparts
1182 in regmatch. /grrr */
1185 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1186 const char *strend, regmatch_info *reginfo)
1189 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1193 register STRLEN uskip;
1197 register I32 tmp = 1; /* Scratch variable? */
1198 register const bool do_utf8 = PL_reg_match_utf8;
1199 RXi_GET_DECL(prog,progi);
1201 PERL_ARGS_ASSERT_FIND_BYCLASS;
1203 /* We know what class it must start with. */
1207 REXEC_FBC_UTF8_CLASS_SCAN((ANYOF_FLAGS(c) & ANYOF_UNICODE) ||
1208 !UTF8_IS_INVARIANT((U8)s[0]) ?
1209 reginclass(prog, c, (U8*)s, 0, do_utf8) :
1210 REGINCLASS(prog, c, (U8*)s));
1213 while (s < strend) {
1216 if (REGINCLASS(prog, c, (U8*)s) ||
1217 (ANYOF_FOLD_SHARP_S(c, s, strend) &&
1218 /* The assignment of 2 is intentional:
1219 * for the folded sharp s, the skip is 2. */
1220 (skip = SHARP_S_SKIP))) {
1221 if (tmp && (!reginfo || regtry(reginfo, &s)))
1234 if (tmp && (!reginfo || regtry(reginfo, &s)))
1242 ln = STR_LEN(c); /* length to match in octets/bytes */
1243 lnc = (I32) ln; /* length to match in characters */
1245 STRLEN ulen1, ulen2;
1247 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
1248 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
1249 /* used by commented-out code below */
1250 /*const U32 uniflags = UTF8_ALLOW_DEFAULT;*/
1252 /* XXX: Since the node will be case folded at compile
1253 time this logic is a little odd, although im not
1254 sure that its actually wrong. --dmq */
1256 c1 = to_utf8_lower((U8*)m, tmpbuf1, &ulen1);
1257 c2 = to_utf8_upper((U8*)m, tmpbuf2, &ulen2);
1259 /* XXX: This is kinda strange. to_utf8_XYZ returns the
1260 codepoint of the first character in the converted
1261 form, yet originally we did the extra step.
1262 No tests fail by commenting this code out however
1263 so Ive left it out. -- dmq.
1265 c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXBYTES_CASE,
1267 c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXBYTES_CASE,
1272 while (sm < ((U8 *) m + ln)) {
1287 c2 = PL_fold_locale[c1];
1289 e = HOP3c(strend, -((I32)lnc), s);
1291 if (!reginfo && e < s)
1292 e = s; /* Due to minlen logic of intuit() */
1294 /* The idea in the EXACTF* cases is to first find the
1295 * first character of the EXACTF* node and then, if
1296 * necessary, case-insensitively compare the full
1297 * text of the node. The c1 and c2 are the first
1298 * characters (though in Unicode it gets a bit
1299 * more complicated because there are more cases
1300 * than just upper and lower: one needs to use
1301 * the so-called folding case for case-insensitive
1302 * matching (called "loose matching" in Unicode).
1303 * ibcmp_utf8() will do just that. */
1305 if (do_utf8 || UTF) {
1307 U8 tmpbuf [UTF8_MAXBYTES+1];
1310 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1312 /* Upper and lower of 1st char are equal -
1313 * probably not a "letter". */
1316 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1321 REXEC_FBC_EXACTISH_CHECK(c == c1);
1327 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1333 /* Handle some of the three Greek sigmas cases.
1334 * Note that not all the possible combinations
1335 * are handled here: some of them are handled
1336 * by the standard folding rules, and some of
1337 * them (the character class or ANYOF cases)
1338 * are handled during compiletime in
1339 * regexec.c:S_regclass(). */
1340 if (c == (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA ||
1341 c == (UV)UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA)
1342 c = (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA;
1344 REXEC_FBC_EXACTISH_CHECK(c == c1 || c == c2);
1349 /* Neither pattern nor string are UTF8 */
1351 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1353 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1357 PL_reg_flags |= RF_tainted;
1364 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1365 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1367 tmp = ((OP(c) == BOUND ?
1368 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1369 LOAD_UTF8_CHARCLASS_ALNUM();
1370 REXEC_FBC_UTF8_SCAN(
1371 if (tmp == !(OP(c) == BOUND ?
1372 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1373 isALNUM_LC_utf8((U8*)s)))
1381 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1382 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1385 !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
1391 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s)))
1395 PL_reg_flags |= RF_tainted;
1402 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1403 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1405 tmp = ((OP(c) == NBOUND ?
1406 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1407 LOAD_UTF8_CHARCLASS_ALNUM();
1408 REXEC_FBC_UTF8_SCAN(
1409 if (tmp == !(OP(c) == NBOUND ?
1410 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1411 isALNUM_LC_utf8((U8*)s)))
1413 else REXEC_FBC_TRYIT;
1417 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1418 tmp = ((OP(c) == NBOUND ?
1419 isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1422 !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
1424 else REXEC_FBC_TRYIT;
1427 if ((!prog->minlen && !tmp) && (!reginfo || regtry(reginfo, &s)))
1431 REXEC_FBC_CSCAN_PRELOAD(
1432 LOAD_UTF8_CHARCLASS_ALNUM(),
1433 swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8),
1437 REXEC_FBC_CSCAN_TAINT(
1438 isALNUM_LC_utf8((U8*)s),
1442 REXEC_FBC_CSCAN_PRELOAD(
1443 LOAD_UTF8_CHARCLASS_ALNUM(),
1444 !swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8),
1448 REXEC_FBC_CSCAN_TAINT(
1449 !isALNUM_LC_utf8((U8*)s),
1453 REXEC_FBC_CSCAN_PRELOAD(
1454 LOAD_UTF8_CHARCLASS_SPACE(),
1455 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8),
1459 REXEC_FBC_CSCAN_TAINT(
1460 *s == ' ' || isSPACE_LC_utf8((U8*)s),
1464 REXEC_FBC_CSCAN_PRELOAD(
1465 LOAD_UTF8_CHARCLASS_SPACE(),
1466 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8)),
1470 REXEC_FBC_CSCAN_TAINT(
1471 !(*s == ' ' || isSPACE_LC_utf8((U8*)s)),
1475 REXEC_FBC_CSCAN_PRELOAD(
1476 LOAD_UTF8_CHARCLASS_DIGIT(),
1477 swash_fetch(PL_utf8_digit,(U8*)s, do_utf8),
1481 REXEC_FBC_CSCAN_TAINT(
1482 isDIGIT_LC_utf8((U8*)s),
1486 REXEC_FBC_CSCAN_PRELOAD(
1487 LOAD_UTF8_CHARCLASS_DIGIT(),
1488 !swash_fetch(PL_utf8_digit,(U8*)s, do_utf8),
1492 REXEC_FBC_CSCAN_TAINT(
1493 !isDIGIT_LC_utf8((U8*)s),
1499 is_LNBREAK_latin1(s)
1509 !is_VERTWS_latin1(s)
1514 is_HORIZWS_latin1(s)
1518 !is_HORIZWS_utf8(s),
1519 !is_HORIZWS_latin1(s)
1525 /* what trie are we using right now */
1527 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1529 = (reg_trie_data*)progi->data->data[ aho->trie ];
1530 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1532 const char *last_start = strend - trie->minlen;
1534 const char *real_start = s;
1536 STRLEN maxlen = trie->maxlen;
1538 U8 **points; /* map of where we were in the input string
1539 when reading a given char. For ASCII this
1540 is unnecessary overhead as the relationship
1541 is always 1:1, but for Unicode, especially
1542 case folded Unicode this is not true. */
1543 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1547 GET_RE_DEBUG_FLAGS_DECL;
1549 /* We can't just allocate points here. We need to wrap it in
1550 * an SV so it gets freed properly if there is a croak while
1551 * running the match */
1554 sv_points=newSV(maxlen * sizeof(U8 *));
1555 SvCUR_set(sv_points,
1556 maxlen * sizeof(U8 *));
1557 SvPOK_on(sv_points);
1558 sv_2mortal(sv_points);
1559 points=(U8**)SvPV_nolen(sv_points );
1560 if ( trie_type != trie_utf8_fold
1561 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1564 bitmap=(U8*)trie->bitmap;
1566 bitmap=(U8*)ANYOF_BITMAP(c);
1568 /* this is the Aho-Corasick algorithm modified a touch
1569 to include special handling for long "unknown char"
1570 sequences. The basic idea being that we use AC as long
1571 as we are dealing with a possible matching char, when
1572 we encounter an unknown char (and we have not encountered
1573 an accepting state) we scan forward until we find a legal
1575 AC matching is basically that of trie matching, except
1576 that when we encounter a failing transition, we fall back
1577 to the current states "fail state", and try the current char
1578 again, a process we repeat until we reach the root state,
1579 state 1, or a legal transition. If we fail on the root state
1580 then we can either terminate if we have reached an accepting
1581 state previously, or restart the entire process from the beginning
1585 while (s <= last_start) {
1586 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1594 U8 *uscan = (U8*)NULL;
1595 U8 *leftmost = NULL;
1597 U32 accepted_word= 0;
1601 while ( state && uc <= (U8*)strend ) {
1603 U32 word = aho->states[ state ].wordnum;
1607 DEBUG_TRIE_EXECUTE_r(
1608 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1609 dump_exec_pos( (char *)uc, c, strend, real_start,
1610 (char *)uc, do_utf8 );
1611 PerlIO_printf( Perl_debug_log,
1612 " Scanning for legal start char...\n");
1615 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1620 if (uc >(U8*)last_start) break;
1624 U8 *lpos= points[ (pointpos - trie->wordlen[word-1] ) % maxlen ];
1625 if (!leftmost || lpos < leftmost) {
1626 DEBUG_r(accepted_word=word);
1632 points[pointpos++ % maxlen]= uc;
1633 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1634 uscan, len, uvc, charid, foldlen,
1636 DEBUG_TRIE_EXECUTE_r({
1637 dump_exec_pos( (char *)uc, c, strend, real_start,
1639 PerlIO_printf(Perl_debug_log,
1640 " Charid:%3u CP:%4"UVxf" ",
1646 word = aho->states[ state ].wordnum;
1648 base = aho->states[ state ].trans.base;
1650 DEBUG_TRIE_EXECUTE_r({
1652 dump_exec_pos( (char *)uc, c, strend, real_start,
1654 PerlIO_printf( Perl_debug_log,
1655 "%sState: %4"UVxf", word=%"UVxf,
1656 failed ? " Fail transition to " : "",
1657 (UV)state, (UV)word);
1662 (base + charid > trie->uniquecharcount )
1663 && (base + charid - 1 - trie->uniquecharcount
1665 && trie->trans[base + charid - 1 -
1666 trie->uniquecharcount].check == state
1667 && (tmp=trie->trans[base + charid - 1 -
1668 trie->uniquecharcount ].next))
1670 DEBUG_TRIE_EXECUTE_r(
1671 PerlIO_printf( Perl_debug_log," - legal\n"));
1676 DEBUG_TRIE_EXECUTE_r(
1677 PerlIO_printf( Perl_debug_log," - fail\n"));
1679 state = aho->fail[state];
1683 /* we must be accepting here */
1684 DEBUG_TRIE_EXECUTE_r(
1685 PerlIO_printf( Perl_debug_log," - accepting\n"));
1694 if (!state) state = 1;
1697 if ( aho->states[ state ].wordnum ) {
1698 U8 *lpos = points[ (pointpos - trie->wordlen[aho->states[ state ].wordnum-1]) % maxlen ];
1699 if (!leftmost || lpos < leftmost) {
1700 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
1705 s = (char*)leftmost;
1706 DEBUG_TRIE_EXECUTE_r({
1708 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
1709 (UV)accepted_word, (IV)(s - real_start)
1712 if (!reginfo || regtry(reginfo, &s)) {
1718 DEBUG_TRIE_EXECUTE_r({
1719 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
1722 DEBUG_TRIE_EXECUTE_r(
1723 PerlIO_printf( Perl_debug_log,"No match.\n"));
1732 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1741 S_swap_match_buff (pTHX_ regexp *prog)
1743 regexp_paren_pair *t;
1745 PERL_ARGS_ASSERT_SWAP_MATCH_BUFF;
1748 /* We have to be careful. If the previous successful match
1749 was from this regex we don't want a subsequent paritally
1750 successful match to clobber the old results.
1751 So when we detect this possibility we add a swap buffer
1752 to the re, and switch the buffer each match. If we fail
1753 we switch it back, otherwise we leave it swapped.
1755 Newxz(prog->swap, (prog->nparens + 1), regexp_paren_pair);
1758 prog->swap = prog->offs;
1764 - regexec_flags - match a regexp against a string
1767 Perl_regexec_flags(pTHX_ REGEXP * const prog, char *stringarg, register char *strend,
1768 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1769 /* strend: pointer to null at end of string */
1770 /* strbeg: real beginning of string */
1771 /* minend: end of match must be >=minend after stringarg. */
1772 /* data: May be used for some additional optimizations.
1773 Currently its only used, with a U32 cast, for transmitting
1774 the ganch offset when doing a /g match. This will change */
1775 /* nosave: For optimizations. */
1778 /*register*/ char *s;
1779 register regnode *c;
1780 /*register*/ char *startpos = stringarg;
1781 I32 minlen; /* must match at least this many chars */
1782 I32 dontbother = 0; /* how many characters not to try at end */
1783 I32 end_shift = 0; /* Same for the end. */ /* CC */
1784 I32 scream_pos = -1; /* Internal iterator of scream. */
1785 char *scream_olds = NULL;
1786 const bool do_utf8 = (bool)DO_UTF8(sv);
1788 RXi_GET_DECL(prog,progi);
1789 regmatch_info reginfo; /* create some info to pass to regtry etc */
1790 bool swap_on_fail = 0;
1791 GET_RE_DEBUG_FLAGS_DECL;
1793 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
1794 PERL_UNUSED_ARG(data);
1796 /* Be paranoid... */
1797 if (prog == NULL || startpos == NULL) {
1798 Perl_croak(aTHX_ "NULL regexp parameter");
1802 multiline = prog->extflags & RXf_PMf_MULTILINE;
1803 reginfo.prog = prog;
1805 RX_MATCH_UTF8_set(prog, do_utf8);
1807 debug_start_match(prog, do_utf8, startpos, strend,
1811 minlen = prog->minlen;
1813 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
1814 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1815 "String too short [regexec_flags]...\n"));
1820 /* Check validity of program. */
1821 if (UCHARAT(progi->program) != REG_MAGIC) {
1822 Perl_croak(aTHX_ "corrupted regexp program");
1826 PL_reg_eval_set = 0;
1830 PL_reg_flags |= RF_utf8;
1832 /* Mark beginning of line for ^ and lookbehind. */
1833 reginfo.bol = startpos; /* XXX not used ??? */
1837 /* Mark end of line for $ (and such) */
1840 /* see how far we have to get to not match where we matched before */
1841 reginfo.till = startpos+minend;
1843 /* If there is a "must appear" string, look for it. */
1846 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
1849 if (flags & REXEC_IGNOREPOS) /* Means: check only at start */
1850 reginfo.ganch = startpos + prog->gofs;
1851 else if (sv && SvTYPE(sv) >= SVt_PVMG
1853 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
1854 && mg->mg_len >= 0) {
1855 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
1856 if (prog->extflags & RXf_ANCH_GPOS) {
1857 if (s > reginfo.ganch)
1859 s = reginfo.ganch - prog->gofs;
1863 reginfo.ganch = strbeg + PTR2UV(data);
1864 } else /* pos() not defined */
1865 reginfo.ganch = strbeg;
1867 if (PL_curpm && (PM_GETRE(PL_curpm) == prog)) {
1869 swap_match_buff(prog); /* do we need a save destructor here for
1872 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
1873 re_scream_pos_data d;
1875 d.scream_olds = &scream_olds;
1876 d.scream_pos = &scream_pos;
1877 s = re_intuit_start(prog, sv, s, strend, flags, &d);
1879 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
1880 goto phooey; /* not present */
1886 /* Simplest case: anchored match need be tried only once. */
1887 /* [unless only anchor is BOL and multiline is set] */
1888 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
1889 if (s == startpos && regtry(®info, &startpos))
1891 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
1892 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
1897 dontbother = minlen - 1;
1898 end = HOP3c(strend, -dontbother, strbeg) - 1;
1899 /* for multiline we only have to try after newlines */
1900 if (prog->check_substr || prog->check_utf8) {
1904 if (regtry(®info, &s))
1909 if (prog->extflags & RXf_USE_INTUIT) {
1910 s = re_intuit_start(prog, sv, s + 1, strend, flags, NULL);
1921 if (*s++ == '\n') { /* don't need PL_utf8skip here */
1922 if (regtry(®info, &s))
1929 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
1931 /* the warning about reginfo.ganch being used without intialization
1932 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
1933 and we only enter this block when the same bit is set. */
1934 char *tmp_s = reginfo.ganch - prog->gofs;
1935 if (regtry(®info, &tmp_s))
1940 /* Messy cases: unanchored match. */
1941 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
1942 /* we have /x+whatever/ */
1943 /* it must be a one character string (XXXX Except UTF?) */
1948 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1949 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1950 ch = SvPVX_const(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)[0];
1955 DEBUG_EXECUTE_r( did_match = 1 );
1956 if (regtry(®info, &s)) goto got_it;
1958 while (s < strend && *s == ch)
1966 DEBUG_EXECUTE_r( did_match = 1 );
1967 if (regtry(®info, &s)) goto got_it;
1969 while (s < strend && *s == ch)
1974 DEBUG_EXECUTE_r(if (!did_match)
1975 PerlIO_printf(Perl_debug_log,
1976 "Did not find anchored character...\n")
1979 else if (prog->anchored_substr != NULL
1980 || prog->anchored_utf8 != NULL
1981 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
1982 && prog->float_max_offset < strend - s)) {
1987 char *last1; /* Last position checked before */
1991 if (prog->anchored_substr || prog->anchored_utf8) {
1992 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1993 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1994 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
1995 back_max = back_min = prog->anchored_offset;
1997 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
1998 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1999 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
2000 back_max = prog->float_max_offset;
2001 back_min = prog->float_min_offset;
2005 if (must == &PL_sv_undef)
2006 /* could not downgrade utf8 check substring, so must fail */
2012 last = HOP3c(strend, /* Cannot start after this */
2013 -(I32)(CHR_SVLEN(must)
2014 - (SvTAIL(must) != 0) + back_min), strbeg);
2017 last1 = HOPc(s, -1);
2019 last1 = s - 1; /* bogus */
2021 /* XXXX check_substr already used to find "s", can optimize if
2022 check_substr==must. */
2024 dontbother = end_shift;
2025 strend = HOPc(strend, -dontbother);
2026 while ( (s <= last) &&
2027 ((flags & REXEC_SCREAM)
2028 ? (s = screaminstr(sv, must, HOP3c(s, back_min, (back_min<0 ? strbeg : strend)) - strbeg,
2029 end_shift, &scream_pos, 0))
2030 : (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2031 (unsigned char*)strend, must,
2032 multiline ? FBMrf_MULTILINE : 0))) ) {
2033 /* we may be pointing at the wrong string */
2034 if ((flags & REXEC_SCREAM) && RXp_MATCH_COPIED(prog))
2035 s = strbeg + (s - SvPVX_const(sv));
2036 DEBUG_EXECUTE_r( did_match = 1 );
2037 if (HOPc(s, -back_max) > last1) {
2038 last1 = HOPc(s, -back_min);
2039 s = HOPc(s, -back_max);
2042 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2044 last1 = HOPc(s, -back_min);
2048 while (s <= last1) {
2049 if (regtry(®info, &s))
2055 while (s <= last1) {
2056 if (regtry(®info, &s))
2062 DEBUG_EXECUTE_r(if (!did_match) {
2063 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
2064 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2065 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2066 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2067 ? "anchored" : "floating"),
2068 quoted, RE_SV_TAIL(must));
2072 else if ( (c = progi->regstclass) ) {
2074 const OPCODE op = OP(progi->regstclass);
2075 /* don't bother with what can't match */
2076 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2077 strend = HOPc(strend, -(minlen - 1));
2080 SV * const prop = sv_newmortal();
2081 regprop(prog, prop, c);
2083 RE_PV_QUOTED_DECL(quoted,do_utf8,PERL_DEBUG_PAD_ZERO(1),
2085 PerlIO_printf(Perl_debug_log,
2086 "Matching stclass %.*s against %s (%d chars)\n",
2087 (int)SvCUR(prop), SvPVX_const(prop),
2088 quoted, (int)(strend - s));
2091 if (find_byclass(prog, c, s, strend, ®info))
2093 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2097 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2102 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
2103 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2104 float_real = do_utf8 ? prog->float_utf8 : prog->float_substr;
2106 if (flags & REXEC_SCREAM) {
2107 last = screaminstr(sv, float_real, s - strbeg,
2108 end_shift, &scream_pos, 1); /* last one */
2110 last = scream_olds; /* Only one occurrence. */
2111 /* we may be pointing at the wrong string */
2112 else if (RXp_MATCH_COPIED(prog))
2113 s = strbeg + (s - SvPVX_const(sv));
2117 const char * const little = SvPV_const(float_real, len);
2119 if (SvTAIL(float_real)) {
2120 if (memEQ(strend - len + 1, little, len - 1))
2121 last = strend - len + 1;
2122 else if (!multiline)
2123 last = memEQ(strend - len, little, len)
2124 ? strend - len : NULL;
2130 last = rninstr(s, strend, little, little + len);
2132 last = strend; /* matching "$" */
2137 PerlIO_printf(Perl_debug_log,
2138 "%sCan't trim the tail, match fails (should not happen)%s\n",
2139 PL_colors[4], PL_colors[5]));
2140 goto phooey; /* Should not happen! */
2142 dontbother = strend - last + prog->float_min_offset;
2144 if (minlen && (dontbother < minlen))
2145 dontbother = minlen - 1;
2146 strend -= dontbother; /* this one's always in bytes! */
2147 /* We don't know much -- general case. */
2150 if (regtry(®info, &s))
2159 if (regtry(®info, &s))
2161 } while (s++ < strend);
2169 RX_MATCH_TAINTED_set(prog, 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(prog);
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(prog);
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 swap_match_buff(prog);
2223 - regtry - try match at specific point
2225 STATIC I32 /* 0 failure, 1 success */
2226 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2230 regexp *prog = reginfo->prog;
2231 RXi_GET_DECL(prog,progi);
2232 GET_RE_DEBUG_FLAGS_DECL;
2234 PERL_ARGS_ASSERT_REGTRY;
2236 reginfo->cutpoint=NULL;
2238 if ((prog->extflags & RXf_EVAL_SEEN) && !PL_reg_eval_set) {
2241 PL_reg_eval_set = RS_init;
2242 DEBUG_EXECUTE_r(DEBUG_s(
2243 PerlIO_printf(Perl_debug_log, " setting stack tmpbase at %"IVdf"\n",
2244 (IV)(PL_stack_sp - PL_stack_base));
2247 cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2248 /* Otherwise OP_NEXTSTATE will free whatever on stack now. */
2250 /* Apparently this is not needed, judging by wantarray. */
2251 /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2252 cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2255 /* Make $_ available to executed code. */
2256 if (reginfo->sv != DEFSV) {
2258 DEFSV_set(reginfo->sv);
2261 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2262 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2263 /* prepare for quick setting of pos */
2264 #ifdef PERL_OLD_COPY_ON_WRITE
2265 if (SvIsCOW(reginfo->sv))
2266 sv_force_normal_flags(reginfo->sv, 0);
2268 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2269 &PL_vtbl_mglob, NULL, 0);
2273 PL_reg_oldpos = mg->mg_len;
2274 SAVEDESTRUCTOR_X(restore_pos, prog);
2276 if (!PL_reg_curpm) {
2277 Newxz(PL_reg_curpm, 1, PMOP);
2280 SV* const repointer = newSViv(0);
2281 /* this regexp is also owned by the new PL_reg_curpm, which
2282 will try to free it. */
2283 av_push(PL_regex_padav,repointer);
2284 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2285 PL_regex_pad = AvARRAY(PL_regex_padav);
2290 /* It seems that non-ithreads works both with and without this code.
2291 So for efficiency reasons it seems best not to have the code
2292 compiled when it is not needed. */
2293 /* This is safe against NULLs: */
2294 ReREFCNT_dec(PM_GETRE(PL_reg_curpm));
2295 /* PM_reg_curpm owns a reference to this regexp. */
2298 PM_SETRE(PL_reg_curpm, prog);
2299 PL_reg_oldcurpm = PL_curpm;
2300 PL_curpm = PL_reg_curpm;
2301 if (RXp_MATCH_COPIED(prog)) {
2302 /* Here is a serious problem: we cannot rewrite subbeg,
2303 since it may be needed if this match fails. Thus
2304 $` inside (?{}) could fail... */
2305 PL_reg_oldsaved = prog->subbeg;
2306 PL_reg_oldsavedlen = prog->sublen;
2307 #ifdef PERL_OLD_COPY_ON_WRITE
2308 PL_nrs = prog->saved_copy;
2310 RXp_MATCH_COPIED_off(prog);
2313 PL_reg_oldsaved = NULL;
2314 prog->subbeg = PL_bostr;
2315 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2317 DEBUG_EXECUTE_r(PL_reg_starttry = *startpos);
2318 prog->offs[0].start = *startpos - PL_bostr;
2319 PL_reginput = *startpos;
2320 PL_reglastparen = &prog->lastparen;
2321 PL_reglastcloseparen = &prog->lastcloseparen;
2322 prog->lastparen = 0;
2323 prog->lastcloseparen = 0;
2325 PL_regoffs = prog->offs;
2326 if (PL_reg_start_tmpl <= prog->nparens) {
2327 PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2328 if(PL_reg_start_tmp)
2329 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2331 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2334 /* XXXX What this code is doing here?!!! There should be no need
2335 to do this again and again, PL_reglastparen should take care of
2338 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2339 * Actually, the code in regcppop() (which Ilya may be meaning by
2340 * PL_reglastparen), is not needed at all by the test suite
2341 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2342 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2343 * Meanwhile, this code *is* needed for the
2344 * above-mentioned test suite tests to succeed. The common theme
2345 * on those tests seems to be returning null fields from matches.
2346 * --jhi updated by dapm */
2348 if (prog->nparens) {
2349 regexp_paren_pair *pp = PL_regoffs;
2351 for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2359 if (regmatch(reginfo, progi->program + 1)) {
2360 PL_regoffs[0].end = PL_reginput - PL_bostr;
2363 if (reginfo->cutpoint)
2364 *startpos= reginfo->cutpoint;
2365 REGCP_UNWIND(lastcp);
2370 #define sayYES goto yes
2371 #define sayNO goto no
2372 #define sayNO_SILENT goto no_silent
2374 /* we dont use STMT_START/END here because it leads to
2375 "unreachable code" warnings, which are bogus, but distracting. */
2376 #define CACHEsayNO \
2377 if (ST.cache_mask) \
2378 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2381 /* this is used to determine how far from the left messages like
2382 'failed...' are printed. It should be set such that messages
2383 are inline with the regop output that created them.
2385 #define REPORT_CODE_OFF 32
2388 /* Make sure there is a test for this +1 options in re_tests */
2389 #define TRIE_INITAL_ACCEPT_BUFFLEN 4;
2391 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2392 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2394 #define SLAB_FIRST(s) (&(s)->states[0])
2395 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2397 /* grab a new slab and return the first slot in it */
2399 STATIC regmatch_state *
2402 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2405 regmatch_slab *s = PL_regmatch_slab->next;
2407 Newx(s, 1, regmatch_slab);
2408 s->prev = PL_regmatch_slab;
2410 PL_regmatch_slab->next = s;
2412 PL_regmatch_slab = s;
2413 return SLAB_FIRST(s);
2417 /* push a new state then goto it */
2419 #define PUSH_STATE_GOTO(state, node) \
2421 st->resume_state = state; \
2424 /* push a new state with success backtracking, then goto it */
2426 #define PUSH_YES_STATE_GOTO(state, node) \
2428 st->resume_state = state; \
2429 goto push_yes_state;
2435 regmatch() - main matching routine
2437 This is basically one big switch statement in a loop. We execute an op,
2438 set 'next' to point the next op, and continue. If we come to a point which
2439 we may need to backtrack to on failure such as (A|B|C), we push a
2440 backtrack state onto the backtrack stack. On failure, we pop the top
2441 state, and re-enter the loop at the state indicated. If there are no more
2442 states to pop, we return failure.
2444 Sometimes we also need to backtrack on success; for example /A+/, where
2445 after successfully matching one A, we need to go back and try to
2446 match another one; similarly for lookahead assertions: if the assertion
2447 completes successfully, we backtrack to the state just before the assertion
2448 and then carry on. In these cases, the pushed state is marked as
2449 'backtrack on success too'. This marking is in fact done by a chain of
2450 pointers, each pointing to the previous 'yes' state. On success, we pop to
2451 the nearest yes state, discarding any intermediate failure-only states.
2452 Sometimes a yes state is pushed just to force some cleanup code to be
2453 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2454 it to free the inner regex.
2456 Note that failure backtracking rewinds the cursor position, while
2457 success backtracking leaves it alone.
2459 A pattern is complete when the END op is executed, while a subpattern
2460 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2461 ops trigger the "pop to last yes state if any, otherwise return true"
2464 A common convention in this function is to use A and B to refer to the two
2465 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2466 the subpattern to be matched possibly multiple times, while B is the entire
2467 rest of the pattern. Variable and state names reflect this convention.
2469 The states in the main switch are the union of ops and failure/success of
2470 substates associated with with that op. For example, IFMATCH is the op
2471 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2472 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2473 successfully matched A and IFMATCH_A_fail is a state saying that we have
2474 just failed to match A. Resume states always come in pairs. The backtrack
2475 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2476 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2477 on success or failure.
2479 The struct that holds a backtracking state is actually a big union, with
2480 one variant for each major type of op. The variable st points to the
2481 top-most backtrack struct. To make the code clearer, within each
2482 block of code we #define ST to alias the relevant union.
2484 Here's a concrete example of a (vastly oversimplified) IFMATCH
2490 #define ST st->u.ifmatch
2492 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2493 ST.foo = ...; // some state we wish to save
2495 // push a yes backtrack state with a resume value of
2496 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2498 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2501 case IFMATCH_A: // we have successfully executed A; now continue with B
2503 bar = ST.foo; // do something with the preserved value
2506 case IFMATCH_A_fail: // A failed, so the assertion failed
2507 ...; // do some housekeeping, then ...
2508 sayNO; // propagate the failure
2515 For any old-timers reading this who are familiar with the old recursive
2516 approach, the code above is equivalent to:
2518 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2527 ...; // do some housekeeping, then ...
2528 sayNO; // propagate the failure
2531 The topmost backtrack state, pointed to by st, is usually free. If you
2532 want to claim it, populate any ST.foo fields in it with values you wish to
2533 save, then do one of
2535 PUSH_STATE_GOTO(resume_state, node);
2536 PUSH_YES_STATE_GOTO(resume_state, node);
2538 which sets that backtrack state's resume value to 'resume_state', pushes a
2539 new free entry to the top of the backtrack stack, then goes to 'node'.
2540 On backtracking, the free slot is popped, and the saved state becomes the
2541 new free state. An ST.foo field in this new top state can be temporarily
2542 accessed to retrieve values, but once the main loop is re-entered, it
2543 becomes available for reuse.
2545 Note that the depth of the backtrack stack constantly increases during the
2546 left-to-right execution of the pattern, rather than going up and down with
2547 the pattern nesting. For example the stack is at its maximum at Z at the
2548 end of the pattern, rather than at X in the following:
2550 /(((X)+)+)+....(Y)+....Z/
2552 The only exceptions to this are lookahead/behind assertions and the cut,
2553 (?>A), which pop all the backtrack states associated with A before
2556 Bascktrack state structs are allocated in slabs of about 4K in size.
2557 PL_regmatch_state and st always point to the currently active state,
2558 and PL_regmatch_slab points to the slab currently containing
2559 PL_regmatch_state. The first time regmatch() is called, the first slab is
2560 allocated, and is never freed until interpreter destruction. When the slab
2561 is full, a new one is allocated and chained to the end. At exit from
2562 regmatch(), slabs allocated since entry are freed.
2567 #define DEBUG_STATE_pp(pp) \
2569 DUMP_EXEC_POS(locinput, scan, do_utf8); \
2570 PerlIO_printf(Perl_debug_log, \
2571 " %*s"pp" %s%s%s%s%s\n", \
2573 PL_reg_name[st->resume_state], \
2574 ((st==yes_state||st==mark_state) ? "[" : ""), \
2575 ((st==yes_state) ? "Y" : ""), \
2576 ((st==mark_state) ? "M" : ""), \
2577 ((st==yes_state||st==mark_state) ? "]" : "") \
2582 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2587 S_debug_start_match(pTHX_ const REGEXP *prog, const bool do_utf8,
2588 const char *start, const char *end, const char *blurb)
2590 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2592 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2597 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2598 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2600 RE_PV_QUOTED_DECL(s1, do_utf8, PERL_DEBUG_PAD_ZERO(1),
2601 start, end - start, 60);
2603 PerlIO_printf(Perl_debug_log,
2604 "%s%s REx%s %s against %s\n",
2605 PL_colors[4], blurb, PL_colors[5], s0, s1);
2607 if (do_utf8||utf8_pat)
2608 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2609 utf8_pat ? "pattern" : "",
2610 utf8_pat && do_utf8 ? " and " : "",
2611 do_utf8 ? "string" : ""
2617 S_dump_exec_pos(pTHX_ const char *locinput,
2618 const regnode *scan,
2619 const char *loc_regeol,
2620 const char *loc_bostr,
2621 const char *loc_reg_starttry,
2624 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
2625 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2626 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
2627 /* The part of the string before starttry has one color
2628 (pref0_len chars), between starttry and current
2629 position another one (pref_len - pref0_len chars),
2630 after the current position the third one.
2631 We assume that pref0_len <= pref_len, otherwise we
2632 decrease pref0_len. */
2633 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
2634 ? (5 + taill) - l : locinput - loc_bostr;
2637 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
2639 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2641 pref0_len = pref_len - (locinput - loc_reg_starttry);
2642 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
2643 l = ( loc_regeol - locinput > (5 + taill) - pref_len
2644 ? (5 + taill) - pref_len : loc_regeol - locinput);
2645 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2649 if (pref0_len > pref_len)
2650 pref0_len = pref_len;
2652 const int is_uni = (do_utf8 && OP(scan) != CANY) ? 1 : 0;
2654 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
2655 (locinput - pref_len),pref0_len, 60, 4, 5);
2657 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
2658 (locinput - pref_len + pref0_len),
2659 pref_len - pref0_len, 60, 2, 3);
2661 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
2662 locinput, loc_regeol - locinput, 10, 0, 1);
2664 const STRLEN tlen=len0+len1+len2;
2665 PerlIO_printf(Perl_debug_log,
2666 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
2667 (IV)(locinput - loc_bostr),
2670 (docolor ? "" : "> <"),
2672 (int)(tlen > 19 ? 0 : 19 - tlen),
2679 /* reg_check_named_buff_matched()
2680 * Checks to see if a named buffer has matched. The data array of
2681 * buffer numbers corresponding to the buffer is expected to reside
2682 * in the regexp->data->data array in the slot stored in the ARG() of
2683 * node involved. Note that this routine doesn't actually care about the
2684 * name, that information is not preserved from compilation to execution.
2685 * Returns the index of the leftmost defined buffer with the given name
2686 * or 0 if non of the buffers matched.
2689 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
2692 RXi_GET_DECL(rex,rexi);
2693 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
2694 I32 *nums=(I32*)SvPVX(sv_dat);
2696 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
2698 for ( n=0; n<SvIVX(sv_dat); n++ ) {
2699 if ((I32)*PL_reglastparen >= nums[n] &&
2700 PL_regoffs[nums[n]].end != -1)
2709 /* free all slabs above current one - called during LEAVE_SCOPE */
2712 S_clear_backtrack_stack(pTHX_ void *p)
2714 regmatch_slab *s = PL_regmatch_slab->next;
2719 PL_regmatch_slab->next = NULL;
2721 regmatch_slab * const osl = s;
2728 #define SETREX(Re1,Re2) \
2729 if (PL_reg_eval_set) PM_SETRE((PL_reg_curpm), (Re2)); \
2732 STATIC I32 /* 0 failure, 1 success */
2733 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
2735 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2739 register const bool do_utf8 = PL_reg_match_utf8;
2740 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2741 regexp *rex = reginfo->prog;
2742 RXi_GET_DECL(rex,rexi);
2744 /* the current state. This is a cached copy of PL_regmatch_state */
2745 register regmatch_state *st;
2746 /* cache heavy used fields of st in registers */
2747 register regnode *scan;
2748 register regnode *next;
2749 register U32 n = 0; /* general value; init to avoid compiler warning */
2750 register I32 ln = 0; /* len or last; init to avoid compiler warning */
2751 register char *locinput = PL_reginput;
2752 register I32 nextchr; /* is always set to UCHARAT(locinput) */
2754 bool result = 0; /* return value of S_regmatch */
2755 int depth = 0; /* depth of backtrack stack */
2756 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
2757 const U32 max_nochange_depth =
2758 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
2759 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
2760 regmatch_state *yes_state = NULL; /* state to pop to on success of
2762 /* mark_state piggy backs on the yes_state logic so that when we unwind
2763 the stack on success we can update the mark_state as we go */
2764 regmatch_state *mark_state = NULL; /* last mark state we have seen */
2765 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
2766 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
2768 bool no_final = 0; /* prevent failure from backtracking? */
2769 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
2770 char *startpoint = PL_reginput;
2771 SV *popmark = NULL; /* are we looking for a mark? */
2772 SV *sv_commit = NULL; /* last mark name seen in failure */
2773 SV *sv_yes_mark = NULL; /* last mark name we have seen
2774 during a successfull match */
2775 U32 lastopen = 0; /* last open we saw */
2776 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
2777 SV* const oreplsv = GvSV(PL_replgv);
2778 /* these three flags are set by various ops to signal information to
2779 * the very next op. They have a useful lifetime of exactly one loop
2780 * iteration, and are not preserved or restored by state pushes/pops
2782 bool sw = 0; /* the condition value in (?(cond)a|b) */
2783 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
2784 int logical = 0; /* the following EVAL is:
2788 or the following IFMATCH/UNLESSM is:
2789 false: plain (?=foo)
2790 true: used as a condition: (?(?=foo))
2793 GET_RE_DEBUG_FLAGS_DECL;
2796 PERL_ARGS_ASSERT_REGMATCH;
2798 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
2799 PerlIO_printf(Perl_debug_log,"regmatch start\n");
2801 /* on first ever call to regmatch, allocate first slab */
2802 if (!PL_regmatch_slab) {
2803 Newx(PL_regmatch_slab, 1, regmatch_slab);
2804 PL_regmatch_slab->prev = NULL;
2805 PL_regmatch_slab->next = NULL;
2806 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2809 oldsave = PL_savestack_ix;
2810 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
2811 SAVEVPTR(PL_regmatch_slab);
2812 SAVEVPTR(PL_regmatch_state);
2814 /* grab next free state slot */
2815 st = ++PL_regmatch_state;
2816 if (st > SLAB_LAST(PL_regmatch_slab))
2817 st = PL_regmatch_state = S_push_slab(aTHX);
2819 /* Note that nextchr is a byte even in UTF */
2820 nextchr = UCHARAT(locinput);
2822 while (scan != NULL) {
2825 SV * const prop = sv_newmortal();
2826 regnode *rnext=regnext(scan);
2827 DUMP_EXEC_POS( locinput, scan, do_utf8 );
2828 regprop(rex, prop, scan);
2830 PerlIO_printf(Perl_debug_log,
2831 "%3"IVdf":%*s%s(%"IVdf")\n",
2832 (IV)(scan - rexi->program), depth*2, "",
2834 (PL_regkind[OP(scan)] == END || !rnext) ?
2835 0 : (IV)(rnext - rexi->program));
2838 next = scan + NEXT_OFF(scan);
2841 state_num = OP(scan);
2843 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
2846 assert(PL_reglastparen == &rex->lastparen);
2847 assert(PL_reglastcloseparen == &rex->lastcloseparen);
2848 assert(PL_regoffs == rex->offs);
2850 switch (state_num) {
2852 if (locinput == PL_bostr)
2854 /* reginfo->till = reginfo->bol; */
2859 if (locinput == PL_bostr ||
2860 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
2866 if (locinput == PL_bostr)
2870 if (locinput == reginfo->ganch)
2875 /* update the startpoint */
2876 st->u.keeper.val = PL_regoffs[0].start;
2877 PL_reginput = locinput;
2878 PL_regoffs[0].start = locinput - PL_bostr;
2879 PUSH_STATE_GOTO(KEEPS_next, next);
2881 case KEEPS_next_fail:
2882 /* rollback the start point change */
2883 PL_regoffs[0].start = st->u.keeper.val;
2889 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2894 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2896 if (PL_regeol - locinput > 1)
2900 if (PL_regeol != locinput)
2904 if (!nextchr && locinput >= PL_regeol)
2907 locinput += PL_utf8skip[nextchr];
2908 if (locinput > PL_regeol)
2910 nextchr = UCHARAT(locinput);
2913 nextchr = UCHARAT(++locinput);
2916 if (!nextchr && locinput >= PL_regeol)
2918 nextchr = UCHARAT(++locinput);
2921 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
2924 locinput += PL_utf8skip[nextchr];
2925 if (locinput > PL_regeol)
2927 nextchr = UCHARAT(locinput);
2930 nextchr = UCHARAT(++locinput);
2934 #define ST st->u.trie
2936 /* In this case the charclass data is available inline so
2937 we can fail fast without a lot of extra overhead.
2939 if (scan->flags == EXACT || !do_utf8) {
2940 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
2942 PerlIO_printf(Perl_debug_log,
2943 "%*s %sfailed to match trie start class...%s\n",
2944 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
2953 /* what type of TRIE am I? (utf8 makes this contextual) */
2954 DECL_TRIE_TYPE(scan);
2956 /* what trie are we using right now */
2957 reg_trie_data * const trie
2958 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
2959 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
2960 U32 state = trie->startstate;
2962 if (trie->bitmap && trie_type != trie_utf8_fold &&
2963 !TRIE_BITMAP_TEST(trie,*locinput)
2965 if (trie->states[ state ].wordnum) {
2967 PerlIO_printf(Perl_debug_log,
2968 "%*s %smatched empty string...%s\n",
2969 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
2974 PerlIO_printf(Perl_debug_log,
2975 "%*s %sfailed to match trie start class...%s\n",
2976 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
2983 U8 *uc = ( U8* )locinput;
2987 U8 *uscan = (U8*)NULL;
2989 SV *sv_accept_buff = NULL;
2990 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2992 ST.accepted = 0; /* how many accepting states we have seen */
2994 ST.jump = trie->jump;
2997 traverse the TRIE keeping track of all accepting states
2998 we transition through until we get to a failing node.
3001 while ( state && uc <= (U8*)PL_regeol ) {
3002 U32 base = trie->states[ state ].trans.base;
3005 /* We use charid to hold the wordnum as we don't use it
3006 for charid until after we have done the wordnum logic.
3007 We define an alias just so that the wordnum logic reads
3010 #define got_wordnum charid
3011 got_wordnum = trie->states[ state ].wordnum;
3013 if ( got_wordnum ) {
3014 if ( ! ST.accepted ) {
3016 SAVETMPS; /* XXX is this necessary? dmq */
3017 bufflen = TRIE_INITAL_ACCEPT_BUFFLEN;
3018 sv_accept_buff=newSV(bufflen *
3019 sizeof(reg_trie_accepted) - 1);
3020 SvCUR_set(sv_accept_buff, 0);
3021 SvPOK_on(sv_accept_buff);
3022 sv_2mortal(sv_accept_buff);
3025 (reg_trie_accepted*)SvPV_nolen(sv_accept_buff );
3028 if (ST.accepted >= bufflen) {
3030 ST.accept_buff =(reg_trie_accepted*)
3031 SvGROW(sv_accept_buff,
3032 bufflen * sizeof(reg_trie_accepted));
3034 SvCUR_set(sv_accept_buff,SvCUR(sv_accept_buff)
3035 + sizeof(reg_trie_accepted));
3038 ST.accept_buff[ST.accepted].wordnum = got_wordnum;
3039 ST.accept_buff[ST.accepted].endpos = uc;
3041 } while (trie->nextword && (got_wordnum= trie->nextword[got_wordnum]));
3045 DEBUG_TRIE_EXECUTE_r({
3046 DUMP_EXEC_POS( (char *)uc, scan, do_utf8 );
3047 PerlIO_printf( Perl_debug_log,
3048 "%*s %sState: %4"UVxf" Accepted: %4"UVxf" ",
3049 2+depth * 2, "", PL_colors[4],
3050 (UV)state, (UV)ST.accepted );
3054 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3055 uscan, len, uvc, charid, foldlen,
3059 (base + charid > trie->uniquecharcount )
3060 && (base + charid - 1 - trie->uniquecharcount
3062 && trie->trans[base + charid - 1 -
3063 trie->uniquecharcount].check == state)
3065 state = trie->trans[base + charid - 1 -
3066 trie->uniquecharcount ].next;
3077 DEBUG_TRIE_EXECUTE_r(
3078 PerlIO_printf( Perl_debug_log,
3079 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3080 charid, uvc, (UV)state, PL_colors[5] );
3087 PerlIO_printf( Perl_debug_log,
3088 "%*s %sgot %"IVdf" possible matches%s\n",
3089 REPORT_CODE_OFF + depth * 2, "",
3090 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3093 goto trie_first_try; /* jump into the fail handler */
3095 case TRIE_next_fail: /* we failed - try next alterative */
3097 REGCP_UNWIND(ST.cp);
3098 for (n = *PL_reglastparen; n > ST.lastparen; n--)
3099 PL_regoffs[n].end = -1;
3100 *PL_reglastparen = n;
3109 ST.lastparen = *PL_reglastparen;
3112 if ( ST.accepted == 1 ) {
3113 /* only one choice left - just continue */
3115 AV *const trie_words
3116 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3117 SV ** const tmp = av_fetch( trie_words,
3118 ST.accept_buff[ 0 ].wordnum-1, 0 );
3119 SV *sv= tmp ? sv_newmortal() : NULL;
3121 PerlIO_printf( Perl_debug_log,
3122 "%*s %sonly one match left: #%d <%s>%s\n",
3123 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3124 ST.accept_buff[ 0 ].wordnum,
3125 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3126 PL_colors[0], PL_colors[1],
3127 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3129 : "not compiled under -Dr",
3132 PL_reginput = (char *)ST.accept_buff[ 0 ].endpos;
3133 /* in this case we free tmps/leave before we call regmatch
3134 as we wont be using accept_buff again. */
3136 locinput = PL_reginput;
3137 nextchr = UCHARAT(locinput);
3138 if ( !ST.jump || !ST.jump[ST.accept_buff[0].wordnum])
3141 scan = ST.me + ST.jump[ST.accept_buff[0].wordnum];
3142 if (!has_cutgroup) {
3147 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3150 continue; /* execute rest of RE */
3153 if ( !ST.accepted-- ) {
3155 PerlIO_printf( Perl_debug_log,
3156 "%*s %sTRIE failed...%s\n",
3157 REPORT_CODE_OFF+depth*2, "",
3168 There are at least two accepting states left. Presumably
3169 the number of accepting states is going to be low,
3170 typically two. So we simply scan through to find the one
3171 with lowest wordnum. Once we find it, we swap the last
3172 state into its place and decrement the size. We then try to
3173 match the rest of the pattern at the point where the word
3174 ends. If we succeed, control just continues along the
3175 regex; if we fail we return here to try the next accepting
3182 for( cur = 1 ; cur <= ST.accepted ; cur++ ) {
3183 DEBUG_TRIE_EXECUTE_r(
3184 PerlIO_printf( Perl_debug_log,
3185 "%*s %sgot %"IVdf" (%d) as best, looking at %"IVdf" (%d)%s\n",
3186 REPORT_CODE_OFF + depth * 2, "", PL_colors[4],
3187 (IV)best, ST.accept_buff[ best ].wordnum, (IV)cur,
3188 ST.accept_buff[ cur ].wordnum, PL_colors[5] );
3191 if (ST.accept_buff[cur].wordnum <
3192 ST.accept_buff[best].wordnum)
3197 AV *const trie_words
3198 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3199 SV ** const tmp = av_fetch( trie_words,
3200 ST.accept_buff[ best ].wordnum - 1, 0 );
3201 regnode *nextop=(!ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) ?
3203 ST.me + ST.jump[ST.accept_buff[best].wordnum];
3204 SV *sv= tmp ? sv_newmortal() : NULL;
3206 PerlIO_printf( Perl_debug_log,
3207 "%*s %strying alternation #%d <%s> at node #%d %s\n",
3208 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3209 ST.accept_buff[best].wordnum,
3210 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3211 PL_colors[0], PL_colors[1],
3212 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3213 ) : "not compiled under -Dr",
3214 REG_NODE_NUM(nextop),
3218 if ( best<ST.accepted ) {
3219 reg_trie_accepted tmp = ST.accept_buff[ best ];
3220 ST.accept_buff[ best ] = ST.accept_buff[ ST.accepted ];
3221 ST.accept_buff[ ST.accepted ] = tmp;
3224 PL_reginput = (char *)ST.accept_buff[ best ].endpos;
3225 if ( !ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) {
3228 scan = ST.me + ST.jump[ST.accept_buff[best].wordnum];
3230 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3235 /* we dont want to throw this away, see bug 57042*/
3236 if (oreplsv != GvSV(PL_replgv))
3237 sv_setsv(oreplsv, GvSV(PL_replgv));
3244 char *s = STRING(scan);
3246 if (do_utf8 != UTF) {
3247 /* The target and the pattern have differing utf8ness. */
3249 const char * const e = s + ln;
3252 /* The target is utf8, the pattern is not utf8. */
3257 if (NATIVE_TO_UNI(*(U8*)s) !=
3258 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3266 /* The target is not utf8, the pattern is utf8. */
3271 if (NATIVE_TO_UNI(*((U8*)l)) !=
3272 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3280 nextchr = UCHARAT(locinput);
3283 /* The target and the pattern have the same utf8ness. */
3284 /* Inline the first character, for speed. */
3285 if (UCHARAT(s) != nextchr)
3287 if (PL_regeol - locinput < ln)
3289 if (ln > 1 && memNE(s, locinput, ln))
3292 nextchr = UCHARAT(locinput);
3296 PL_reg_flags |= RF_tainted;
3299 char * const s = STRING(scan);
3302 if (do_utf8 || UTF) {
3303 /* Either target or the pattern are utf8. */
3304 const char * const l = locinput;
3305 char *e = PL_regeol;
3307 if (ibcmp_utf8(s, 0, ln, (bool)UTF,
3308 l, &e, 0, do_utf8)) {
3309 /* One more case for the sharp s:
3310 * pack("U0U*", 0xDF) =~ /ss/i,
3311 * the 0xC3 0x9F are the UTF-8
3312 * byte sequence for the U+00DF. */
3315 toLOWER(s[0]) == 's' &&
3317 toLOWER(s[1]) == 's' &&
3324 nextchr = UCHARAT(locinput);
3328 /* Neither the target and the pattern are utf8. */
3330 /* Inline the first character, for speed. */
3331 if (UCHARAT(s) != nextchr &&
3332 UCHARAT(s) != ((OP(scan) == EXACTF)
3333 ? PL_fold : PL_fold_locale)[nextchr])
3335 if (PL_regeol - locinput < ln)
3337 if (ln > 1 && (OP(scan) == EXACTF
3338 ? ibcmp(s, locinput, ln)
3339 : ibcmp_locale(s, locinput, ln)))
3342 nextchr = UCHARAT(locinput);
3347 STRLEN inclasslen = PL_regeol - locinput;
3349 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, do_utf8))
3351 if (locinput >= PL_regeol)
3353 locinput += inclasslen ? inclasslen : UTF8SKIP(locinput);
3354 nextchr = UCHARAT(locinput);
3359 nextchr = UCHARAT(locinput);
3360 if (!REGINCLASS(rex, scan, (U8*)locinput))
3362 if (!nextchr && locinput >= PL_regeol)
3364 nextchr = UCHARAT(++locinput);
3368 /* If we might have the case of the German sharp s
3369 * in a casefolding Unicode character class. */
3371 if (ANYOF_FOLD_SHARP_S(scan, locinput, PL_regeol)) {
3372 locinput += SHARP_S_SKIP;
3373 nextchr = UCHARAT(locinput);
3379 PL_reg_flags |= RF_tainted;
3385 LOAD_UTF8_CHARCLASS_ALNUM();
3386 if (!(OP(scan) == ALNUM
3387 ? (bool)swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
3388 : isALNUM_LC_utf8((U8*)locinput)))
3392 locinput += PL_utf8skip[nextchr];
3393 nextchr = UCHARAT(locinput);
3396 if (!(OP(scan) == ALNUM
3397 ? isALNUM(nextchr) : isALNUM_LC(nextchr)))
3399 nextchr = UCHARAT(++locinput);
3402 PL_reg_flags |= RF_tainted;
3405 if (!nextchr && locinput >= PL_regeol)
3408 LOAD_UTF8_CHARCLASS_ALNUM();
3409 if (OP(scan) == NALNUM
3410 ? (bool)swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
3411 : isALNUM_LC_utf8((U8*)locinput))
3415 locinput += PL_utf8skip[nextchr];
3416 nextchr = UCHARAT(locinput);
3419 if (OP(scan) == NALNUM
3420 ? isALNUM(nextchr) : isALNUM_LC(nextchr))
3422 nextchr = UCHARAT(++locinput);
3426 PL_reg_flags |= RF_tainted;
3430 /* was last char in word? */
3432 if (locinput == PL_bostr)
3435 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3437 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3439 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3440 ln = isALNUM_uni(ln);
3441 LOAD_UTF8_CHARCLASS_ALNUM();
3442 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8);
3445 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3446 n = isALNUM_LC_utf8((U8*)locinput);
3450 ln = (locinput != PL_bostr) ?
3451 UCHARAT(locinput - 1) : '\n';
3452 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3454 n = isALNUM(nextchr);
3457 ln = isALNUM_LC(ln);
3458 n = isALNUM_LC(nextchr);
3461 if (((!ln) == (!n)) == (OP(scan) == BOUND ||
3462 OP(scan) == BOUNDL))
3466 PL_reg_flags |= RF_tainted;
3472 if (UTF8_IS_CONTINUED(nextchr)) {
3473 LOAD_UTF8_CHARCLASS_SPACE();
3474 if (!(OP(scan) == SPACE
3475 ? (bool)swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
3476 : isSPACE_LC_utf8((U8*)locinput)))
3480 locinput += PL_utf8skip[nextchr];
3481 nextchr = UCHARAT(locinput);
3484 if (!(OP(scan) == SPACE
3485 ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
3487 nextchr = UCHARAT(++locinput);
3490 if (!(OP(scan) == SPACE
3491 ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
3493 nextchr = UCHARAT(++locinput);
3497 PL_reg_flags |= RF_tainted;
3500 if (!nextchr && locinput >= PL_regeol)
3503 LOAD_UTF8_CHARCLASS_SPACE();
3504 if (OP(scan) == NSPACE
3505 ? (bool)swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
3506 : isSPACE_LC_utf8((U8*)locinput))
3510 locinput += PL_utf8skip[nextchr];
3511 nextchr = UCHARAT(locinput);
3514 if (OP(scan) == NSPACE
3515 ? isSPACE(nextchr) : isSPACE_LC(nextchr))
3517 nextchr = UCHARAT(++locinput);
3520 PL_reg_flags |= RF_tainted;
3526 LOAD_UTF8_CHARCLASS_DIGIT();
3527 if (!(OP(scan) == DIGIT
3528 ? (bool)swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
3529 : isDIGIT_LC_utf8((U8*)locinput)))
3533 locinput += PL_utf8skip[nextchr];
3534 nextchr = UCHARAT(locinput);
3537 if (!(OP(scan) == DIGIT
3538 ? isDIGIT(nextchr) : isDIGIT_LC(nextchr)))
3540 nextchr = UCHARAT(++locinput);
3543 PL_reg_flags |= RF_tainted;
3546 if (!nextchr && locinput >= PL_regeol)
3549 LOAD_UTF8_CHARCLASS_DIGIT();
3550 if (OP(scan) == NDIGIT
3551 ? (bool)swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
3552 : isDIGIT_LC_utf8((U8*)locinput))
3556 locinput += PL_utf8skip[nextchr];
3557 nextchr = UCHARAT(locinput);
3560 if (OP(scan) == NDIGIT
3561 ? isDIGIT(nextchr) : isDIGIT_LC(nextchr))
3563 nextchr = UCHARAT(++locinput);
3566 if (locinput >= PL_regeol)
3569 LOAD_UTF8_CHARCLASS_MARK();
3570 if (swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3572 locinput += PL_utf8skip[nextchr];
3573 while (locinput < PL_regeol &&
3574 swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3575 locinput += UTF8SKIP(locinput);
3576 if (locinput > PL_regeol)
3581 nextchr = UCHARAT(locinput);
3588 PL_reg_flags |= RF_tainted;
3593 n = reg_check_named_buff_matched(rex,scan);
3596 type = REF + ( type - NREF );
3603 PL_reg_flags |= RF_tainted;
3607 n = ARG(scan); /* which paren pair */
3610 ln = PL_regoffs[n].start;
3611 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
3612 if (*PL_reglastparen < n || ln == -1)
3613 sayNO; /* Do not match unless seen CLOSEn. */
3614 if (ln == PL_regoffs[n].end)
3618 if (do_utf8 && type != REF) { /* REF can do byte comparison */
3620 const char *e = PL_bostr + PL_regoffs[n].end;
3622 * Note that we can't do the "other character" lookup trick as
3623 * in the 8-bit case (no pun intended) because in Unicode we
3624 * have to map both upper and title case to lower case.
3628 STRLEN ulen1, ulen2;
3629 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
3630 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
3634 toLOWER_utf8((U8*)s, tmpbuf1, &ulen1);
3635 toLOWER_utf8((U8*)l, tmpbuf2, &ulen2);
3636 if (ulen1 != ulen2 || memNE((char *)tmpbuf1, (char *)tmpbuf2, ulen1))
3643 nextchr = UCHARAT(locinput);
3647 /* Inline the first character, for speed. */
3648 if (UCHARAT(s) != nextchr &&
3650 (UCHARAT(s) != (type == REFF
3651 ? PL_fold : PL_fold_locale)[nextchr])))
3653 ln = PL_regoffs[n].end - ln;
3654 if (locinput + ln > PL_regeol)
3656 if (ln > 1 && (type == REF
3657 ? memNE(s, locinput, ln)
3659 ? ibcmp(s, locinput, ln)
3660 : ibcmp_locale(s, locinput, ln))))
3663 nextchr = UCHARAT(locinput);
3673 #define ST st->u.eval
3677 regexp_internal *rei;
3678 regnode *startpoint;
3681 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
3682 if (cur_eval && cur_eval->locinput==locinput) {
3683 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
3684 Perl_croak(aTHX_ "Infinite recursion in regex");
3685 if ( ++nochange_depth > max_nochange_depth )
3687 "Pattern subroutine nesting without pos change"
3688 " exceeded limit in regex");
3694 (void)ReREFCNT_inc(rex);
3695 if (OP(scan)==GOSUB) {
3696 startpoint = scan + ARG2L(scan);
3697 ST.close_paren = ARG(scan);
3699 startpoint = rei->program+1;
3702 goto eval_recurse_doit;
3704 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
3705 if (cur_eval && cur_eval->locinput==locinput) {
3706 if ( ++nochange_depth > max_nochange_depth )
3707 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
3712 /* execute the code in the {...} */
3714 SV ** const before = SP;
3715 OP_4tree * const oop = PL_op;
3716 COP * const ocurcop = PL_curcop;
3720 PL_op = (OP_4tree*)rexi->data->data[n];
3721 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
3722 " re_eval 0x%"UVxf"\n", PTR2UV(PL_op)) );
3723 PAD_SAVE_LOCAL(old_comppad, (PAD*)rexi->data->data[n + 2]);
3724 PL_regoffs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
3727 SV *sv_mrk = get_sv("REGMARK", 1);
3728 sv_setsv(sv_mrk, sv_yes_mark);
3731 CALLRUNOPS(aTHX); /* Scalar context. */
3734 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
3741 PAD_RESTORE_LOCAL(old_comppad);
3742 PL_curcop = ocurcop;
3745 sv_setsv(save_scalar(PL_replgv), ret);
3749 if (logical == 2) { /* Postponed subexpression: /(??{...})/ */
3752 /* extract RE object from returned value; compiling if
3757 if(SvROK(ret) && SvSMAGICAL(sv = SvRV(ret)))
3758 mg = mg_find(sv, PERL_MAGIC_qr);
3759 else if (SvSMAGICAL(ret)) {
3760 if (SvGMAGICAL(ret))
3761 sv_unmagic(ret, PERL_MAGIC_qr);
3763 mg = mg_find(ret, PERL_MAGIC_qr);
3767 re = reg_temp_copy((regexp *)mg->mg_obj); /*XXX:dmq*/
3771 const I32 osize = PL_regsize;
3773 if (DO_UTF8(ret)) pm_flags |= RXf_UTF8;
3774 re = CALLREGCOMP(ret, pm_flags);
3776 & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
3778 sv_magic(ret,MUTABLE_SV(ReREFCNT_inc(re)),
3783 RXp_MATCH_COPIED_off(re);
3784 re->subbeg = rex->subbeg;
3785 re->sublen = rex->sublen;
3788 debug_start_match(re, do_utf8, locinput, PL_regeol,
3789 "Matching embedded");
3791 startpoint = rei->program + 1;
3792 ST.close_paren = 0; /* only used for GOSUB */
3793 /* borrowed from regtry */
3794 if (PL_reg_start_tmpl <= re->nparens) {
3795 PL_reg_start_tmpl = re->nparens*3/2 + 3;
3796 if(PL_reg_start_tmp)
3797 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
3799 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
3802 eval_recurse_doit: /* Share code with GOSUB below this line */
3803 /* run the pattern returned from (??{...}) */
3804 ST.cp = regcppush(0); /* Save *all* the positions. */
3805 REGCP_SET(ST.lastcp);
3807 PL_regoffs = re->offs; /* essentially NOOP on GOSUB */
3809 /* see regtry, specifically PL_reglast(?:close)?paren is a pointer! (i dont know why) :dmq */
3810 PL_reglastparen = &re->lastparen;
3811 PL_reglastcloseparen = &re->lastcloseparen;
3813 re->lastcloseparen = 0;
3815 PL_reginput = locinput;
3818 /* XXXX This is too dramatic a measure... */
3821 ST.toggle_reg_flags = PL_reg_flags;
3823 PL_reg_flags |= RF_utf8;
3825 PL_reg_flags &= ~RF_utf8;
3826 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
3829 ST.prev_curlyx = cur_curlyx;
3834 ST.prev_eval = cur_eval;
3836 /* now continue from first node in postoned RE */
3837 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
3840 /* logical is 1, /(?(?{...})X|Y)/ */
3841 sw = (bool)SvTRUE(ret);
3846 case EVAL_AB: /* cleanup after a successful (??{A})B */
3847 /* note: this is called twice; first after popping B, then A */
3848 PL_reg_flags ^= ST.toggle_reg_flags;
3850 SETREX(rex,ST.prev_rex);
3851 rexi = RXi_GET(rex);
3853 cur_eval = ST.prev_eval;
3854 cur_curlyx = ST.prev_curlyx;
3856 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
3857 PL_reglastparen = &rex->lastparen;
3858 PL_reglastcloseparen = &rex->lastcloseparen;
3859 /* also update PL_regoffs */
3860 PL_regoffs = rex->offs;
3862 /* XXXX This is too dramatic a measure... */
3864 if ( nochange_depth )
3869 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
3870 /* note: this is called twice; first after popping B, then A */
3871 PL_reg_flags ^= ST.toggle_reg_flags;
3873 SETREX(rex,ST.prev_rex);
3874 rexi = RXi_GET(rex);
3875 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
3876 PL_reglastparen = &rex->lastparen;
3877 PL_reglastcloseparen = &rex->lastcloseparen;
3879 PL_reginput = locinput;
3880 REGCP_UNWIND(ST.lastcp);
3882 cur_eval = ST.prev_eval;
3883 cur_curlyx = ST.prev_curlyx;
3884 /* XXXX This is too dramatic a measure... */
3886 if ( nochange_depth )
3892 n = ARG(scan); /* which paren pair */
3893 PL_reg_start_tmp[n] = locinput;
3899 n = ARG(scan); /* which paren pair */
3900 PL_regoffs[n].start = PL_reg_start_tmp[n] - PL_bostr;
3901 PL_regoffs[n].end = locinput - PL_bostr;
3902 /*if (n > PL_regsize)
3904 if (n > *PL_reglastparen)
3905 *PL_reglastparen = n;
3906 *PL_reglastcloseparen = n;
3907 if (cur_eval && cur_eval->u.eval.close_paren == n) {
3915 cursor && OP(cursor)!=END;
3916 cursor=regnext(cursor))
3918 if ( OP(cursor)==CLOSE ){
3920 if ( n <= lastopen ) {
3922 = PL_reg_start_tmp[n] - PL_bostr;
3923 PL_regoffs[n].end = locinput - PL_bostr;
3924 /*if (n > PL_regsize)
3926 if (n > *PL_reglastparen)
3927 *PL_reglastparen = n;
3928 *PL_reglastcloseparen = n;
3929 if ( n == ARG(scan) || (cur_eval &&
3930 cur_eval->u.eval.close_paren == n))
3939 n = ARG(scan); /* which paren pair */
3940 sw = (bool)(*PL_reglastparen >= n && PL_regoffs[n].end != -1);
3943 /* reg_check_named_buff_matched returns 0 for no match */
3944 sw = (bool)(0 < reg_check_named_buff_matched(rex,scan));
3948 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
3954 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
3956 next = NEXTOPER(NEXTOPER(scan));
3958 next = scan + ARG(scan);
3959 if (OP(next) == IFTHEN) /* Fake one. */
3960 next = NEXTOPER(NEXTOPER(next));
3964 logical = scan->flags;
3967 /*******************************************************************
3969 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
3970 pattern, where A and B are subpatterns. (For simple A, CURLYM or
3971 STAR/PLUS/CURLY/CURLYN are used instead.)
3973 A*B is compiled as <CURLYX><A><WHILEM><B>
3975 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
3976 state, which contains the current count, initialised to -1. It also sets
3977 cur_curlyx to point to this state, with any previous value saved in the
3980 CURLYX then jumps straight to the WHILEM op, rather than executing A,
3981 since the pattern may possibly match zero times (i.e. it's a while {} loop
3982 rather than a do {} while loop).
3984 Each entry to WHILEM represents a successful match of A. The count in the
3985 CURLYX block is incremented, another WHILEM state is pushed, and execution
3986 passes to A or B depending on greediness and the current count.
3988 For example, if matching against the string a1a2a3b (where the aN are
3989 substrings that match /A/), then the match progresses as follows: (the
3990 pushed states are interspersed with the bits of strings matched so far):
3993 <CURLYX cnt=0><WHILEM>
3994 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
3995 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
3996 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
3997 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
3999 (Contrast this with something like CURLYM, which maintains only a single
4003 a1 <CURLYM cnt=1> a2
4004 a1 a2 <CURLYM cnt=2> a3
4005 a1 a2 a3 <CURLYM cnt=3> b
4008 Each WHILEM state block marks a point to backtrack to upon partial failure
4009 of A or B, and also contains some minor state data related to that
4010 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
4011 overall state, such as the count, and pointers to the A and B ops.
4013 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4014 must always point to the *current* CURLYX block, the rules are:
4016 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4017 and set cur_curlyx to point the new block.
4019 When popping the CURLYX block after a successful or unsuccessful match,
4020 restore the previous cur_curlyx.
4022 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4023 to the outer one saved in the CURLYX block.
4025 When popping the WHILEM block after a successful or unsuccessful B match,
4026 restore the previous cur_curlyx.
4028 Here's an example for the pattern (AI* BI)*BO
4029 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4032 curlyx backtrack stack
4033 ------ ---------------
4035 CO <CO prev=NULL> <WO>
4036 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4037 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4038 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4040 At this point the pattern succeeds, and we work back down the stack to
4041 clean up, restoring as we go:
4043 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4044 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4045 CO <CO prev=NULL> <WO>
4048 *******************************************************************/
4050 #define ST st->u.curlyx
4052 case CURLYX: /* start of /A*B/ (for complex A) */
4054 /* No need to save/restore up to this paren */
4055 I32 parenfloor = scan->flags;
4057 assert(next); /* keep Coverity happy */
4058 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4061 /* XXXX Probably it is better to teach regpush to support
4062 parenfloor > PL_regsize... */
4063 if (parenfloor > (I32)*PL_reglastparen)
4064 parenfloor = *PL_reglastparen; /* Pessimization... */
4066 ST.prev_curlyx= cur_curlyx;
4068 ST.cp = PL_savestack_ix;
4070 /* these fields contain the state of the current curly.
4071 * they are accessed by subsequent WHILEMs */
4072 ST.parenfloor = parenfloor;
4073 ST.min = ARG1(scan);
4074 ST.max = ARG2(scan);
4075 ST.A = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
4079 ST.count = -1; /* this will be updated by WHILEM */
4080 ST.lastloc = NULL; /* this will be updated by WHILEM */
4082 PL_reginput = locinput;
4083 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4087 case CURLYX_end: /* just finished matching all of A*B */
4088 cur_curlyx = ST.prev_curlyx;
4092 case CURLYX_end_fail: /* just failed to match all of A*B */
4094 cur_curlyx = ST.prev_curlyx;
4100 #define ST st->u.whilem
4102 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
4104 /* see the discussion above about CURLYX/WHILEM */
4106 assert(cur_curlyx); /* keep Coverity happy */
4107 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4108 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4109 ST.cache_offset = 0;
4112 PL_reginput = locinput;
4114 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4115 "%*s whilem: matched %ld out of %ld..%ld\n",
4116 REPORT_CODE_OFF+depth*2, "", (long)n,
4117 (long)cur_curlyx->u.curlyx.min,
4118 (long)cur_curlyx->u.curlyx.max)
4121 /* First just match a string of min A's. */
4123 if (n < cur_curlyx->u.curlyx.min) {
4124 cur_curlyx->u.curlyx.lastloc = locinput;
4125 PUSH_STATE_GOTO(WHILEM_A_pre, cur_curlyx->u.curlyx.A);
4129 /* If degenerate A matches "", assume A done. */
4131 if (locinput == cur_curlyx->u.curlyx.lastloc) {
4132 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4133 "%*s whilem: empty match detected, trying continuation...\n",
4134 REPORT_CODE_OFF+depth*2, "")
4136 goto do_whilem_B_max;
4139 /* super-linear cache processing */
4143 if (!PL_reg_maxiter) {
4144 /* start the countdown: Postpone detection until we
4145 * know the match is not *that* much linear. */
4146 PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4147 /* possible overflow for long strings and many CURLYX's */
4148 if (PL_reg_maxiter < 0)
4149 PL_reg_maxiter = I32_MAX;
4150 PL_reg_leftiter = PL_reg_maxiter;
4153 if (PL_reg_leftiter-- == 0) {
4154 /* initialise cache */
4155 const I32 size = (PL_reg_maxiter + 7)/8;
4156 if (PL_reg_poscache) {
4157 if ((I32)PL_reg_poscache_size < size) {
4158 Renew(PL_reg_poscache, size, char);
4159 PL_reg_poscache_size = size;
4161 Zero(PL_reg_poscache, size, char);
4164 PL_reg_poscache_size = size;
4165 Newxz(PL_reg_poscache, size, char);
4167 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4168 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4169 PL_colors[4], PL_colors[5])
4173 if (PL_reg_leftiter < 0) {
4174 /* have we already failed at this position? */
4176 offset = (scan->flags & 0xf) - 1
4177 + (locinput - PL_bostr) * (scan->flags>>4);
4178 mask = 1 << (offset % 8);
4180 if (PL_reg_poscache[offset] & mask) {
4181 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4182 "%*s whilem: (cache) already tried at this position...\n",
4183 REPORT_CODE_OFF+depth*2, "")
4185 sayNO; /* cache records failure */
4187 ST.cache_offset = offset;
4188 ST.cache_mask = mask;
4192 /* Prefer B over A for minimal matching. */
4194 if (cur_curlyx->u.curlyx.minmod) {
4195 ST.save_curlyx = cur_curlyx;
4196 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4197 ST.cp = regcppush(ST.save_curlyx->u.curlyx.parenfloor);
4198 REGCP_SET(ST.lastcp);
4199 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4203 /* Prefer A over B for maximal matching. */
4205 if (n < cur_curlyx->u.curlyx.max) { /* More greed allowed? */
4206 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4207 cur_curlyx->u.curlyx.lastloc = locinput;
4208 REGCP_SET(ST.lastcp);
4209 PUSH_STATE_GOTO(WHILEM_A_max, cur_curlyx->u.curlyx.A);
4212 goto do_whilem_B_max;
4216 case WHILEM_B_min: /* just matched B in a minimal match */
4217 case WHILEM_B_max: /* just matched B in a maximal match */
4218 cur_curlyx = ST.save_curlyx;
4222 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4223 cur_curlyx = ST.save_curlyx;
4224 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4225 cur_curlyx->u.curlyx.count--;
4229 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4230 REGCP_UNWIND(ST.lastcp);
4233 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
4234 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4235 cur_curlyx->u.curlyx.count--;
4239 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
4240 REGCP_UNWIND(ST.lastcp);
4241 regcppop(rex); /* Restore some previous $<digit>s? */
4242 PL_reginput = locinput;
4243 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4244 "%*s whilem: failed, trying continuation...\n",
4245 REPORT_CODE_OFF+depth*2, "")
4248 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4249 && ckWARN(WARN_REGEXP)
4250 && !(PL_reg_flags & RF_warned))
4252 PL_reg_flags |= RF_warned;
4253 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
4254 "Complex regular subexpression recursion",
4259 ST.save_curlyx = cur_curlyx;
4260 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4261 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
4264 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
4265 cur_curlyx = ST.save_curlyx;
4266 REGCP_UNWIND(ST.lastcp);
4269 if (cur_curlyx->u.curlyx.count >= cur_curlyx->u.curlyx.max) {
4270 /* Maximum greed exceeded */
4271 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4272 && ckWARN(WARN_REGEXP)
4273 && !(PL_reg_flags & RF_warned))
4275 PL_reg_flags |= RF_warned;
4276 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
4277 "%s limit (%d) exceeded",
4278 "Complex regular subexpression recursion",
4281 cur_curlyx->u.curlyx.count--;
4285 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4286 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
4288 /* Try grabbing another A and see if it helps. */
4289 PL_reginput = locinput;
4290 cur_curlyx->u.curlyx.lastloc = locinput;
4291 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4292 REGCP_SET(ST.lastcp);
4293 PUSH_STATE_GOTO(WHILEM_A_min, ST.save_curlyx->u.curlyx.A);
4297 #define ST st->u.branch
4299 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
4300 next = scan + ARG(scan);
4303 scan = NEXTOPER(scan);
4306 case BRANCH: /* /(...|A|...)/ */
4307 scan = NEXTOPER(scan); /* scan now points to inner node */
4308 ST.lastparen = *PL_reglastparen;
4309 ST.next_branch = next;
4311 PL_reginput = locinput;
4313 /* Now go into the branch */
4315 PUSH_YES_STATE_GOTO(BRANCH_next, scan);
4317 PUSH_STATE_GOTO(BRANCH_next, scan);
4321 PL_reginput = locinput;
4322 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
4323 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4324 PUSH_STATE_GOTO(CUTGROUP_next,next);
4326 case CUTGROUP_next_fail:
4329 if (st->u.mark.mark_name)
4330 sv_commit = st->u.mark.mark_name;
4336 case BRANCH_next_fail: /* that branch failed; try the next, if any */
4341 REGCP_UNWIND(ST.cp);
4342 for (n = *PL_reglastparen; n > ST.lastparen; n--)
4343 PL_regoffs[n].end = -1;
4344 *PL_reglastparen = n;
4345 /*dmq: *PL_reglastcloseparen = n; */
4346 scan = ST.next_branch;
4347 /* no more branches? */
4348 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
4350 PerlIO_printf( Perl_debug_log,
4351 "%*s %sBRANCH failed...%s\n",
4352 REPORT_CODE_OFF+depth*2, "",
4358 continue; /* execute next BRANCH[J] op */
4366 #define ST st->u.curlym
4368 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
4370 /* This is an optimisation of CURLYX that enables us to push
4371 * only a single backtracking state, no matter how many matches
4372 * there are in {m,n}. It relies on the pattern being constant
4373 * length, with no parens to influence future backrefs
4377 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4379 /* if paren positive, emulate an OPEN/CLOSE around A */
4381 U32 paren = ST.me->flags;
4382 if (paren > PL_regsize)
4384 if (paren > *PL_reglastparen)
4385 *PL_reglastparen = paren;
4386 scan += NEXT_OFF(scan); /* Skip former OPEN. */
4394 ST.c1 = CHRTEST_UNINIT;
4397 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
4400 curlym_do_A: /* execute the A in /A{m,n}B/ */
4401 PL_reginput = locinput;
4402 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
4405 case CURLYM_A: /* we've just matched an A */
4406 locinput = st->locinput;
4407 nextchr = UCHARAT(locinput);
4410 /* after first match, determine A's length: u.curlym.alen */
4411 if (ST.count == 1) {
4412 if (PL_reg_match_utf8) {
4414 while (s < PL_reginput) {
4420 ST.alen = PL_reginput - locinput;
4423 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
4426 PerlIO_printf(Perl_debug_log,
4427 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
4428 (int)(REPORT_CODE_OFF+(depth*2)), "",
4429 (IV) ST.count, (IV)ST.alen)
4432 locinput = PL_reginput;
4434 if (cur_eval && cur_eval->u.eval.close_paren &&
4435 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4439 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
4440 if ( max == REG_INFTY || ST.count < max )
4441 goto curlym_do_A; /* try to match another A */
4443 goto curlym_do_B; /* try to match B */
4445 case CURLYM_A_fail: /* just failed to match an A */
4446 REGCP_UNWIND(ST.cp);
4448 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
4449 || (cur_eval && cur_eval->u.eval.close_paren &&
4450 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
4453 curlym_do_B: /* execute the B in /A{m,n}B/ */
4454 PL_reginput = locinput;
4455 if (ST.c1 == CHRTEST_UNINIT) {
4456 /* calculate c1 and c2 for possible match of 1st char
4457 * following curly */
4458 ST.c1 = ST.c2 = CHRTEST_VOID;
4459 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
4460 regnode *text_node = ST.B;
4461 if (! HAS_TEXT(text_node))
4462 FIND_NEXT_IMPT(text_node);
4465 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
4467 But the former is redundant in light of the latter.
4469 if this changes back then the macro for
4470 IS_TEXT and friends need to change.
4472 if (PL_regkind[OP(text_node)] == EXACT)
4475 ST.c1 = (U8)*STRING(text_node);
4477 (IS_TEXTF(text_node))
4479 : (IS_TEXTFL(text_node))
4480 ? PL_fold_locale[ST.c1]
4487 PerlIO_printf(Perl_debug_log,
4488 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
4489 (int)(REPORT_CODE_OFF+(depth*2)),
4492 if (ST.c1 != CHRTEST_VOID
4493 && UCHARAT(PL_reginput) != ST.c1
4494 && UCHARAT(PL_reginput) != ST.c2)
4496 /* simulate B failing */
4498 PerlIO_printf(Perl_debug_log,
4499 "%*s CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
4500 (int)(REPORT_CODE_OFF+(depth*2)),"",
4503 state_num = CURLYM_B_fail;
4504 goto reenter_switch;
4508 /* mark current A as captured */
4509 I32 paren = ST.me->flags;
4511 PL_regoffs[paren].start
4512 = HOPc(PL_reginput, -ST.alen) - PL_bostr;
4513 PL_regoffs[paren].end = PL_reginput - PL_bostr;
4514 /*dmq: *PL_reglastcloseparen = paren; */
4517 PL_regoffs[paren].end = -1;
4518 if (cur_eval && cur_eval->u.eval.close_paren &&
4519 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4528 PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
4531 case CURLYM_B_fail: /* just failed to match a B */
4532 REGCP_UNWIND(ST.cp);
4534 I32 max = ARG2(ST.me);
4535 if (max != REG_INFTY && ST.count == max)
4537 goto curlym_do_A; /* try to match a further A */
4539 /* backtrack one A */
4540 if (ST.count == ARG1(ST.me) /* min */)
4543 locinput = HOPc(locinput, -ST.alen);
4544 goto curlym_do_B; /* try to match B */
4547 #define ST st->u.curly
4549 #define CURLY_SETPAREN(paren, success) \
4552 PL_regoffs[paren].start = HOPc(locinput, -1) - PL_bostr; \
4553 PL_regoffs[paren].end = locinput - PL_bostr; \
4554 *PL_reglastcloseparen = paren; \
4557 PL_regoffs[paren].end = -1; \
4560 case STAR: /* /A*B/ where A is width 1 */
4564 scan = NEXTOPER(scan);
4566 case PLUS: /* /A+B/ where A is width 1 */
4570 scan = NEXTOPER(scan);
4572 case CURLYN: /* /(A){m,n}B/ where A is width 1 */
4573 ST.paren = scan->flags; /* Which paren to set */
4574 if (ST.paren > PL_regsize)
4575 PL_regsize = ST.paren;
4576 if (ST.paren > *PL_reglastparen)
4577 *PL_reglastparen = ST.paren;
4578 ST.min = ARG1(scan); /* min to match */
4579 ST.max = ARG2(scan); /* max to match */
4580 if (cur_eval && cur_eval->u.eval.close_paren &&
4581 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4585 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
4587 case CURLY: /* /A{m,n}B/ where A is width 1 */
4589 ST.min = ARG1(scan); /* min to match */
4590 ST.max = ARG2(scan); /* max to match */
4591 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4594 * Lookahead to avoid useless match attempts
4595 * when we know what character comes next.
4597 * Used to only do .*x and .*?x, but now it allows
4598 * for )'s, ('s and (?{ ... })'s to be in the way
4599 * of the quantifier and the EXACT-like node. -- japhy
4602 if (ST.min > ST.max) /* XXX make this a compile-time check? */
4604 if (HAS_TEXT(next) || JUMPABLE(next)) {
4606 regnode *text_node = next;
4608 if (! HAS_TEXT(text_node))
4609 FIND_NEXT_IMPT(text_node);
4611 if (! HAS_TEXT(text_node))
4612 ST.c1 = ST.c2 = CHRTEST_VOID;
4614 if ( PL_regkind[OP(text_node)] != EXACT ) {
4615 ST.c1 = ST.c2 = CHRTEST_VOID;
4616 goto assume_ok_easy;
4619 s = (U8*)STRING(text_node);
4621 /* Currently we only get here when
4623 PL_rekind[OP(text_node)] == EXACT
4625 if this changes back then the macro for IS_TEXT and
4626 friends need to change. */
4629 if (IS_TEXTF(text_node))
4630 ST.c2 = PL_fold[ST.c1];
4631 else if (IS_TEXTFL(text_node))
4632 ST.c2 = PL_fold_locale[ST.c1];
4635 if (IS_TEXTF(text_node)) {
4636 STRLEN ulen1, ulen2;
4637 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
4638 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
4640 to_utf8_lower((U8*)s, tmpbuf1, &ulen1);
4641 to_utf8_upper((U8*)s, tmpbuf2, &ulen2);
4643 ST.c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXLEN, 0,
4645 0 : UTF8_ALLOW_ANY);
4646 ST.c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXLEN, 0,
4648 0 : UTF8_ALLOW_ANY);
4650 ST.c1 = utf8n_to_uvuni(tmpbuf1, UTF8_MAXBYTES, 0,
4652 ST.c2 = utf8n_to_uvuni(tmpbuf2, UTF8_MAXBYTES, 0,
4657 ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
4664 ST.c1 = ST.c2 = CHRTEST_VOID;
4669 PL_reginput = locinput;
4672 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
4675 locinput = PL_reginput;
4677 if (ST.c1 == CHRTEST_VOID)
4678 goto curly_try_B_min;
4680 ST.oldloc = locinput;
4682 /* set ST.maxpos to the furthest point along the
4683 * string that could possibly match */
4684 if (ST.max == REG_INFTY) {
4685 ST.maxpos = PL_regeol - 1;
4687 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
4691 int m = ST.max - ST.min;
4692 for (ST.maxpos = locinput;
4693 m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
4694 ST.maxpos += UTF8SKIP(ST.maxpos);
4697 ST.maxpos = locinput + ST.max - ST.min;
4698 if (ST.maxpos >= PL_regeol)
4699 ST.maxpos = PL_regeol - 1;
4701 goto curly_try_B_min_known;
4705 ST.count = regrepeat(rex, ST.A, ST.max, depth);
4706 locinput = PL_reginput;
4707 if (ST.count < ST.min)
4709 if ((ST.count > ST.min)
4710 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
4712 /* A{m,n} must come at the end of the string, there's
4713 * no point in backing off ... */
4715 /* ...except that $ and \Z can match before *and* after
4716 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
4717 We may back off by one in this case. */
4718 if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
4722 goto curly_try_B_max;
4727 case CURLY_B_min_known_fail:
4728 /* failed to find B in a non-greedy match where c1,c2 valid */
4729 if (ST.paren && ST.count)
4730 PL_regoffs[ST.paren].end = -1;
4732 PL_reginput = locinput; /* Could be reset... */
4733 REGCP_UNWIND(ST.cp);
4734 /* Couldn't or didn't -- move forward. */
4735 ST.oldloc = locinput;
4737 locinput += UTF8SKIP(locinput);
4741 curly_try_B_min_known:
4742 /* find the next place where 'B' could work, then call B */
4746 n = (ST.oldloc == locinput) ? 0 : 1;
4747 if (ST.c1 == ST.c2) {
4749 /* set n to utf8_distance(oldloc, locinput) */
4750 while (locinput <= ST.maxpos &&
4751 utf8n_to_uvchr((U8*)locinput,
4752 UTF8_MAXBYTES, &len,
4753 uniflags) != (UV)ST.c1) {
4759 /* set n to utf8_distance(oldloc, locinput) */
4760 while (locinput <= ST.maxpos) {
4762 const UV c = utf8n_to_uvchr((U8*)locinput,
4763 UTF8_MAXBYTES, &len,
4765 if (c == (UV)ST.c1 || c == (UV)ST.c2)
4773 if (ST.c1 == ST.c2) {
4774 while (locinput <= ST.maxpos &&
4775 UCHARAT(locinput) != ST.c1)
4779 while (locinput <= ST.maxpos
4780 && UCHARAT(locinput) != ST.c1
4781 && UCHARAT(locinput) != ST.c2)
4784 n = locinput - ST.oldloc;
4786 if (locinput > ST.maxpos)
4788 /* PL_reginput == oldloc now */
4791 if (regrepeat(rex, ST.A, n, depth) < n)
4794 PL_reginput = locinput;
4795 CURLY_SETPAREN(ST.paren, ST.count);
4796 if (cur_eval && cur_eval->u.eval.close_paren &&
4797 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4800 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
4805 case CURLY_B_min_fail:
4806 /* failed to find B in a non-greedy match where c1,c2 invalid */
4807 if (ST.paren && ST.count)
4808 PL_regoffs[ST.paren].end = -1;
4810 REGCP_UNWIND(ST.cp);
4811 /* failed -- move forward one */
4812 PL_reginput = locinput;
4813 if (regrepeat(rex, ST.A, 1, depth)) {
4815 locinput = PL_reginput;
4816 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
4817 ST.count > 0)) /* count overflow ? */
4820 CURLY_SETPAREN(ST.paren, ST.count);
4821 if (cur_eval && cur_eval->u.eval.close_paren &&
4822 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4825 PUSH_STATE_GOTO(CURLY_B_min, ST.B);
4833 /* a successful greedy match: now try to match B */
4834 if (cur_eval && cur_eval->u.eval.close_paren &&
4835 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4840 if (ST.c1 != CHRTEST_VOID)
4841 c = do_utf8 ? utf8n_to_uvchr((U8*)PL_reginput,
4842 UTF8_MAXBYTES, 0, uniflags)
4843 : (UV) UCHARAT(PL_reginput);
4844 /* If it could work, try it. */
4845 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
4846 CURLY_SETPAREN(ST.paren, ST.count);
4847 PUSH_STATE_GOTO(CURLY_B_max, ST.B);
4852 case CURLY_B_max_fail:
4853 /* failed to find B in a greedy match */
4854 if (ST.paren && ST.count)
4855 PL_regoffs[ST.paren].end = -1;
4857 REGCP_UNWIND(ST.cp);
4859 if (--ST.count < ST.min)
4861 PL_reginput = locinput = HOPc(locinput, -1);
4862 goto curly_try_B_max;
4869 /* we've just finished A in /(??{A})B/; now continue with B */
4871 st->u.eval.toggle_reg_flags
4872 = cur_eval->u.eval.toggle_reg_flags;
4873 PL_reg_flags ^= st->u.eval.toggle_reg_flags;
4875 st->u.eval.prev_rex = rex; /* inner */
4876 SETREX(rex,cur_eval->u.eval.prev_rex);
4877 rexi = RXi_GET(rex);
4878 cur_curlyx = cur_eval->u.eval.prev_curlyx;
4880 st->u.eval.cp = regcppush(0); /* Save *all* the positions. */
4882 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
4883 PL_reglastparen = &rex->lastparen;
4884 PL_reglastcloseparen = &rex->lastcloseparen;
4886 REGCP_SET(st->u.eval.lastcp);
4887 PL_reginput = locinput;
4889 /* Restore parens of the outer rex without popping the
4891 tmpix = PL_savestack_ix;
4892 PL_savestack_ix = cur_eval->u.eval.lastcp;
4894 PL_savestack_ix = tmpix;
4896 st->u.eval.prev_eval = cur_eval;
4897 cur_eval = cur_eval->u.eval.prev_eval;
4899 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
4900 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
4901 if ( nochange_depth )
4904 PUSH_YES_STATE_GOTO(EVAL_AB,
4905 st->u.eval.prev_eval->u.eval.B); /* match B */
4908 if (locinput < reginfo->till) {
4909 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4910 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
4912 (long)(locinput - PL_reg_starttry),
4913 (long)(reginfo->till - PL_reg_starttry),
4916 sayNO_SILENT; /* Cannot match: too short. */
4918 PL_reginput = locinput; /* put where regtry can find it */
4919 sayYES; /* Success! */
4921 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
4923 PerlIO_printf(Perl_debug_log,
4924 "%*s %ssubpattern success...%s\n",
4925 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
4926 PL_reginput = locinput; /* put where regtry can find it */
4927 sayYES; /* Success! */
4930 #define ST st->u.ifmatch
4932 case SUSPEND: /* (?>A) */
4934 PL_reginput = locinput;
4937 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
4939 goto ifmatch_trivial_fail_test;
4941 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
4943 ifmatch_trivial_fail_test:
4945 char * const s = HOPBACKc(locinput, scan->flags);
4950 sw = 1 - (bool)ST.wanted;
4954 next = scan + ARG(scan);
4962 PL_reginput = locinput;
4966 ST.logical = logical;
4967 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
4969 /* execute body of (?...A) */
4970 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
4973 case IFMATCH_A_fail: /* body of (?...A) failed */
4974 ST.wanted = !ST.wanted;
4977 case IFMATCH_A: /* body of (?...A) succeeded */
4979 sw = (bool)ST.wanted;
4981 else if (!ST.wanted)
4984 if (OP(ST.me) == SUSPEND)
4985 locinput = PL_reginput;
4987 locinput = PL_reginput = st->locinput;
4988 nextchr = UCHARAT(locinput);
4990 scan = ST.me + ARG(ST.me);
4993 continue; /* execute B */
4998 next = scan + ARG(scan);
5003 reginfo->cutpoint = PL_regeol;
5006 PL_reginput = locinput;
5008 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5009 PUSH_STATE_GOTO(COMMIT_next,next);
5011 case COMMIT_next_fail:
5018 #define ST st->u.mark
5020 ST.prev_mark = mark_state;
5021 ST.mark_name = sv_commit = sv_yes_mark
5022 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5024 ST.mark_loc = PL_reginput = locinput;
5025 PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5027 case MARKPOINT_next:
5028 mark_state = ST.prev_mark;
5031 case MARKPOINT_next_fail:
5032 if (popmark && sv_eq(ST.mark_name,popmark))
5034 if (ST.mark_loc > startpoint)
5035 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5036 popmark = NULL; /* we found our mark */
5037 sv_commit = ST.mark_name;
5040 PerlIO_printf(Perl_debug_log,
5041 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
5042 REPORT_CODE_OFF+depth*2, "",
5043 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5046 mark_state = ST.prev_mark;
5047 sv_yes_mark = mark_state ?
5048 mark_state->u.mark.mark_name : NULL;
5052 PL_reginput = locinput;
5054 /* (*SKIP) : if we fail we cut here*/
5055 ST.mark_name = NULL;
5056 ST.mark_loc = locinput;
5057 PUSH_STATE_GOTO(SKIP_next,next);
5059 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5060 otherwise do nothing. Meaning we need to scan
5062 regmatch_state *cur = mark_state;
5063 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5066 if ( sv_eq( cur->u.mark.mark_name,
5069 ST.mark_name = find;
5070 PUSH_STATE_GOTO( SKIP_next, next );
5072 cur = cur->u.mark.prev_mark;
5075 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5077 case SKIP_next_fail:
5079 /* (*CUT:NAME) - Set up to search for the name as we
5080 collapse the stack*/
5081 popmark = ST.mark_name;
5083 /* (*CUT) - No name, we cut here.*/
5084 if (ST.mark_loc > startpoint)
5085 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5086 /* but we set sv_commit to latest mark_name if there
5087 is one so they can test to see how things lead to this
5090 sv_commit=mark_state->u.mark.mark_name;
5098 if ( n == (U32)what_len_TRICKYFOLD(locinput,do_utf8,ln) ) {
5100 } else if ( 0xDF == n && !do_utf8 && !UTF ) {
5103 U8 folded[UTF8_MAXBYTES_CASE+1];
5105 const char * const l = locinput;
5106 char *e = PL_regeol;
5107 to_uni_fold(n, folded, &foldlen);
5109 if (ibcmp_utf8((const char*) folded, 0, foldlen, 1,
5110 l, &e, 0, do_utf8)) {
5115 nextchr = UCHARAT(locinput);
5118 if ((n=is_LNBREAK(locinput,do_utf8))) {
5120 nextchr = UCHARAT(locinput);
5125 #define CASE_CLASS(nAmE) \
5127 if ((n=is_##nAmE(locinput,do_utf8))) { \
5129 nextchr = UCHARAT(locinput); \
5134 if ((n=is_##nAmE(locinput,do_utf8))) { \
5137 locinput += UTF8SKIP(locinput); \
5138 nextchr = UCHARAT(locinput); \
5143 CASE_CLASS(HORIZWS);
5147 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5148 PTR2UV(scan), OP(scan));
5149 Perl_croak(aTHX_ "regexp memory corruption");
5153 /* switch break jumps here */
5154 scan = next; /* prepare to execute the next op and ... */
5155 continue; /* ... jump back to the top, reusing st */
5159 /* push a state that backtracks on success */
5160 st->u.yes.prev_yes_state = yes_state;
5164 /* push a new regex state, then continue at scan */
5166 regmatch_state *newst;
5169 regmatch_state *cur = st;
5170 regmatch_state *curyes = yes_state;
5172 regmatch_slab *slab = PL_regmatch_slab;
5173 for (;curd > -1;cur--,curd--) {
5174 if (cur < SLAB_FIRST(slab)) {
5176 cur = SLAB_LAST(slab);
5178 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5179 REPORT_CODE_OFF + 2 + depth * 2,"",
5180 curd, PL_reg_name[cur->resume_state],
5181 (curyes == cur) ? "yes" : ""
5184 curyes = cur->u.yes.prev_yes_state;
5187 DEBUG_STATE_pp("push")
5190 st->locinput = locinput;
5192 if (newst > SLAB_LAST(PL_regmatch_slab))
5193 newst = S_push_slab(aTHX);
5194 PL_regmatch_state = newst;
5196 locinput = PL_reginput;
5197 nextchr = UCHARAT(locinput);
5205 * We get here only if there's trouble -- normally "case END" is
5206 * the terminating point.
5208 Perl_croak(aTHX_ "corrupted regexp pointers");
5214 /* we have successfully completed a subexpression, but we must now
5215 * pop to the state marked by yes_state and continue from there */
5216 assert(st != yes_state);
5218 while (st != yes_state) {
5220 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5221 PL_regmatch_slab = PL_regmatch_slab->prev;
5222 st = SLAB_LAST(PL_regmatch_slab);
5226 DEBUG_STATE_pp("pop (no final)");
5228 DEBUG_STATE_pp("pop (yes)");
5234 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5235 || yes_state > SLAB_LAST(PL_regmatch_slab))
5237 /* not in this slab, pop slab */
5238 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5239 PL_regmatch_slab = PL_regmatch_slab->prev;
5240 st = SLAB_LAST(PL_regmatch_slab);
5242 depth -= (st - yes_state);
5245 yes_state = st->u.yes.prev_yes_state;
5246 PL_regmatch_state = st;
5249 locinput= st->locinput;
5250 nextchr = UCHARAT(locinput);
5252 state_num = st->resume_state + no_final;
5253 goto reenter_switch;
5256 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
5257 PL_colors[4], PL_colors[5]));
5259 if (PL_reg_eval_set) {
5260 /* each successfully executed (?{...}) block does the equivalent of
5261 * local $^R = do {...}
5262 * When popping the save stack, all these locals would be undone;
5263 * bypass this by setting the outermost saved $^R to the latest
5265 if (oreplsv != GvSV(PL_replgv))
5266 sv_setsv(oreplsv, GvSV(PL_replgv));
5273 PerlIO_printf(Perl_debug_log,
5274 "%*s %sfailed...%s\n",
5275 REPORT_CODE_OFF+depth*2, "",
5276 PL_colors[4], PL_colors[5])
5288 /* there's a previous state to backtrack to */
5290 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5291 PL_regmatch_slab = PL_regmatch_slab->prev;
5292 st = SLAB_LAST(PL_regmatch_slab);
5294 PL_regmatch_state = st;
5295 locinput= st->locinput;
5296 nextchr = UCHARAT(locinput);
5298 DEBUG_STATE_pp("pop");
5300 if (yes_state == st)
5301 yes_state = st->u.yes.prev_yes_state;
5303 state_num = st->resume_state + 1; /* failure = success + 1 */
5304 goto reenter_switch;
5309 if (rex->intflags & PREGf_VERBARG_SEEN) {
5310 SV *sv_err = get_sv("REGERROR", 1);
5311 SV *sv_mrk = get_sv("REGMARK", 1);
5313 sv_commit = &PL_sv_no;
5315 sv_yes_mark = &PL_sv_yes;
5318 sv_commit = &PL_sv_yes;
5319 sv_yes_mark = &PL_sv_no;
5321 sv_setsv(sv_err, sv_commit);
5322 sv_setsv(sv_mrk, sv_yes_mark);
5325 /* clean up; in particular, free all slabs above current one */
5326 LEAVE_SCOPE(oldsave);
5332 - regrepeat - repeatedly match something simple, report how many
5335 * [This routine now assumes that it will only match on things of length 1.
5336 * That was true before, but now we assume scan - reginput is the count,
5337 * rather than incrementing count on every character. [Er, except utf8.]]
5340 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
5343 register char *scan;
5345 register char *loceol = PL_regeol;
5346 register I32 hardcount = 0;
5347 register bool do_utf8 = PL_reg_match_utf8;
5349 PERL_UNUSED_ARG(depth);
5352 PERL_ARGS_ASSERT_REGREPEAT;
5355 if (max == REG_INFTY)
5357 else if (max < loceol - scan)
5358 loceol = scan + max;
5363 while (scan < loceol && hardcount < max && *scan != '\n') {
5364 scan += UTF8SKIP(scan);
5368 while (scan < loceol && *scan != '\n')
5375 while (scan < loceol && hardcount < max) {
5376 scan += UTF8SKIP(scan);
5386 case EXACT: /* length of string is 1 */
5388 while (scan < loceol && UCHARAT(scan) == c)
5391 case EXACTF: /* length of string is 1 */
5393 while (scan < loceol &&
5394 (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold[c]))
5397 case EXACTFL: /* length of string is 1 */
5398 PL_reg_flags |= RF_tainted;
5400 while (scan < loceol &&
5401 (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold_locale[c]))
5407 while (hardcount < max && scan < loceol &&
5408 reginclass(prog, p, (U8*)scan, 0, do_utf8)) {
5409 scan += UTF8SKIP(scan);
5413 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
5420 LOAD_UTF8_CHARCLASS_ALNUM();
5421 while (hardcount < max && scan < loceol &&
5422 swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
5423 scan += UTF8SKIP(scan);
5427 while (scan < loceol && isALNUM(*scan))
5432 PL_reg_flags |= RF_tainted;
5435 while (hardcount < max && scan < loceol &&
5436 isALNUM_LC_utf8((U8*)scan)) {
5437 scan += UTF8SKIP(scan);
5441 while (scan < loceol && isALNUM_LC(*scan))
5448 LOAD_UTF8_CHARCLASS_ALNUM();
5449 while (hardcount < max && scan < loceol &&
5450 !swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
5451 scan += UTF8SKIP(scan);
5455 while (scan < loceol && !isALNUM(*scan))
5460 PL_reg_flags |= RF_tainted;
5463 while (hardcount < max && scan < loceol &&
5464 !isALNUM_LC_utf8((U8*)scan)) {
5465 scan += UTF8SKIP(scan);
5469 while (scan < loceol && !isALNUM_LC(*scan))
5476 LOAD_UTF8_CHARCLASS_SPACE();
5477 while (hardcount < max && scan < loceol &&
5479 swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
5480 scan += UTF8SKIP(scan);
5484 while (scan < loceol && isSPACE(*scan))
5489 PL_reg_flags |= RF_tainted;
5492 while (hardcount < max && scan < loceol &&
5493 (*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
5494 scan += UTF8SKIP(scan);
5498 while (scan < loceol && isSPACE_LC(*scan))
5505 LOAD_UTF8_CHARCLASS_SPACE();
5506 while (hardcount < max && scan < loceol &&
5508 swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
5509 scan += UTF8SKIP(scan);
5513 while (scan < loceol && !isSPACE(*scan))
5518 PL_reg_flags |= RF_tainted;
5521 while (hardcount < max && scan < loceol &&
5522 !(*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
5523 scan += UTF8SKIP(scan);
5527 while (scan < loceol && !isSPACE_LC(*scan))
5534 LOAD_UTF8_CHARCLASS_DIGIT();
5535 while (hardcount < max && scan < loceol &&
5536 swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
5537 scan += UTF8SKIP(scan);
5541 while (scan < loceol && isDIGIT(*scan))
5548 LOAD_UTF8_CHARCLASS_DIGIT();
5549 while (hardcount < max && scan < loceol &&
5550 !swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
5551 scan += UTF8SKIP(scan);
5555 while (scan < loceol && !isDIGIT(*scan))
5561 while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
5567 LNBREAK can match two latin chars, which is ok,
5568 because we have a null terminated string, but we
5569 have to use hardcount in this situation
5571 while (scan < loceol && (c=is_LNBREAK_latin1(scan))) {
5580 while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
5585 while (scan < loceol && is_HORIZWS_latin1(scan))
5592 while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
5593 scan += UTF8SKIP(scan);
5597 while (scan < loceol && !is_HORIZWS_latin1(scan))
5605 while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
5610 while (scan < loceol && is_VERTWS_latin1(scan))
5618 while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
5619 scan += UTF8SKIP(scan);
5623 while (scan < loceol && !is_VERTWS_latin1(scan))
5629 default: /* Called on something of 0 width. */
5630 break; /* So match right here or not at all. */
5636 c = scan - PL_reginput;
5640 GET_RE_DEBUG_FLAGS_DECL;
5642 SV * const prop = sv_newmortal();
5643 regprop(prog, prop, p);
5644 PerlIO_printf(Perl_debug_log,
5645 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
5646 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
5654 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
5656 - regclass_swash - prepare the utf8 swash
5660 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
5666 RXi_GET_DECL(prog,progi);
5667 const struct reg_data * const data = prog ? progi->data : NULL;
5669 PERL_ARGS_ASSERT_REGCLASS_SWASH;
5671 if (data && data->count) {
5672 const U32 n = ARG(node);
5674 if (data->what[n] == 's') {
5675 SV * const rv = MUTABLE_SV(data->data[n]);
5676 AV * const av = MUTABLE_AV(SvRV(rv));
5677 SV **const ary = AvARRAY(av);
5680 /* See the end of regcomp.c:S_regclass() for
5681 * documentation of these array elements. */
5684 a = SvROK(ary[1]) ? &ary[1] : NULL;
5685 b = SvTYPE(ary[2]) == SVt_PVAV ? &ary[2] : NULL;
5689 else if (si && doinit) {
5690 sw = swash_init("utf8", "", si, 1, 0);
5691 (void)av_store(av, 1, sw);
5708 - reginclass - determine if a character falls into a character class
5710 The n is the ANYOF regnode, the p is the target string, lenp
5711 is pointer to the maximum length of how far to go in the p
5712 (if the lenp is zero, UTF8SKIP(p) is used),
5713 do_utf8 tells whether the target string is in UTF-8.
5718 S_reginclass(pTHX_ const regexp *prog, register const regnode *n, register const U8* p, STRLEN* lenp, register bool do_utf8)
5721 const char flags = ANYOF_FLAGS(n);
5727 PERL_ARGS_ASSERT_REGINCLASS;
5729 if (do_utf8 && !UTF8_IS_INVARIANT(c)) {
5730 c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &len,
5731 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV) | UTF8_CHECK_ONLY);
5732 /* see [perl #37836] for UTF8_ALLOW_ANYUV */
5733 if (len == (STRLEN)-1)
5734 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
5737 plen = lenp ? *lenp : UNISKIP(NATIVE_TO_UNI(c));
5738 if (do_utf8 || (flags & ANYOF_UNICODE)) {
5741 if (do_utf8 && !ANYOF_RUNTIME(n)) {
5742 if (len != (STRLEN)-1 && c < 256 && ANYOF_BITMAP_TEST(n, c))
5745 if (!match && do_utf8 && (flags & ANYOF_UNICODE_ALL) && c >= 256)
5749 SV * const sw = regclass_swash(prog, n, TRUE, 0, (SV**)&av);
5757 utf8_p = bytes_to_utf8(p, &len);
5759 if (swash_fetch(sw, utf8_p, 1))
5761 else if (flags & ANYOF_FOLD) {
5762 if (!match && lenp && av) {
5764 for (i = 0; i <= av_len(av); i++) {
5765 SV* const sv = *av_fetch(av, i, FALSE);
5767 const char * const s = SvPV_const(sv, len);
5768 if (len <= plen && memEQ(s, (char*)utf8_p, len)) {
5776 U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5779 to_utf8_fold(utf8_p, tmpbuf, &tmplen);
5780 if (swash_fetch(sw, tmpbuf, 1))
5785 /* If we allocated a string above, free it */
5786 if (! do_utf8) Safefree(utf8_p);
5789 if (match && lenp && *lenp == 0)
5790 *lenp = UNISKIP(NATIVE_TO_UNI(c));
5792 if (!match && c < 256) {
5793 if (ANYOF_BITMAP_TEST(n, c))
5795 else if (flags & ANYOF_FOLD) {
5798 if (flags & ANYOF_LOCALE) {
5799 PL_reg_flags |= RF_tainted;
5800 f = PL_fold_locale[c];
5804 if (f != c && ANYOF_BITMAP_TEST(n, f))
5808 if (!match && (flags & ANYOF_CLASS)) {
5809 PL_reg_flags |= RF_tainted;
5811 (ANYOF_CLASS_TEST(n, ANYOF_ALNUM) && isALNUM_LC(c)) ||
5812 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM) && !isALNUM_LC(c)) ||
5813 (ANYOF_CLASS_TEST(n, ANYOF_SPACE) && isSPACE_LC(c)) ||
5814 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE) && !isSPACE_LC(c)) ||
5815 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT) && isDIGIT_LC(c)) ||
5816 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT) && !isDIGIT_LC(c)) ||
5817 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC) && isALNUMC_LC(c)) ||
5818 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
5819 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA) && isALPHA_LC(c)) ||
5820 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA) && !isALPHA_LC(c)) ||
5821 (ANYOF_CLASS_TEST(n, ANYOF_ASCII) && isASCII(c)) ||
5822 (ANYOF_CLASS_TEST(n, ANYOF_NASCII) && !isASCII(c)) ||
5823 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL) && isCNTRL_LC(c)) ||
5824 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL) && !isCNTRL_LC(c)) ||
5825 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH) && isGRAPH_LC(c)) ||
5826 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH) && !isGRAPH_LC(c)) ||
5827 (ANYOF_CLASS_TEST(n, ANYOF_LOWER) && isLOWER_LC(c)) ||
5828 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER) && !isLOWER_LC(c)) ||
5829 (ANYOF_CLASS_TEST(n, ANYOF_PRINT) && isPRINT_LC(c)) ||
5830 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT) && !isPRINT_LC(c)) ||
5831 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT) && isPUNCT_LC(c)) ||
5832 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT) && !isPUNCT_LC(c)) ||
5833 (ANYOF_CLASS_TEST(n, ANYOF_UPPER) && isUPPER_LC(c)) ||
5834 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER) && !isUPPER_LC(c)) ||
5835 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT) && isXDIGIT(c)) ||
5836 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c)) ||
5837 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC) && isPSXSPC(c)) ||
5838 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c)) ||
5839 (ANYOF_CLASS_TEST(n, ANYOF_BLANK) && isBLANK(c)) ||
5840 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK) && !isBLANK(c))
5841 ) /* How's that for a conditional? */
5848 return (flags & ANYOF_INVERT) ? !match : match;
5852 S_reghop3(U8 *s, I32 off, const U8* lim)
5856 PERL_ARGS_ASSERT_REGHOP3;
5859 while (off-- && s < lim) {
5860 /* XXX could check well-formedness here */
5865 while (off++ && s > lim) {
5867 if (UTF8_IS_CONTINUED(*s)) {
5868 while (s > lim && UTF8_IS_CONTINUATION(*s))
5871 /* XXX could check well-formedness here */
5878 /* there are a bunch of places where we use two reghop3's that should
5879 be replaced with this routine. but since thats not done yet
5880 we ifdef it out - dmq
5883 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
5887 PERL_ARGS_ASSERT_REGHOP4;
5890 while (off-- && s < rlim) {
5891 /* XXX could check well-formedness here */
5896 while (off++ && s > llim) {
5898 if (UTF8_IS_CONTINUED(*s)) {
5899 while (s > llim && UTF8_IS_CONTINUATION(*s))
5902 /* XXX could check well-formedness here */
5910 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
5914 PERL_ARGS_ASSERT_REGHOPMAYBE3;
5917 while (off-- && s < lim) {
5918 /* XXX could check well-formedness here */
5925 while (off++ && s > lim) {
5927 if (UTF8_IS_CONTINUED(*s)) {
5928 while (s > lim && UTF8_IS_CONTINUATION(*s))
5931 /* XXX could check well-formedness here */
5940 restore_pos(pTHX_ void *arg)
5943 regexp * const rex = (regexp *)arg;
5944 if (PL_reg_eval_set) {
5945 if (PL_reg_oldsaved) {
5946 rex->subbeg = PL_reg_oldsaved;
5947 rex->sublen = PL_reg_oldsavedlen;
5948 #ifdef PERL_OLD_COPY_ON_WRITE
5949 rex->saved_copy = PL_nrs;
5951 RXp_MATCH_COPIED_on(rex);
5953 PL_reg_magic->mg_len = PL_reg_oldpos;
5954 PL_reg_eval_set = 0;
5955 PL_curpm = PL_reg_oldcurpm;
5960 S_to_utf8_substr(pTHX_ register regexp *prog)
5964 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
5967 if (prog->substrs->data[i].substr
5968 && !prog->substrs->data[i].utf8_substr) {
5969 SV* const sv = newSVsv(prog->substrs->data[i].substr);
5970 prog->substrs->data[i].utf8_substr = sv;
5971 sv_utf8_upgrade(sv);
5972 if (SvVALID(prog->substrs->data[i].substr)) {
5973 const U8 flags = BmFLAGS(prog->substrs->data[i].substr);
5974 if (flags & FBMcf_TAIL) {
5975 /* Trim the trailing \n that fbm_compile added last
5977 SvCUR_set(sv, SvCUR(sv) - 1);
5978 /* Whilst this makes the SV technically "invalid" (as its
5979 buffer is no longer followed by "\0") when fbm_compile()
5980 adds the "\n" back, a "\0" is restored. */
5982 fbm_compile(sv, flags);
5984 if (prog->substrs->data[i].substr == prog->check_substr)
5985 prog->check_utf8 = sv;
5991 S_to_byte_substr(pTHX_ register regexp *prog)
5996 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
5999 if (prog->substrs->data[i].utf8_substr
6000 && !prog->substrs->data[i].substr) {
6001 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
6002 if (sv_utf8_downgrade(sv, TRUE)) {
6003 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
6005 = BmFLAGS(prog->substrs->data[i].utf8_substr);
6006 if (flags & FBMcf_TAIL) {
6007 /* Trim the trailing \n that fbm_compile added last
6009 SvCUR_set(sv, SvCUR(sv) - 1);
6011 fbm_compile(sv, flags);
6017 prog->substrs->data[i].substr = sv;
6018 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
6019 prog->check_substr = sv;
6026 * c-indentation-style: bsd
6028 * indent-tabs-mode: t
6031 * ex: set ts=8 sts=4 sw=4 noet: