This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regen/mk_invlists.pl: Add tables for \b{wb}
[perl5.git] / regexec.c
CommitLineData
a0d0e21e
LW
1/* regexec.c
2 */
3
4/*
4ac71550
TC
5 * One Ring to rule them all, One Ring to find them
6 &
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"]
a0d0e21e
LW
10 */
11
61296642
DM
12/* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
166f8a29 14 * a regular expression.
e4a054ea
DM
15 *
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.
166f8a29
DM
20 */
21
a687059c
LW
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!
24 */
25
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.
29 */
30
e50aee73
AD
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.
34*/
35
b9d5759e 36#ifdef PERL_EXT_RE_BUILD
54df2634 37#include "re_top.h"
9041c2e3 38#endif
56953603 39
64935bc6
KW
40#define B_ON_NON_UTF8_LOCALE_IS_WRONG \
41 "Use of \\b{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
42
a687059c 43/*
e50aee73 44 * pregcomp and pregexec -- regsub and regerror are not used in perl
a687059c
LW
45 *
46 * Copyright (c) 1986 by University of Toronto.
47 * Written by Henry Spencer. Not derived from licensed software.
48 *
49 * Permission is granted to anyone to use this software for any
50 * purpose on any computer system, and to redistribute it freely,
51 * subject to the following restrictions:
52 *
53 * 1. The author is not responsible for the consequences of use of
54 * this software, no matter how awful, even if they arise
55 * from defects in it.
56 *
57 * 2. The origin of this software must not be misrepresented, either
58 * by explicit claim or by omission.
59 *
60 * 3. Altered versions must be plainly marked as such, and must not
61 * be misrepresented as being the original software.
62 *
63 **** Alterations to Henry's code are...
64 ****
4bb101f2 65 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
1129b882
NC
66 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
67 **** by Larry Wall and others
a687059c 68 ****
9ef589d8
LW
69 **** You may distribute under the terms of either the GNU General Public
70 **** License or the Artistic License, as specified in the README file.
a687059c
LW
71 *
72 * Beware that some of this code is subtly aware of the way operator
73 * precedence is structured in regular expressions. Serious changes in
74 * regular-expression syntax might require a total rethink.
75 */
76#include "EXTERN.h"
864dbfa3 77#define PERL_IN_REGEXEC_C
a687059c 78#include "perl.h"
0f5d15d6 79
54df2634
NC
80#ifdef PERL_IN_XSUB_RE
81# include "re_comp.h"
82#else
83# include "regcomp.h"
84#endif
a687059c 85
81e983c1 86#include "inline_invlist.c"
1b0f46bf 87#include "unicode_constants.h"
81e983c1 88
e1cf74e3
CB
89#ifdef DEBUGGING
90/* At least one required character in the target string is expressible only in
91 * UTF-8. */
92static const char* const non_utf8_target_but_utf8_required
93 = "Can't match, because target string needs to be in UTF-8\n";
94#endif
95
96#define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
97 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
98 goto target; \
99} STMT_END
100
c74f6de9
KW
101#define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
102
a687059c
LW
103#ifndef STATIC
104#define STATIC static
105#endif
106
2d66f61e 107/* Valid only for non-utf8 strings: avoids the reginclass
7e2509c1
KW
108 * call if there are no complications: i.e., if everything matchable is
109 * straight forward in the bitmap */
3db24e1e 110#define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
af364d03 111 : ANYOF_BITMAP_TEST(p,*(c)))
7d3e948e 112
c277df42
IZ
113/*
114 * Forwards.
115 */
116
f2ed9b32 117#define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
ba44c216 118#define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
a0ed51b3 119
3dab1dad 120#define HOPc(pos,off) \
ba44c216 121 (char *)(reginfo->is_utf8_target \
220db18a 122 ? reghop3((U8*)pos, off, \
9d9163fb 123 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
3dab1dad 124 : (U8*)(pos + off))
557f47af 125
3dab1dad 126#define HOPBACKc(pos, off) \
ba44c216 127 (char*)(reginfo->is_utf8_target \
9d9163fb
DM
128 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
129 : (pos - off >= reginfo->strbeg) \
8e11feef 130 ? (U8*)pos - off \
3dab1dad 131 : NULL)
efb30f32 132
ba44c216 133#define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
1aa99e6b 134#define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
1aa99e6b 135
557f47af
DM
136/* lim must be +ve. Returns NULL on overshoot */
137#define HOPMAYBE3(pos,off,lim) \
138 (reginfo->is_utf8_target \
139 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
140 : ((U8*)pos + off <= lim) \
141 ? (U8*)pos + off \
142 : NULL)
143
8e9f2289
DM
144/* like HOP3, but limits the result to <= lim even for the non-utf8 case.
145 * off must be >=0; args should be vars rather than expressions */
146#define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
147 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
148 : (U8*)((pos + off) > lim ? lim : (pos + off)))
149
2974eaec
DM
150#define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
151 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
152 : (U8*)(pos + off))
153#define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
7016d6eb
DM
154
155#define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
156#define NEXTCHR_IS_EOS (nextchr < 0)
157
158#define SET_nextchr \
220db18a 159 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
7016d6eb
DM
160
161#define SET_locinput(p) \
162 locinput = (p); \
163 SET_nextchr
164
165
2a16ac92 166#define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
c7304fe2
KW
167 if (!swash_ptr) { \
168 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
c7304fe2 169 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
2a16ac92 170 1, 0, invlist, &flags); \
c7304fe2
KW
171 assert(swash_ptr); \
172 } \
173 } STMT_END
174
175/* If in debug mode, we test that a known character properly matches */
176#ifdef DEBUGGING
177# define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
178 property_name, \
2a16ac92 179 invlist, \
c7304fe2 180 utf8_char_in_property) \
2a16ac92 181 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
c7304fe2
KW
182 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
183#else
184# define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
185 property_name, \
2a16ac92 186 invlist, \
c7304fe2 187 utf8_char_in_property) \
2a16ac92 188 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
c7304fe2 189#endif
d1eb3177 190
c7304fe2
KW
191#define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
192 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
2a16ac92
KW
193 "", \
194 PL_XPosix_ptrs[_CC_WORDCHAR], \
df38da56 195 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
c7304fe2 196
c7304fe2 197#define PLACEHOLDER /* Something for the preprocessor to grab onto */
3dab1dad
YO
198/* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
199
5f80c4cf 200/* for use after a quantifier and before an EXACT-like node -- japhy */
c35dcbe2
YO
201/* it would be nice to rework regcomp.sym to generate this stuff. sigh
202 *
203 * NOTE that *nothing* that affects backtracking should be in here, specifically
204 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
205 * node that is in between two EXACT like nodes when ascertaining what the required
206 * "follow" character is. This should probably be moved to regex compile time
207 * although it may be done at run time beause of the REF possibility - more
208 * investigation required. -- demerphq
209*/
baa60164
KW
210#define JUMPABLE(rn) ( \
211 OP(rn) == OPEN || \
3e901dc0 212 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
baa60164
KW
213 OP(rn) == EVAL || \
214 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
215 OP(rn) == PLUS || OP(rn) == MINMOD || \
216 OP(rn) == KEEPS || \
217 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
e2d8ce26 218)
ee9b8eae 219#define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
e2d8ce26 220
ee9b8eae
YO
221#define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
222
223#if 0
224/* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
a4525e78 225 we don't need this definition. XXX These are now out-of-sync*/
ee9b8eae 226#define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
098b07d5 227#define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFA || OP(rn)==EXACTFA_NO_TRIE || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
ee9b8eae
YO
228#define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
229
230#else
231/* ... so we use this as its faster. */
a4525e78
KW
232#define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
233#define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
ee9b8eae
YO
234#define IS_TEXTF(rn) ( OP(rn)==EXACTF )
235#define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
236
237#endif
e2d8ce26 238
a84d97b6
HS
239/*
240 Search for mandatory following text node; for lookahead, the text must
241 follow but for lookbehind (rn->flags != 0) we skip to the next step.
242*/
baa60164 243#define FIND_NEXT_IMPT(rn) STMT_START { \
3dab1dad
YO
244 while (JUMPABLE(rn)) { \
245 const OPCODE type = OP(rn); \
246 if (type == SUSPEND || PL_regkind[type] == CURLY) \
e2d8ce26 247 rn = NEXTOPER(NEXTOPER(rn)); \
3dab1dad 248 else if (type == PLUS) \
cca55fe3 249 rn = NEXTOPER(rn); \
3dab1dad 250 else if (type == IFMATCH) \
a84d97b6 251 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
e2d8ce26 252 else rn += NEXT_OFF(rn); \
3dab1dad 253 } \
5f80c4cf 254} STMT_END
74750237 255
006f26b2
DM
256#define SLAB_FIRST(s) (&(s)->states[0])
257#define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
258
a75351a1 259static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
bf2039a9 260static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
bf2039a9 261static regmatch_state * S_push_slab(pTHX);
51371543 262
87c0511b 263#define REGCP_PAREN_ELEMS 3
f067efbf 264#define REGCP_OTHER_ELEMS 3
e0fa7e2b 265#define REGCP_FRAME_ELEMS 1
620d5b66
NC
266/* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
267 * are needed for the regexp context stack bookkeeping. */
268
76e3520e 269STATIC CHECKPOINT
92da3157 270S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
a0d0e21e 271{
a3b680e6 272 const int retval = PL_savestack_ix;
92da3157
DM
273 const int paren_elems_to_push =
274 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
e0fa7e2b
NC
275 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
276 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
87c0511b 277 I32 p;
40a82448 278 GET_RE_DEBUG_FLAGS_DECL;
a0d0e21e 279
b93070ed
DM
280 PERL_ARGS_ASSERT_REGCPPUSH;
281
e49a9654 282 if (paren_elems_to_push < 0)
e8a85d26
JH
283 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
284 (int)paren_elems_to_push, (int)maxopenparen,
285 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
e49a9654 286
e0fa7e2b
NC
287 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
288 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
5df417d0 289 " out of range (%lu-%ld)",
92da3157
DM
290 total_elems,
291 (unsigned long)maxopenparen,
292 (long)parenfloor);
e0fa7e2b 293
620d5b66 294 SSGROW(total_elems + REGCP_FRAME_ELEMS);
7f69552c 295
495f47a5 296 DEBUG_BUFFERS_r(
92da3157 297 if ((int)maxopenparen > (int)parenfloor)
495f47a5
DM
298 PerlIO_printf(Perl_debug_log,
299 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
300 PTR2UV(rex),
301 PTR2UV(rex->offs)
302 );
303 );
92da3157 304 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
b1ce53c5 305/* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
99a90e59
FC
306 SSPUSHIV(rex->offs[p].end);
307 SSPUSHIV(rex->offs[p].start);
1ca2007e 308 SSPUSHINT(rex->offs[p].start_tmp);
e7707071 309 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
495f47a5
DM
310 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
311 (UV)p,
312 (IV)rex->offs[p].start,
313 (IV)rex->offs[p].start_tmp,
314 (IV)rex->offs[p].end
40a82448 315 ));
a0d0e21e 316 }
b1ce53c5 317/* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
92da3157 318 SSPUSHINT(maxopenparen);
b93070ed
DM
319 SSPUSHINT(rex->lastparen);
320 SSPUSHINT(rex->lastcloseparen);
e0fa7e2b 321 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
41123dfd 322
a0d0e21e
LW
323 return retval;
324}
325
c277df42 326/* These are needed since we do not localize EVAL nodes: */
ab3bbdeb
YO
327#define REGCP_SET(cp) \
328 DEBUG_STATE_r( \
ab3bbdeb 329 PerlIO_printf(Perl_debug_log, \
e4f74956 330 " Setting an EVAL scope, savestack=%"IVdf"\n", \
ab3bbdeb
YO
331 (IV)PL_savestack_ix)); \
332 cp = PL_savestack_ix
c3464db5 333
ab3bbdeb 334#define REGCP_UNWIND(cp) \
e4f74956 335 DEBUG_STATE_r( \
ab3bbdeb 336 if (cp != PL_savestack_ix) \
e4f74956
YO
337 PerlIO_printf(Perl_debug_log, \
338 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
ab3bbdeb
YO
339 (IV)(cp), (IV)PL_savestack_ix)); \
340 regcpblow(cp)
c277df42 341
a8d1f4b4
DM
342#define UNWIND_PAREN(lp, lcp) \
343 for (n = rex->lastparen; n > lp; n--) \
344 rex->offs[n].end = -1; \
345 rex->lastparen = n; \
346 rex->lastcloseparen = lcp;
347
348
f067efbf 349STATIC void
92da3157 350S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
a0d0e21e 351{
e0fa7e2b 352 UV i;
87c0511b 353 U32 paren;
a3621e74
YO
354 GET_RE_DEBUG_FLAGS_DECL;
355
7918f24d
NC
356 PERL_ARGS_ASSERT_REGCPPOP;
357
b1ce53c5 358 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
c6bf6a65 359 i = SSPOPUV;
e0fa7e2b
NC
360 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
361 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
b93070ed
DM
362 rex->lastcloseparen = SSPOPINT;
363 rex->lastparen = SSPOPINT;
92da3157 364 *maxopenparen_p = SSPOPINT;
b1ce53c5 365
620d5b66 366 i -= REGCP_OTHER_ELEMS;
b1ce53c5 367 /* Now restore the parentheses context. */
495f47a5
DM
368 DEBUG_BUFFERS_r(
369 if (i || rex->lastparen + 1 <= rex->nparens)
370 PerlIO_printf(Perl_debug_log,
371 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
372 PTR2UV(rex),
373 PTR2UV(rex->offs)
374 );
375 );
92da3157 376 paren = *maxopenparen_p;
620d5b66 377 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
ea3daa5d 378 SSize_t tmps;
1ca2007e 379 rex->offs[paren].start_tmp = SSPOPINT;
99a90e59
FC
380 rex->offs[paren].start = SSPOPIV;
381 tmps = SSPOPIV;
b93070ed
DM
382 if (paren <= rex->lastparen)
383 rex->offs[paren].end = tmps;
495f47a5
DM
384 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
385 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
386 (UV)paren,
387 (IV)rex->offs[paren].start,
388 (IV)rex->offs[paren].start_tmp,
389 (IV)rex->offs[paren].end,
390 (paren > rex->lastparen ? "(skipped)" : ""));
c277df42 391 );
87c0511b 392 paren--;
a0d0e21e 393 }
daf18116 394#if 1
dafc8851
JH
395 /* It would seem that the similar code in regtry()
396 * already takes care of this, and in fact it is in
397 * a better location to since this code can #if 0-ed out
398 * but the code in regtry() is needed or otherwise tests
399 * requiring null fields (pat.t#187 and split.t#{13,14}
daf18116
JH
400 * (as of patchlevel 7877) will fail. Then again,
401 * this code seems to be necessary or otherwise
225593e1
DM
402 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
403 * --jhi updated by dapm */
b93070ed 404 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
92da3157 405 if (i > *maxopenparen_p)
b93070ed
DM
406 rex->offs[i].start = -1;
407 rex->offs[i].end = -1;
495f47a5
DM
408 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
409 " \\%"UVuf": %s ..-1 undeffing\n",
410 (UV)i,
92da3157 411 (i > *maxopenparen_p) ? "-1" : " "
495f47a5 412 ));
a0d0e21e 413 }
dafc8851 414#endif
a0d0e21e
LW
415}
416
74088413
DM
417/* restore the parens and associated vars at savestack position ix,
418 * but without popping the stack */
419
420STATIC void
92da3157 421S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
74088413
DM
422{
423 I32 tmpix = PL_savestack_ix;
424 PL_savestack_ix = ix;
92da3157 425 regcppop(rex, maxopenparen_p);
74088413
DM
426 PL_savestack_ix = tmpix;
427}
428
02db2b7b 429#define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
a0d0e21e 430
31c7f561
KW
431STATIC bool
432S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
433{
434 /* Returns a boolean as to whether or not 'character' is a member of the
435 * Posix character class given by 'classnum' that should be equivalent to a
436 * value in the typedef '_char_class_number'.
437 *
438 * Ideally this could be replaced by a just an array of function pointers
439 * to the C library functions that implement the macros this calls.
440 * However, to compile, the precise function signatures are required, and
441 * these may vary from platform to to platform. To avoid having to figure
442 * out what those all are on each platform, I (khw) am using this method,
7aee35ff
KW
443 * which adds an extra layer of function call overhead (unless the C
444 * optimizer strips it away). But we don't particularly care about
445 * performance with locales anyway. */
31c7f561
KW
446
447 switch ((_char_class_number) classnum) {
15861f94 448 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
31c7f561 449 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
e8d596e0
KW
450 case _CC_ENUM_ASCII: return isASCII_LC(character);
451 case _CC_ENUM_BLANK: return isBLANK_LC(character);
b0d691b2
KW
452 case _CC_ENUM_CASED: return isLOWER_LC(character)
453 || isUPPER_LC(character);
e8d596e0 454 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
31c7f561
KW
455 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
456 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
457 case _CC_ENUM_LOWER: return isLOWER_LC(character);
458 case _CC_ENUM_PRINT: return isPRINT_LC(character);
e8d596e0 459 case _CC_ENUM_PSXSPC: return isPSXSPC_LC(character);
31c7f561 460 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
e8d596e0 461 case _CC_ENUM_SPACE: return isSPACE_LC(character);
31c7f561
KW
462 case _CC_ENUM_UPPER: return isUPPER_LC(character);
463 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
31c7f561 464 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
31c7f561
KW
465 default: /* VERTSPACE should never occur in locales */
466 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
467 }
468
e5964223 469 NOT_REACHED; /* NOTREACHED */
31c7f561
KW
470 return FALSE;
471}
472
3018b823
KW
473STATIC bool
474S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
475{
476 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
477 * 'character' is a member of the Posix character class given by 'classnum'
478 * that should be equivalent to a value in the typedef
479 * '_char_class_number'.
480 *
481 * This just calls isFOO_lc on the code point for the character if it is in
2f306ab9 482 * the range 0-255. Outside that range, all characters use Unicode
3018b823
KW
483 * rules, ignoring any locale. So use the Unicode function if this class
484 * requires a swash, and use the Unicode macro otherwise. */
485
486 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
487
488 if (UTF8_IS_INVARIANT(*character)) {
489 return isFOO_lc(classnum, *character);
490 }
491 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
492 return isFOO_lc(classnum,
94bb8c36 493 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
3018b823
KW
494 }
495
613abc6d
KW
496 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
497
3018b823
KW
498 if (classnum < _FIRST_NON_SWASH_CC) {
499
500 /* Initialize the swash unless done already */
501 if (! PL_utf8_swash_ptrs[classnum]) {
502 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2a16ac92
KW
503 PL_utf8_swash_ptrs[classnum] =
504 _core_swash_init("utf8",
505 "",
506 &PL_sv_undef, 1, 0,
507 PL_XPosix_ptrs[classnum], &flags);
3018b823
KW
508 }
509
92a2046b
KW
510 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
511 character,
512 TRUE /* is UTF */ ));
3018b823
KW
513 }
514
515 switch ((_char_class_number) classnum) {
516 case _CC_ENUM_SPACE:
517 case _CC_ENUM_PSXSPC: return is_XPERLSPACE_high(character);
518
519 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
520 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
521 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
e1ee3960 522 default: break;
3018b823
KW
523 }
524
e1ee3960 525 return FALSE; /* Things like CNTRL are always below 256 */
3018b823
KW
526}
527
a687059c 528/*
e50aee73 529 * pregexec and friends
a687059c
LW
530 */
531
76234dfb 532#ifndef PERL_IN_XSUB_RE
a687059c 533/*
c277df42 534 - pregexec - match a regexp against a string
a687059c 535 */
c277df42 536I32
5aaab254 537Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
ea3daa5d 538 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
8fd1a950
DM
539/* stringarg: the point in the string at which to begin matching */
540/* strend: pointer to null at end of string */
541/* strbeg: real beginning of string */
542/* minend: end of match must be >= minend bytes after stringarg. */
543/* screamer: SV being matched: only used for utf8 flag, pos() etc; string
544 * itself is accessed via the pointers above */
545/* nosave: For optimizations. */
c277df42 546{
7918f24d
NC
547 PERL_ARGS_ASSERT_PREGEXEC;
548
c277df42 549 return
9041c2e3 550 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
c277df42
IZ
551 nosave ? 0 : REXEC_COPY_STR);
552}
76234dfb 553#endif
22e551b9 554
cad2e5aa 555
6eb5f6b9 556
1a4edc3c
DM
557/* re_intuit_start():
558 *
559 * Based on some optimiser hints, try to find the earliest position in the
560 * string where the regex could match.
561 *
562 * rx: the regex to match against
563 * sv: the SV being matched: only used for utf8 flag; the string
564 * itself is accessed via the pointers below. Note that on
565 * something like an overloaded SV, SvPOK(sv) may be false
566 * and the string pointers may point to something unrelated to
567 * the SV itself.
568 * strbeg: real beginning of string
569 * strpos: the point in the string at which to begin matching
570 * strend: pointer to the byte following the last char of the string
571 * flags currently unused; set to 0
572 * data: currently unused; set to NULL
573 *
574 * The basic idea of re_intuit_start() is to use some known information
575 * about the pattern, namely:
576 *
577 * a) the longest known anchored substring (i.e. one that's at a
578 * constant offset from the beginning of the pattern; but not
579 * necessarily at a fixed offset from the beginning of the
580 * string);
581 * b) the longest floating substring (i.e. one that's not at a constant
582 * offset from the beginning of the pattern);
583 * c) Whether the pattern is anchored to the string; either
584 * an absolute anchor: /^../, or anchored to \n: /^.../m,
585 * or anchored to pos(): /\G/;
586 * d) A start class: a real or synthetic character class which
587 * represents which characters are legal at the start of the pattern;
588 *
589 * to either quickly reject the match, or to find the earliest position
590 * within the string at which the pattern might match, thus avoiding
591 * running the full NFA engine at those earlier locations, only to
592 * eventually fail and retry further along.
593 *
594 * Returns NULL if the pattern can't match, or returns the address within
595 * the string which is the earliest place the match could occur.
596 *
597 * The longest of the anchored and floating substrings is called 'check'
598 * and is checked first. The other is called 'other' and is checked
599 * second. The 'other' substring may not be present. For example,
600 *
601 * /(abc|xyz)ABC\d{0,3}DEFG/
602 *
603 * will have
604 *
605 * check substr (float) = "DEFG", offset 6..9 chars
606 * other substr (anchored) = "ABC", offset 3..3 chars
607 * stclass = [ax]
608 *
609 * Be aware that during the course of this function, sometimes 'anchored'
610 * refers to a substring being anchored relative to the start of the
611 * pattern, and sometimes to the pattern itself being anchored relative to
612 * the string. For example:
613 *
614 * /\dabc/: "abc" is anchored to the pattern;
615 * /^\dabc/: "abc" is anchored to the pattern and the string;
616 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
617 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
618 * but the pattern is anchored to the string.
52a21eb3
DM
619 */
620
cad2e5aa 621char *
52a21eb3
DM
622Perl_re_intuit_start(pTHX_
623 REGEXP * const rx,
624 SV *sv,
625 const char * const strbeg,
626 char *strpos,
627 char *strend,
628 const U32 flags,
629 re_scream_pos_data *data)
cad2e5aa 630{
8d919b0a 631 struct regexp *const prog = ReANY(rx);
6b071d16 632 SSize_t start_shift = prog->check_offset_min;
cad2e5aa 633 /* Should be nonnegative! */
ea3daa5d 634 SSize_t end_shift = 0;
0fc004dd
DM
635 /* current lowest pos in string where the regex can start matching */
636 char *rx_origin = strpos;
eb578fdb 637 SV *check;
f2ed9b32 638 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
6480a6c4 639 U8 other_ix = 1 - prog->substrs->check_ix;
6ad5ffb3 640 bool ml_anch = 0;
8f4bf5fc 641 char *other_last = strpos;/* latest pos 'other' substr already checked to */
bd61b366 642 char *check_at = NULL; /* check substr found at this pos */
bbe252da 643 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
f8fc2ecf 644 RXi_GET_DECL(prog,progi);
02d5137b
DM
645 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
646 regmatch_info *const reginfo = &reginfo_buf;
a3621e74
YO
647 GET_RE_DEBUG_FLAGS_DECL;
648
7918f24d 649 PERL_ARGS_ASSERT_RE_INTUIT_START;
c33e64f0
FC
650 PERL_UNUSED_ARG(flags);
651 PERL_UNUSED_ARG(data);
7918f24d 652
1dc475d0
DM
653 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
654 "Intuit: trying to determine minimum start position...\n"));
655
fb9bbddb
DM
656 /* for now, assume that all substr offsets are positive. If at some point
657 * in the future someone wants to do clever things with look-behind and
658 * -ve offsets, they'll need to fix up any code in this function
659 * which uses these offsets. See the thread beginning
660 * <20140113145929.GF27210@iabyn.com>
661 */
662 assert(prog->substrs->data[0].min_offset >= 0);
663 assert(prog->substrs->data[0].max_offset >= 0);
664 assert(prog->substrs->data[1].min_offset >= 0);
665 assert(prog->substrs->data[1].max_offset >= 0);
666 assert(prog->substrs->data[2].min_offset >= 0);
667 assert(prog->substrs->data[2].max_offset >= 0);
668
f7022b5a 669 /* for now, assume that if both present, that the floating substring
83f2232d 670 * doesn't start before the anchored substring.
f7022b5a
DM
671 * If you break this assumption (e.g. doing better optimisations
672 * with lookahead/behind), then you'll need to audit the code in this
673 * function carefully first
674 */
675 assert(
676 ! ( (prog->anchored_utf8 || prog->anchored_substr)
677 && (prog->float_utf8 || prog->float_substr))
678 || (prog->float_min_offset >= prog->anchored_offset));
679
1a4edc3c
DM
680 /* byte rather than char calculation for efficiency. It fails
681 * to quickly reject some cases that can't match, but will reject
682 * them later after doing full char arithmetic */
c344f387 683 if (prog->minlen > strend - strpos) {
a3621e74 684 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 685 " String too short...\n"));
cad2e5aa 686 goto fail;
2c2d71f5 687 }
d8da0584 688
ab4e48c1 689 RX_MATCH_UTF8_set(rx,utf8_target);
6c3fea77 690 reginfo->is_utf8_target = cBOOL(utf8_target);
bf2039a9 691 reginfo->info_aux = NULL;
9d9163fb 692 reginfo->strbeg = strbeg;
220db18a 693 reginfo->strend = strend;
aed7b151 694 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
02d5137b 695 reginfo->intuit = 1;
1cb48e53
DM
696 /* not actually used within intuit, but zero for safety anyway */
697 reginfo->poscache_maxiter = 0;
02d5137b 698
f2ed9b32 699 if (utf8_target) {
33b8afdf
JH
700 if (!prog->check_utf8 && prog->check_substr)
701 to_utf8_substr(prog);
702 check = prog->check_utf8;
703 } else {
7e0d5ad7
KW
704 if (!prog->check_substr && prog->check_utf8) {
705 if (! to_byte_substr(prog)) {
6b54ddc5 706 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
7e0d5ad7
KW
707 }
708 }
33b8afdf
JH
709 check = prog->check_substr;
710 }
274cd312 711
1dc475d0
DM
712 /* dump the various substring data */
713 DEBUG_OPTIMISE_MORE_r({
714 int i;
715 for (i=0; i<=2; i++) {
716 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
717 : prog->substrs->data[i].substr);
718 if (!sv)
719 continue;
720
721 PerlIO_printf(Perl_debug_log,
722 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
723 " useful=%"IVdf" utf8=%d [%s]\n",
724 i,
725 (IV)prog->substrs->data[i].min_offset,
726 (IV)prog->substrs->data[i].max_offset,
727 (IV)prog->substrs->data[i].end_shift,
728 BmUSEFUL(sv),
729 utf8_target ? 1 : 0,
730 SvPEEK(sv));
731 }
732 });
733
8e1490ee 734 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
9fc7410e
DM
735
736 /* ml_anch: check after \n?
737 *
0fa70a06 738 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
9fc7410e
DM
739 * with /.*.../, these flags will have been added by the
740 * compiler:
741 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
742 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
743 */
7d2d37f5
DM
744 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
745 && !(prog->intflags & PREGf_IMPLICIT);
cad2e5aa 746
343c8a29 747 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
c889ccc8
DM
748 /* we are only allowed to match at BOS or \G */
749
57fcbfa7 750 /* trivially reject if there's a BOS anchor and we're not at BOS.
7bb3b9eb
DM
751 *
752 * Note that we don't try to do a similar quick reject for
753 * \G, since generally the caller will have calculated strpos
754 * based on pos() and gofs, so the string is already correctly
755 * anchored by definition; and handling the exceptions would
756 * be too fiddly (e.g. REXEC_IGNOREPOS).
57fcbfa7 757 */
7bb3b9eb 758 if ( strpos != strbeg
d3d47aac 759 && (prog->intflags & PREGf_ANCH_SBOL))
c889ccc8
DM
760 {
761 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 762 " Not at start...\n"));
c889ccc8
DM
763 goto fail;
764 }
765
a5d12a4b
DM
766 /* in the presence of an anchor, the anchored (relative to the
767 * start of the regex) substr must also be anchored relative
66b7ec5c
DM
768 * to strpos. So quickly reject if substr isn't found there.
769 * This works for \G too, because the caller will already have
770 * subtracted gofs from pos, and gofs is the offset from the
771 * \G to the start of the regex. For example, in /.abc\Gdef/,
772 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
773 * caller will have set strpos=pos()-4; we look for the substr
774 * at position pos()-4+1, which lines up with the "a" */
a5d12a4b 775
c889ccc8 776 if (prog->check_offset_min == prog->check_offset_max
d0d44648 777 && !(prog->intflags & PREGf_CANY_SEEN))
c889ccc8
DM
778 {
779 /* Substring at constant offset from beg-of-str... */
d307bf57 780 SSize_t slen = SvCUR(check);
343c8a29 781 char *s = HOP3c(strpos, prog->check_offset_min, strend);
1de06328 782
1dc475d0
DM
783 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
784 " Looking for check substr at fixed offset %"IVdf"...\n",
785 (IV)prog->check_offset_min));
786
7742aa66
DM
787 if (SvTAIL(check)) {
788 /* In this case, the regex is anchored at the end too.
789 * Unless it's a multiline match, the lengths must match
790 * exactly, give or take a \n. NB: slen >= 1 since
791 * the last char of check is \n */
792 if (!multiline
793 && ( strend - s > slen
794 || strend - s < slen - 1
795 || (strend - s == slen && strend[-1] != '\n')))
c889ccc8
DM
796 {
797 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 798 " String too long...\n"));
c889ccc8
DM
799 goto fail_finish;
800 }
801 /* Now should match s[0..slen-2] */
802 slen--;
c889ccc8 803 }
d307bf57
DM
804 if (slen && (*SvPVX_const(check) != *s
805 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
806 {
807 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 808 " String not equal...\n"));
d307bf57
DM
809 goto fail_finish;
810 }
c889ccc8
DM
811
812 check_at = s;
813 goto success_at_start;
cad2e5aa 814 }
cad2e5aa 815 }
cad2e5aa 816 }
0fc004dd 817
c0e0ec46 818 end_shift = prog->check_end_shift;
cad2e5aa 819
19188028 820#ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
0033605d 821 if (end_shift < 0)
1de06328 822 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
220fc49f 823 (IV)end_shift, RX_PRECOMP(prog));
2c2d71f5
JH
824#endif
825
2c2d71f5 826 restart:
1de06328 827
66b7ec5c
DM
828 /* This is the (re)entry point of the main loop in this function.
829 * The goal of this loop is to:
830 * 1) find the "check" substring in the region rx_origin..strend
831 * (adjusted by start_shift / end_shift). If not found, reject
832 * immediately.
833 * 2) If it exists, look for the "other" substr too if defined; for
834 * example, if the check substr maps to the anchored substr, then
835 * check the floating substr, and vice-versa. If not found, go
836 * back to (1) with rx_origin suitably incremented.
837 * 3) If we find an rx_origin position that doesn't contradict
838 * either of the substrings, then check the possible additional
839 * constraints on rx_origin of /^.../m or a known start class.
840 * If these fail, then depending on which constraints fail, jump
841 * back to here, or to various other re-entry points further along
842 * that skip some of the first steps.
843 * 4) If we pass all those tests, update the BmUSEFUL() count on the
844 * substring. If the start position was determined to be at the
845 * beginning of the string - so, not rejected, but not optimised,
846 * since we have to run regmatch from position 0 - decrement the
847 * BmUSEFUL() count. Otherwise increment it.
848 */
849
1a4edc3c
DM
850
851 /* first, look for the 'check' substring */
852
1de06328 853 {
c33e64f0
FC
854 U8* start_point;
855 U8* end_point;
c889ccc8 856
c889ccc8 857 DEBUG_OPTIMISE_MORE_r({
1dc475d0 858 PerlIO_printf(Perl_debug_log,
ae5d4331 859 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
1dc475d0 860 " Start shift: %"IVdf" End shift %"IVdf
4d281893 861 " Real end Shift: %"IVdf"\n",
197641b6 862 (IV)(rx_origin - strpos),
c889ccc8 863 (IV)prog->check_offset_min,
12fbc530
DM
864 (IV)start_shift,
865 (IV)end_shift,
c889ccc8
DM
866 (IV)prog->check_end_shift);
867 });
1de06328 868
0d331aaf 869 if (prog->intflags & PREGf_CANY_SEEN) {
0fc004dd 870 start_point= (U8*)(rx_origin + start_shift);
12fbc530 871 end_point= (U8*)(strend - end_shift);
557f47af
DM
872 if (start_point > end_point)
873 goto fail_finish;
1de06328 874 } else {
557f47af
DM
875 end_point = HOP3(strend, -end_shift, strbeg);
876 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
877 if (!start_point)
878 goto fail_finish;
1de06328 879 }
c889ccc8 880
557f47af 881
e0362b86 882 /* If the regex is absolutely anchored to either the start of the
d3d47aac 883 * string (SBOL) or to pos() (ANCH_GPOS), then
e0362b86
DM
884 * check_offset_max represents an upper bound on the string where
885 * the substr could start. For the ANCH_GPOS case, we assume that
886 * the caller of intuit will have already set strpos to
887 * pos()-gofs, so in this case strpos + offset_max will still be
888 * an upper bound on the substr.
889 */
c19c836a
DM
890 if (!ml_anch
891 && prog->intflags & PREGf_ANCH
e0362b86 892 && prog->check_offset_max != SSize_t_MAX)
c19c836a 893 {
1a08ba3a 894 SSize_t len = SvCUR(check) - !!SvTAIL(check);
e0362b86
DM
895 const char * const anchor =
896 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
897
898 /* do a bytes rather than chars comparison. It's conservative;
899 * so it skips doing the HOP if the result can't possibly end
900 * up earlier than the old value of end_point.
901 */
902 if ((char*)end_point - anchor > prog->check_offset_max) {
903 end_point = HOP3lim((U8*)anchor,
904 prog->check_offset_max,
905 end_point -len)
906 + len;
907 }
d6ef1678
DM
908 }
909
6bda09f9 910 DEBUG_OPTIMISE_MORE_r({
1dc475d0 911 PerlIO_printf(Perl_debug_log, " fbm_instr len=%d str=<%.*s>\n",
1de06328 912 (int)(end_point - start_point),
fc8cd66c 913 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
1de06328
YO
914 start_point);
915 });
916
ae5d4331 917 check_at = fbm_instr( start_point, end_point,
7fba1cd6 918 check, multiline ? FBMrf_MULTILINE : 0);
c889ccc8 919
8fd34720
DM
920 /* Update the count-of-usability, remove useless subpatterns,
921 unshift s. */
922
923 DEBUG_EXECUTE_r({
924 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
925 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
926 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
927 (check_at ? "Found" : "Did not find"),
928 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
929 ? "anchored" : "floating"),
930 quoted,
931 RE_SV_TAIL(check),
932 (check_at ? " at offset " : "...\n") );
933 });
2c2d71f5 934
8fd34720
DM
935 if (!check_at)
936 goto fail_finish;
937 /* Finish the diagnostic message */
938 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(check_at - strpos)) );
2c2d71f5 939
8fd34720
DM
940 /* set rx_origin to the minimum position where the regex could start
941 * matching, given the constraint of the just-matched check substring.
942 * But don't set it lower than previously.
943 */
fdc003fd 944
8fd34720
DM
945 if (check_at - rx_origin > prog->check_offset_max)
946 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
947 }
fdc003fd
DM
948
949
1a4edc3c 950 /* now look for the 'other' substring if defined */
2c2d71f5 951
6480a6c4
DM
952 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
953 : prog->substrs->data[other_ix].substr)
1de06328 954 {
30944b6d 955 /* Take into account the "other" substring. */
6c3343a6
DM
956 char *last, *last1;
957 char *s;
958 SV* must;
959 struct reg_substr_datum *other;
960
961 do_other_substr:
962 other = &prog->substrs->data[other_ix];
963
964 /* if "other" is anchored:
965 * we've previously found a floating substr starting at check_at.
966 * This means that the regex origin must lie somewhere
967 * between min (rx_origin): HOP3(check_at, -check_offset_max)
968 * and max: HOP3(check_at, -check_offset_min)
969 * (except that min will be >= strpos)
970 * So the fixed substr must lie somewhere between
971 * HOP3(min, anchored_offset)
972 * HOP3(max, anchored_offset) + SvCUR(substr)
973 */
974
975 /* if "other" is floating
976 * Calculate last1, the absolute latest point where the
977 * floating substr could start in the string, ignoring any
978 * constraints from the earlier fixed match. It is calculated
979 * as follows:
980 *
981 * strend - prog->minlen (in chars) is the absolute latest
982 * position within the string where the origin of the regex
983 * could appear. The latest start point for the floating
984 * substr is float_min_offset(*) on from the start of the
985 * regex. last1 simply combines thee two offsets.
986 *
987 * (*) You might think the latest start point should be
988 * float_max_offset from the regex origin, and technically
989 * you'd be correct. However, consider
990 * /a\d{2,4}bcd\w/
991 * Here, float min, max are 3,5 and minlen is 7.
992 * This can match either
993 * /a\d\dbcd\w/
994 * /a\d\d\dbcd\w/
995 * /a\d\d\d\dbcd\w/
996 * In the first case, the regex matches minlen chars; in the
997 * second, minlen+1, in the third, minlen+2.
998 * In the first case, the floating offset is 3 (which equals
999 * float_min), in the second, 4, and in the third, 5 (which
1000 * equals float_max). In all cases, the floating string bcd
1001 * can never start more than 4 chars from the end of the
1002 * string, which equals minlen - float_min. As the substring
1003 * starts to match more than float_min from the start of the
1004 * regex, it makes the regex match more than minlen chars,
1005 * and the two cancel each other out. So we can always use
1006 * float_min - minlen, rather than float_max - minlen for the
1007 * latest position in the string.
1008 *
1009 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1010 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1011 */
1012
e7a14a9c 1013 assert(prog->minlen >= other->min_offset);
6c3343a6
DM
1014 last1 = HOP3c(strend,
1015 other->min_offset - prog->minlen, strbeg);
1016
4d006249 1017 if (other_ix) {/* i.e. if (other-is-float) */
6c3343a6
DM
1018 /* last is the latest point where the floating substr could
1019 * start, *given* any constraints from the earlier fixed
1020 * match. This constraint is that the floating string starts
1021 * <= float_max_offset chars from the regex origin (rx_origin).
1022 * If this value is less than last1, use it instead.
eb3831ce 1023 */
6c3343a6
DM
1024 assert(rx_origin <= last1);
1025 last =
1026 /* this condition handles the offset==infinity case, and
1027 * is a short-cut otherwise. Although it's comparing a
1028 * byte offset to a char length, it does so in a safe way,
1029 * since 1 char always occupies 1 or more bytes,
1030 * so if a string range is (last1 - rx_origin) bytes,
1031 * it will be less than or equal to (last1 - rx_origin)
1032 * chars; meaning it errs towards doing the accurate HOP3
1033 * rather than just using last1 as a short-cut */
1034 (last1 - rx_origin) < other->max_offset
1035 ? last1
1036 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1037 }
1038 else {
1039 assert(strpos + start_shift <= check_at);
1040 last = HOP4c(check_at, other->min_offset - start_shift,
1041 strbeg, strend);
1042 }
ead917d0 1043
6c3343a6
DM
1044 s = HOP3c(rx_origin, other->min_offset, strend);
1045 if (s < other_last) /* These positions already checked */
1046 s = other_last;
1047
1048 must = utf8_target ? other->utf8_substr : other->substr;
1049 assert(SvPOK(must));
1050 s = fbm_instr(
1051 (unsigned char*)s,
1052 (unsigned char*)last + SvCUR(must) - (SvTAIL(must)!=0),
1053 must,
1054 multiline ? FBMrf_MULTILINE : 0
1055 );
1056 DEBUG_EXECUTE_r({
1057 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1058 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1059 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1060 s ? "Found" : "Contradicts",
1061 other_ix ? "floating" : "anchored",
1062 quoted, RE_SV_TAIL(must));
1063 });
ead917d0 1064
ead917d0 1065
6c3343a6
DM
1066 if (!s) {
1067 /* last1 is latest possible substr location. If we didn't
1068 * find it before there, we never will */
1069 if (last >= last1) {
1070 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1071 ", giving up...\n"));
1072 goto fail_finish;
ead917d0
DM
1073 }
1074
6c3343a6
DM
1075 /* try to find the check substr again at a later
1076 * position. Maybe next time we'll find the "other" substr
1077 * in range too */
1078 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1079 ", trying %s at offset %ld...\n",
1080 (other_ix ? "floating" : "anchored"),
197641b6 1081 (long)(HOP3c(check_at, 1, strend) - strpos)));
6c3343a6
DM
1082
1083 other_last = HOP3c(last, 1, strend) /* highest failure */;
1084 rx_origin =
4d006249 1085 other_ix /* i.e. if other-is-float */
6c3343a6
DM
1086 ? HOP3c(rx_origin, 1, strend)
1087 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1088 goto restart;
1089 }
1090 else {
1091 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
197641b6 1092 (long)(s - strpos)));
ead917d0 1093
4d006249 1094 if (other_ix) { /* if (other-is-float) */
6c3343a6
DM
1095 /* other_last is set to s, not s+1, since its possible for
1096 * a floating substr to fail first time, then succeed
1097 * second time at the same floating position; e.g.:
1098 * "-AB--AABZ" =~ /\wAB\d*Z/
1099 * The first time round, anchored and float match at
1100 * "-(AB)--AAB(Z)" then fail on the initial \w character
1101 * class. Second time round, they match at "-AB--A(AB)(Z)".
1102 */
1103 other_last = s;
ead917d0
DM
1104 }
1105 else {
6c3343a6
DM
1106 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1107 other_last = HOP3c(s, 1, strend);
ead917d0 1108 }
6c3343a6 1109 }
cad2e5aa 1110 }
acba93e8
DM
1111 else {
1112 DEBUG_OPTIMISE_MORE_r(
1113 PerlIO_printf(Perl_debug_log,
1114 " Check-only match: offset min:%"IVdf" max:%"IVdf
1c1c599d 1115 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
acba93e8
DM
1116 " strend-strpos:%"IVdf"\n",
1117 (IV)prog->check_offset_min,
1118 (IV)prog->check_offset_max,
1c1c599d 1119 (IV)(check_at-strpos),
acba93e8 1120 (IV)(rx_origin-strpos),
1c1c599d 1121 (IV)(rx_origin-check_at),
acba93e8
DM
1122 (IV)(strend-strpos)
1123 )
1124 );
1125 }
2c2d71f5 1126
acba93e8 1127 postprocess_substr_matches:
0991020e 1128
1a4edc3c 1129 /* handle the extra constraint of /^.../m if present */
e3c6feb0 1130
7d2d37f5 1131 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
4620cb61
DM
1132 char *s;
1133
a62659bd
DM
1134 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1135 " looking for /^/m anchor"));
d0880ea7
DM
1136
1137 /* we have failed the constraint of a \n before rx_origin.
2e759faa
DM
1138 * Find the next \n, if any, even if it's beyond the current
1139 * anchored and/or floating substrings. Whether we should be
1140 * scanning ahead for the next \n or the next substr is debatable.
1141 * On the one hand you'd expect rare substrings to appear less
1142 * often than \n's. On the other hand, searching for \n means
1143 * we're effectively flipping been check_substr and "\n" on each
1144 * iteration as the current "rarest" string candidate, which
1145 * means for example that we'll quickly reject the whole string if
1146 * hasn't got a \n, rather than trying every substr position
1147 * first
1148 */
d0880ea7 1149
4620cb61
DM
1150 s = HOP3c(strend, - prog->minlen, strpos);
1151 if (s <= rx_origin ||
1152 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1153 {
d0880ea7
DM
1154 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1155 " Did not find /%s^%s/m...\n",
1156 PL_colors[0], PL_colors[1]));
a62659bd
DM
1157 goto fail_finish;
1158 }
d0880ea7 1159
4ada1233
DM
1160 /* earliest possible origin is 1 char after the \n.
1161 * (since *rx_origin == '\n', it's safe to ++ here rather than
1162 * HOP(rx_origin, 1)) */
1163 rx_origin++;
d0880ea7 1164
f4f115de 1165 if (prog->substrs->check_ix == 0 /* check is anchored */
4ada1233 1166 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
f4f115de 1167 {
d0880ea7
DM
1168 /* Position contradicts check-string; either because
1169 * check was anchored (and thus has no wiggle room),
4ada1233 1170 * or check was float and rx_origin is above the float range */
d0880ea7
DM
1171 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1172 " Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
4ada1233 1173 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
d0880ea7
DM
1174 goto restart;
1175 }
1176
1177 /* if we get here, the check substr must have been float,
2e759faa 1178 * is in range, and we may or may not have had an anchored
d0880ea7
DM
1179 * "other" substr which still contradicts */
1180 assert(prog->substrs->check_ix); /* check is float */
1181
1182 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1183 /* whoops, the anchored "other" substr exists, so we still
1184 * contradict. On the other hand, the float "check" substr
1185 * didn't contradict, so just retry the anchored "other"
1186 * substr */
1187 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1188 " Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
1189 PL_colors[0], PL_colors[1],
1190 (long)(rx_origin - strpos),
1191 (long)(rx_origin - strpos + prog->anchored_offset)));
1192 goto do_other_substr;
1193 }
1194
1195 /* success: we don't contradict the found floating substring
1196 * (and there's no anchored substr). */
d0880ea7
DM
1197 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1198 " Found /%s^%s/m at offset %ld...\n",
1199 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
e3c6feb0
DM
1200 }
1201 else {
2e759faa 1202 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
fe4f3442 1203 " (multiline anchor test skipped)\n"));
e3c6feb0
DM
1204 }
1205
ffad1e6a 1206 success_at_start:
e3c6feb0 1207
cad2e5aa 1208
dd170ff5
DM
1209 /* if we have a starting character class, then test that extra constraint.
1210 * (trie stclasses are too expensive to use here, we are better off to
1211 * leave it to regmatch itself) */
1212
f8fc2ecf 1213 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
f8fc2ecf 1214 const U8* const str = (U8*)STRING(progi->regstclass);
0991020e 1215
2c75e362 1216 /* XXX this value could be pre-computed */
f8fc2ecf 1217 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
2c75e362
DM
1218 ? (reginfo->is_utf8_pat
1219 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1220 : STR_LEN(progi->regstclass))
66e933ab 1221 : 1);
1de06328 1222 char * endpos;
fa3bb21d 1223 char *s;
000dfd2d
DM
1224 /* latest pos that a matching float substr constrains rx start to */
1225 char *rx_max_float = NULL;
1226
c75a3985
DM
1227 /* if the current rx_origin is anchored, either by satisfying an
1228 * anchored substring constraint, or a /^.../m constraint, then we
1229 * can reject the current origin if the start class isn't found
1230 * at the current position. If we have a float-only match, then
1231 * rx_origin is constrained to a range; so look for the start class
1232 * in that range. if neither, then look for the start class in the
1233 * whole rest of the string */
1234
dd170ff5
DM
1235 /* XXX DAPM it's not clear what the minlen test is for, and why
1236 * it's not used in the floating case. Nothing in the test suite
1237 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1238 * Here are some old comments, which may or may not be correct:
1239 *
1240 * minlen == 0 is possible if regstclass is \b or \B,
1241 * and the fixed substr is ''$.
1242 * Since minlen is already taken into account, rx_origin+1 is
1243 * before strend; accidentally, minlen >= 1 guaranties no false
1244 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1245 * 0) below assumes that regstclass does not come from lookahead...
1246 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1247 * This leaves EXACTF-ish only, which are dealt with in
1248 * find_byclass().
1249 */
1250
7d2d37f5 1251 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
fa3bb21d 1252 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
000dfd2d
DM
1253 else if (prog->float_substr || prog->float_utf8) {
1254 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1255 endpos= HOP3c(rx_max_float, cl_l, strend);
1256 }
1de06328
YO
1257 else
1258 endpos= strend;
1259
1dc475d0
DM
1260 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1261 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
c43b5520 1262 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1dc475d0 1263 (IV)start_shift, (IV)(check_at - strbeg),
c43b5520 1264 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
d8080198 1265
c43b5520 1266 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
f9176b44 1267 reginfo);
be778b1a 1268 if (!s) {
6eb5f6b9 1269 if (endpos == strend) {
a3621e74 1270 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1dc475d0 1271 " Could not match STCLASS...\n") );
6eb5f6b9
JH
1272 goto fail;
1273 }
a3621e74 1274 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1dc475d0 1275 " This position contradicts STCLASS...\n") );
e0eb31e7
DM
1276 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1277 && !(prog->intflags & PREGf_IMPLICIT))
653099ff 1278 goto fail;
9fed8d02 1279
6eb5f6b9 1280 /* Contradict one of substrings */
97136c8a
DM
1281 if (prog->anchored_substr || prog->anchored_utf8) {
1282 if (prog->substrs->check_ix == 1) { /* check is float */
1283 /* Have both, check_string is floating */
1284 assert(rx_origin + start_shift <= check_at);
1285 if (rx_origin + start_shift != check_at) {
1286 /* not at latest position float substr could match:
c75a3985
DM
1287 * Recheck anchored substring, but not floating.
1288 * The condition above is in bytes rather than
1289 * chars for efficiency. It's conservative, in
1290 * that it errs on the side of doing 'goto
1291 * do_other_substr', where a more accurate
1292 * char-based calculation will be done */
97136c8a
DM
1293 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1294 " Looking for anchored substr starting at offset %ld...\n",
1295 (long)(other_last - strpos)) );
1296 goto do_other_substr;
3369914b 1297 }
3369914b
DM
1298 }
1299 }
97136c8a 1300 else {
9fed8d02
DM
1301 /* float-only */
1302
7d2d37f5 1303 if (ml_anch) {
c75a3985
DM
1304 /* In the presence of ml_anch, we might be able to
1305 * find another \n without breaking the current float
1306 * constraint. */
1307
1308 /* strictly speaking this should be HOP3c(..., 1, ...),
1309 * but since we goto a block of code that's going to
1310 * search for the next \n if any, its safe here */
9fed8d02 1311 rx_origin++;
9fed8d02
DM
1312 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1313 " Looking for /%s^%s/m starting at offset %ld...\n",
1314 PL_colors[0], PL_colors[1],
1315 (long)(rx_origin - strpos)) );
9fed8d02 1316 goto postprocess_substr_matches;
ab60c45a 1317 }
c75a3985
DM
1318
1319 /* strictly speaking this can never be true; but might
1320 * be if we ever allow intuit without substrings */
1321 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
9fed8d02 1322 goto fail;
c75a3985 1323
000dfd2d 1324 rx_origin = rx_max_float;
9fed8d02
DM
1325 }
1326
c75a3985
DM
1327 /* at this point, any matching substrings have been
1328 * contradicted. Start again... */
1329
9fed8d02 1330 rx_origin = HOP3c(rx_origin, 1, strend);
557f47af
DM
1331
1332 /* uses bytes rather than char calculations for efficiency.
1333 * It's conservative: it errs on the side of doing 'goto restart',
1334 * where there is code that does a proper char-based test */
9fed8d02 1335 if (rx_origin + start_shift + end_shift > strend) {
40268e5b 1336 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
9fed8d02
DM
1337 " Could not match STCLASS...\n") );
1338 goto fail;
1339 }
1340 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1341 " Looking for %s substr starting at offset %ld...\n",
1342 (prog->substrs->check_ix ? "floating" : "anchored"),
1343 (long)(rx_origin + start_shift - strpos)) );
1344 goto restart;
6eb5f6b9 1345 }
9fed8d02 1346
c75a3985
DM
1347 /* Success !!! */
1348
5f9c6575 1349 if (rx_origin != s) {
a3621e74 1350 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 1351 " By STCLASS: moving %ld --> %ld\n",
5f9c6575 1352 (long)(rx_origin - strpos), (long)(s - strpos))
b7953727
JH
1353 );
1354 }
1355 else {
a3621e74 1356 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 1357 " Does not contradict STCLASS...\n");
b7953727
JH
1358 );
1359 }
6eb5f6b9 1360 }
ffad1e6a
DM
1361
1362 /* Decide whether using the substrings helped */
1363
1364 if (rx_origin != strpos) {
1365 /* Fixed substring is found far enough so that the match
1366 cannot start at strpos. */
1367
1368 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1369 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1370 }
1371 else {
70563e16
DM
1372 /* The found rx_origin position does not prohibit matching at
1373 * strpos, so calling intuit didn't gain us anything. Decrement
1374 * the BmUSEFUL() count on the check substring, and if we reach
1375 * zero, free it. */
1376 if (!(prog->intflags & PREGf_NAUGHTY)
ffad1e6a
DM
1377 && (utf8_target ? (
1378 prog->check_utf8 /* Could be deleted already */
1379 && --BmUSEFUL(prog->check_utf8) < 0
1380 && (prog->check_utf8 == prog->float_utf8)
1381 ) : (
1382 prog->check_substr /* Could be deleted already */
1383 && --BmUSEFUL(prog->check_substr) < 0
1384 && (prog->check_substr == prog->float_substr)
1385 )))
1386 {
1387 /* If flags & SOMETHING - do not do it many times on the same match */
1388 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1389 /* XXX Does the destruction order has to change with utf8_target? */
1390 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1391 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1392 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1393 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1394 check = NULL; /* abort */
ffad1e6a
DM
1395 /* XXXX This is a remnant of the old implementation. It
1396 looks wasteful, since now INTUIT can use many
1397 other heuristics. */
1398 prog->extflags &= ~RXf_USE_INTUIT;
ffad1e6a
DM
1399 }
1400 }
1401
1402 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1403 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1404 PL_colors[4], PL_colors[5], (long)(rx_origin - strpos)) );
1405
c765d6e0 1406 return rx_origin;
2c2d71f5
JH
1407
1408 fail_finish: /* Substring not found */
33b8afdf 1409 if (prog->check_substr || prog->check_utf8) /* could be removed already */
f2ed9b32 1410 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
cad2e5aa 1411 fail:
a3621e74 1412 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
e4584336 1413 PL_colors[4], PL_colors[5]));
bd61b366 1414 return NULL;
cad2e5aa 1415}
9661b544 1416
70563e16 1417
a0a388a1 1418#define DECL_TRIE_TYPE(scan) \
e7fd4aa1 1419 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
a4525e78
KW
1420 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1421 trie_utf8l, trie_flu8 } \
e7fd4aa1
KW
1422 trie_type = ((scan->flags == EXACT) \
1423 ? (utf8_target ? trie_utf8 : trie_plain) \
a4525e78
KW
1424 : (scan->flags == EXACTL) \
1425 ? (utf8_target ? trie_utf8l : trie_plain) \
1426 : (scan->flags == EXACTFA) \
1427 ? (utf8_target \
1428 ? trie_utf8_exactfa_fold \
1429 : trie_latin_utf8_exactfa_fold) \
1430 : (scan->flags == EXACTFLU8 \
1431 ? trie_flu8 \
1432 : (utf8_target \
1433 ? trie_utf8_fold \
1434 : trie_latin_utf8_fold)))
fab2782b 1435
fd3249ee 1436#define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
baa60164 1437STMT_START { \
fab2782b 1438 STRLEN skiplen; \
baa60164 1439 U8 flags = FOLD_FLAGS_FULL; \
fab2782b 1440 switch (trie_type) { \
a4525e78 1441 case trie_flu8: \
780fcc9f 1442 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
613abc6d
KW
1443 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1444 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1445 } \
a4525e78 1446 goto do_trie_utf8_fold; \
31f05a37 1447 case trie_utf8_exactfa_fold: \
baa60164 1448 flags |= FOLD_FLAGS_NOMIX_ASCII; \
8e57b935 1449 /* FALLTHROUGH */ \
fab2782b 1450 case trie_utf8_fold: \
a4525e78 1451 do_trie_utf8_fold: \
fab2782b 1452 if ( foldlen>0 ) { \
c80e42f3 1453 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
fab2782b
YO
1454 foldlen -= len; \
1455 uscan += len; \
1456 len=0; \
1457 } else { \
445bf929 1458 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
fab2782b
YO
1459 len = UTF8SKIP(uc); \
1460 skiplen = UNISKIP( uvc ); \
1461 foldlen -= skiplen; \
1462 uscan = foldbuf + skiplen; \
1463 } \
1464 break; \
baa60164
KW
1465 case trie_latin_utf8_exactfa_fold: \
1466 flags |= FOLD_FLAGS_NOMIX_ASCII; \
8e57b935 1467 /* FALLTHROUGH */ \
fab2782b
YO
1468 case trie_latin_utf8_fold: \
1469 if ( foldlen>0 ) { \
c80e42f3 1470 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
fab2782b
YO
1471 foldlen -= len; \
1472 uscan += len; \
1473 len=0; \
1474 } else { \
1475 len = 1; \
31f05a37 1476 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
fab2782b
YO
1477 skiplen = UNISKIP( uvc ); \
1478 foldlen -= skiplen; \
1479 uscan = foldbuf + skiplen; \
1480 } \
1481 break; \
a4525e78 1482 case trie_utf8l: \
780fcc9f 1483 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
613abc6d
KW
1484 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1485 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1486 } \
780fcc9f 1487 /* FALLTHROUGH */ \
fab2782b 1488 case trie_utf8: \
c80e42f3 1489 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
fab2782b
YO
1490 break; \
1491 case trie_plain: \
1492 uvc = (UV)*uc; \
1493 len = 1; \
1494 } \
1495 if (uvc < 256) { \
1496 charid = trie->charmap[ uvc ]; \
1497 } \
1498 else { \
1499 charid = 0; \
1500 if (widecharmap) { \
1501 SV** const svpp = hv_fetch(widecharmap, \
1502 (char*)&uvc, sizeof(UV), 0); \
1503 if (svpp) \
1504 charid = (U16)SvIV(*svpp); \
1505 } \
1506 } \
4cadc6a9
YO
1507} STMT_END
1508
ae7c5b9b
KW
1509#define DUMP_EXEC_POS(li,s,doutf8) \
1510 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1511 startpos, doutf8)
1512
c84a03c5 1513#define REXEC_FBC_EXACTISH_SCAN(COND) \
4cadc6a9
YO
1514STMT_START { \
1515 while (s <= e) { \
c84a03c5 1516 if ( (COND) \
fac1af77 1517 && (ln == 1 || folder(s, pat_string, ln)) \
02d5137b 1518 && (reginfo->intuit || regtry(reginfo, &s)) )\
4cadc6a9
YO
1519 goto got_it; \
1520 s++; \
1521 } \
1522} STMT_END
1523
c84a03c5 1524#define REXEC_FBC_UTF8_SCAN(CODE) \
4cadc6a9 1525STMT_START { \
9a902117 1526 while (s < strend) { \
c84a03c5 1527 CODE \
9a902117 1528 s += UTF8SKIP(s); \
4cadc6a9
YO
1529 } \
1530} STMT_END
1531
c84a03c5 1532#define REXEC_FBC_SCAN(CODE) \
4cadc6a9
YO
1533STMT_START { \
1534 while (s < strend) { \
c84a03c5 1535 CODE \
4cadc6a9
YO
1536 s++; \
1537 } \
1538} STMT_END
1539
05bd126c
KW
1540#define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1541REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1542 if (COND) { \
1543 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1544 goto got_it; \
1545 else \
1546 tmp = doevery; \
1547 } \
1548 else \
1549 tmp = 1; \
4cadc6a9
YO
1550)
1551
05bd126c
KW
1552#define REXEC_FBC_CLASS_SCAN(COND) \
1553REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1554 if (COND) { \
1555 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1556 goto got_it; \
1557 else \
1558 tmp = doevery; \
1559 } \
1560 else \
1561 tmp = 1; \
4cadc6a9
YO
1562)
1563
c84a03c5 1564#define REXEC_FBC_CSCAN(CONDUTF8,COND) \
baa60164 1565 if (utf8_target) { \
c84a03c5 1566 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
e1d1eefb
YO
1567 } \
1568 else { \
c84a03c5 1569 REXEC_FBC_CLASS_SCAN(COND); \
d981ef24 1570 }
05bd126c 1571
05bd126c
KW
1572/* The three macros below are slightly different versions of the same logic.
1573 *
1574 * The first is for /a and /aa when the target string is UTF-8. This can only
1575 * match ascii, but it must advance based on UTF-8. The other two handle the
1576 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1577 * for the boundary (or non-boundary) between a word and non-word character.
1578 * The utf8 and non-utf8 cases have the same logic, but the details must be
1579 * different. Find the "wordness" of the character just prior to this one, and
1580 * compare it with the wordness of this one. If they differ, we have a
1581 * boundary. At the beginning of the string, pretend that the previous
1582 * character was a new-line.
1583 *
1584 * All these macros uncleanly have side-effects with each other and outside
1585 * variables. So far it's been too much trouble to clean-up
1586 *
1587 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1588 * a word character or not.
1589 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1590 * word/non-word
1591 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1592 *
1593 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1594 * are looking for a boundary or for a non-boundary. If we are looking for a
1595 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1596 * see if this tentative match actually works, and if so, to quit the loop
1597 * here. And vice-versa if we are looking for a non-boundary.
1598 *
1599 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1600 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1601 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1602 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1603 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1604 * complement. But in that branch we complement tmp, meaning that at the
1605 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1606 * which means at the top of the loop in the next iteration, it is
1607 * TEST_NON_UTF8(s-1) */
b2f4e957 1608#define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
05bd126c
KW
1609 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1610 tmp = TEST_NON_UTF8(tmp); \
1611 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1612 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1613 tmp = !tmp; \
1614 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1615 } \
1616 else { \
1617 IF_FAIL; \
1618 } \
1619 ); \
1620
1621/* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1622 * TEST_UTF8 is a macro that for the same input code points returns identically
1623 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
236d82fd 1624#define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
05bd126c
KW
1625 if (s == reginfo->strbeg) { \
1626 tmp = '\n'; \
1627 } \
1628 else { /* Back-up to the start of the previous character */ \
1629 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1630 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
3db24e1e 1631 0, UTF8_ALLOW_DEFAULT); \
05bd126c
KW
1632 } \
1633 tmp = TEST_UV(tmp); \
1634 LOAD_UTF8_CHARCLASS_ALNUM(); \
1635 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1636 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1637 tmp = !tmp; \
1638 IF_SUCCESS; \
1639 } \
1640 else { \
1641 IF_FAIL; \
1642 } \
1643 );
cfaf538b 1644
05bd126c
KW
1645/* Like the above two macros. UTF8_CODE is the complete code for handling
1646 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1647 * macros below */
baa60164 1648#define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
63ac0dad 1649 if (utf8_target) { \
05bd126c 1650 UTF8_CODE \
63ac0dad
KW
1651 } \
1652 else { /* Not utf8 */ \
9d9163fb 1653 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
63ac0dad 1654 tmp = TEST_NON_UTF8(tmp); \
05bd126c 1655 REXEC_FBC_SCAN( /* advances s while s < strend */ \
63ac0dad 1656 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
63ac0dad 1657 IF_SUCCESS; \
760cfa8e 1658 tmp = !tmp; \
63ac0dad
KW
1659 } \
1660 else { \
1661 IF_FAIL; \
1662 } \
1663 ); \
1664 } \
c8519dc7
KW
1665 /* Here, things have been set up by the previous code so that tmp is the \
1666 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1667 * utf8ness of the target). We also have to check if this matches against \
1668 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1669 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1670 * string */ \
1671 if (tmp == ! TEST_NON_UTF8('\n')) { \
1672 IF_SUCCESS; \
1673 } \
1674 else { \
1675 IF_FAIL; \
1676 }
63ac0dad 1677
ae7c5b9b
KW
1678/* This is the macro to use when we want to see if something that looks like it
1679 * could match, actually does, and if so exits the loop */
1680#define REXEC_FBC_TRYIT \
1681 if ((reginfo->intuit || regtry(reginfo, &s))) \
1682 goto got_it
1683
1684/* The only difference between the BOUND and NBOUND cases is that
1685 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1686 * NBOUND. This is accomplished by passing it as either the if or else clause,
1687 * with the other one being empty (PLACEHOLDER is defined as empty).
1688 *
1689 * The TEST_FOO parameters are for operating on different forms of input, but
1690 * all should be ones that return identically for the same underlying code
1691 * points */
1692#define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1693 FBC_BOUND_COMMON( \
1694 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1695 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1696
44129e46 1697#define FBC_BOUND_A(TEST_NON_UTF8) \
ae7c5b9b
KW
1698 FBC_BOUND_COMMON( \
1699 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1700 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1701
1702#define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1703 FBC_BOUND_COMMON( \
1704 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1705 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1706
44129e46 1707#define FBC_NBOUND_A(TEST_NON_UTF8) \
ae7c5b9b
KW
1708 FBC_BOUND_COMMON( \
1709 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1710 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1711
64935bc6
KW
1712/* Takes a pointer to an inversion list, a pointer to its corresponding
1713 * inversion map, and a code point, and returns the code point's value
1714 * according to the two arrays. It assumes that all code points have a value.
1715 * This is used as the base macro for macros for particular properties */
1716#define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1717 invmap[_invlist_search(invlist, cp)]
1718
1719/* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1720 * of a code point, returning the value for the first code point in the string.
1721 * And it takes the particular macro name that finds the desired value given a
1722 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1723#define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1724 (__ASSERT_(pos < strend) \
1725 /* Note assumes is valid UTF-8 */ \
1726 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1727
1728/* Returns the GCB value for the input code point */
1729#define getGCB_VAL_CP(cp) \
1730 _generic_GET_BREAK_VAL_CP( \
1731 PL_GCB_invlist, \
1732 Grapheme_Cluster_Break_invmap, \
1733 (cp))
1734
1735/* Returns the GCB value for the first code point in the UTF-8 encoded string
1736 * bounded by pos and strend */
1737#define getGCB_VAL_UTF8(pos, strend) \
1738 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
05bd126c 1739
786e8c11 1740/* We know what class REx starts with. Try to find this position... */
02d5137b 1741/* if reginfo->intuit, its a dryrun */
786e8c11
YO
1742/* annoyingly all the vars in this routine have different names from their counterparts
1743 in regmatch. /grrr */
3c3eec57 1744STATIC char *
07be1b83 1745S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
f9176b44 1746 const char *strend, regmatch_info *reginfo)
a687059c 1747{
73104a1b
KW
1748 dVAR;
1749 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1750 char *pat_string; /* The pattern's exactish string */
1751 char *pat_end; /* ptr to end char of pat_string */
1752 re_fold_t folder; /* Function for computing non-utf8 folds */
1753 const U8 *fold_array; /* array for folding ords < 256 */
1754 STRLEN ln;
1755 STRLEN lnc;
73104a1b
KW
1756 U8 c1;
1757 U8 c2;
1758 char *e;
1759 I32 tmp = 1; /* Scratch variable? */
ba44c216 1760 const bool utf8_target = reginfo->is_utf8_target;
73104a1b 1761 UV utf8_fold_flags = 0;
f9176b44 1762 const bool is_utf8_pat = reginfo->is_utf8_pat;
3018b823
KW
1763 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1764 with a result inverts that result, as 0^1 =
1765 1 and 1^1 = 0 */
1766 _char_class_number classnum;
1767
73104a1b 1768 RXi_GET_DECL(prog,progi);
2f7f8cb1 1769
73104a1b 1770 PERL_ARGS_ASSERT_FIND_BYCLASS;
2f7f8cb1 1771
73104a1b
KW
1772 /* We know what class it must start with. */
1773 switch (OP(c)) {
a4525e78 1774 case ANYOFL:
780fcc9f
KW
1775 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1776 /* FALLTHROUGH */
73104a1b
KW
1777 case ANYOF:
1778 if (utf8_target) {
1779 REXEC_FBC_UTF8_CLASS_SCAN(
3db24e1e 1780 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
73104a1b
KW
1781 }
1782 else {
1783 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1784 }
1785 break;
1786 case CANY:
1787 REXEC_FBC_SCAN(
02d5137b 1788 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
73104a1b
KW
1789 goto got_it;
1790 else
1791 tmp = doevery;
1792 );
1793 break;
1794
098b07d5
KW
1795 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1796 assert(! is_utf8_pat);
924ba076 1797 /* FALLTHROUGH */
73104a1b 1798 case EXACTFA:
984e6dd1 1799 if (is_utf8_pat || utf8_target) {
73104a1b
KW
1800 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1801 goto do_exactf_utf8;
1802 }
1803 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1804 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1805 goto do_exactf_non_utf8; /* isn't dealt with by these */
77a6d856 1806
2fdb7295
KW
1807 case EXACTF: /* This node only generated for non-utf8 patterns */
1808 assert(! is_utf8_pat);
73104a1b 1809 if (utf8_target) {
73104a1b
KW
1810 utf8_fold_flags = 0;
1811 goto do_exactf_utf8;
1812 }
1813 fold_array = PL_fold;
1814 folder = foldEQ;
1815 goto do_exactf_non_utf8;
1816
1817 case EXACTFL:
780fcc9f 1818 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
31f05a37 1819 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
cea315b6 1820 utf8_fold_flags = FOLDEQ_LOCALE;
73104a1b
KW
1821 goto do_exactf_utf8;
1822 }
1823 fold_array = PL_fold_locale;
1824 folder = foldEQ_locale;
1825 goto do_exactf_non_utf8;
3c760661 1826
73104a1b 1827 case EXACTFU_SS:
984e6dd1 1828 if (is_utf8_pat) {
73104a1b
KW
1829 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1830 }
1831 goto do_exactf_utf8;
16d951b7 1832
a4525e78
KW
1833 case EXACTFLU8:
1834 if (! utf8_target) { /* All code points in this node require
1835 UTF-8 to express. */
1836 break;
1837 }
613abc6d
KW
1838 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1839 | FOLDEQ_S2_FOLDS_SANE;
a4525e78
KW
1840 goto do_exactf_utf8;
1841
73104a1b 1842 case EXACTFU:
984e6dd1
DM
1843 if (is_utf8_pat || utf8_target) {
1844 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
73104a1b
KW
1845 goto do_exactf_utf8;
1846 }
fac1af77 1847
73104a1b
KW
1848 /* Any 'ss' in the pattern should have been replaced by regcomp,
1849 * so we don't have to worry here about this single special case
1850 * in the Latin1 range */
1851 fold_array = PL_fold_latin1;
1852 folder = foldEQ_latin1;
1853
924ba076 1854 /* FALLTHROUGH */
73104a1b 1855
c52b8b12 1856 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
73104a1b
KW
1857 are no glitches with fold-length differences
1858 between the target string and pattern */
1859
1860 /* The idea in the non-utf8 EXACTF* cases is to first find the
1861 * first character of the EXACTF* node and then, if necessary,
1862 * case-insensitively compare the full text of the node. c1 is the
1863 * first character. c2 is its fold. This logic will not work for
1864 * Unicode semantics and the german sharp ss, which hence should
1865 * not be compiled into a node that gets here. */
1866 pat_string = STRING(c);
1867 ln = STR_LEN(c); /* length to match in octets/bytes */
1868
1869 /* We know that we have to match at least 'ln' bytes (which is the
1870 * same as characters, since not utf8). If we have to match 3
1871 * characters, and there are only 2 availabe, we know without
1872 * trying that it will fail; so don't start a match past the
1873 * required minimum number from the far end */
ea3daa5d 1874 e = HOP3c(strend, -((SSize_t)ln), s);
73104a1b 1875
02d5137b 1876 if (reginfo->intuit && e < s) {
73104a1b
KW
1877 e = s; /* Due to minlen logic of intuit() */
1878 }
fac1af77 1879
73104a1b
KW
1880 c1 = *pat_string;
1881 c2 = fold_array[c1];
1882 if (c1 == c2) { /* If char and fold are the same */
1883 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1884 }
1885 else {
1886 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1887 }
1888 break;
fac1af77 1889
c52b8b12
KW
1890 do_exactf_utf8:
1891 {
73104a1b
KW
1892 unsigned expansion;
1893
1894 /* If one of the operands is in utf8, we can't use the simpler folding
1895 * above, due to the fact that many different characters can have the
1896 * same fold, or portion of a fold, or different- length fold */
1897 pat_string = STRING(c);
1898 ln = STR_LEN(c); /* length to match in octets/bytes */
1899 pat_end = pat_string + ln;
984e6dd1 1900 lnc = is_utf8_pat /* length to match in characters */
73104a1b
KW
1901 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1902 : ln;
1903
1904 /* We have 'lnc' characters to match in the pattern, but because of
1905 * multi-character folding, each character in the target can match
1906 * up to 3 characters (Unicode guarantees it will never exceed
1907 * this) if it is utf8-encoded; and up to 2 if not (based on the
1908 * fact that the Latin 1 folds are already determined, and the
1909 * only multi-char fold in that range is the sharp-s folding to
1910 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1911 * string character. Adjust lnc accordingly, rounding up, so that
1912 * if we need to match at least 4+1/3 chars, that really is 5. */
1913 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1914 lnc = (lnc + expansion - 1) / expansion;
1915
1916 /* As in the non-UTF8 case, if we have to match 3 characters, and
1917 * only 2 are left, it's guaranteed to fail, so don't start a
1918 * match that would require us to go beyond the end of the string
1919 */
ea3daa5d 1920 e = HOP3c(strend, -((SSize_t)lnc), s);
73104a1b 1921
02d5137b 1922 if (reginfo->intuit && e < s) {
73104a1b
KW
1923 e = s; /* Due to minlen logic of intuit() */
1924 }
0658cdde 1925
73104a1b
KW
1926 /* XXX Note that we could recalculate e to stop the loop earlier,
1927 * as the worst case expansion above will rarely be met, and as we
1928 * go along we would usually find that e moves further to the left.
1929 * This would happen only after we reached the point in the loop
1930 * where if there were no expansion we should fail. Unclear if
1931 * worth the expense */
1932
1933 while (s <= e) {
1934 char *my_strend= (char *)strend;
1935 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
984e6dd1 1936 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
02d5137b 1937 && (reginfo->intuit || regtry(reginfo, &s)) )
73104a1b
KW
1938 {
1939 goto got_it;
1940 }
1941 s += (utf8_target) ? UTF8SKIP(s) : 1;
1942 }
1943 break;
1944 }
236d82fd 1945
73104a1b 1946 case BOUNDL:
780fcc9f 1947 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
64935bc6
KW
1948 if (FLAGS(c) != TRADITIONAL_BOUND) {
1949 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
1950 B_ON_NON_UTF8_LOCALE_IS_WRONG);
1951 goto do_boundu;
1952 }
1953
236d82fd 1954 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
73104a1b 1955 break;
64935bc6 1956
73104a1b 1957 case NBOUNDL:
780fcc9f 1958 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
64935bc6
KW
1959 if (FLAGS(c) != TRADITIONAL_BOUND) {
1960 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
1961 B_ON_NON_UTF8_LOCALE_IS_WRONG);
1962 goto do_nboundu;
1963 }
1964
236d82fd 1965 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
73104a1b 1966 break;
64935bc6
KW
1967
1968 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
1969 meaning */
1970 assert(FLAGS(c) == TRADITIONAL_BOUND);
1971
236d82fd 1972 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
73104a1b 1973 break;
64935bc6
KW
1974
1975 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
1976 meaning */
1977 assert(FLAGS(c) == TRADITIONAL_BOUND);
1978
44129e46 1979 FBC_BOUND_A(isWORDCHAR_A);
73104a1b 1980 break;
64935bc6
KW
1981
1982 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
1983 meaning */
1984 assert(FLAGS(c) == TRADITIONAL_BOUND);
1985
236d82fd 1986 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
73104a1b 1987 break;
64935bc6
KW
1988
1989 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
1990 meaning */
1991 assert(FLAGS(c) == TRADITIONAL_BOUND);
1992
44129e46 1993 FBC_NBOUND_A(isWORDCHAR_A);
73104a1b 1994 break;
64935bc6 1995
73104a1b 1996 case NBOUNDU:
64935bc6
KW
1997 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
1998 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
1999 break;
2000 }
2001
2002 do_nboundu:
2003
2004 to_complement = 1;
2005 /* FALLTHROUGH */
2006
2007 case BOUNDU:
2008 do_boundu:
2009 switch((bound_type) FLAGS(c)) {
2010 case TRADITIONAL_BOUND:
2011 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2012 break;
2013 case GCB_BOUND:
2014 if (s == reginfo->strbeg) { /* GCB always matches at begin and
2015 end */
2016 if (to_complement ^ cBOOL(reginfo->intuit
2017 || regtry(reginfo, &s)))
2018 {
2019 goto got_it;
2020 }
2021 s += (utf8_target) ? UTF8SKIP(s) : 1;
2022 }
2023
2024 if (utf8_target) {
2025 PL_GCB_enum before = getGCB_VAL_UTF8(
2026 reghop3((U8*)s, -1,
2027 (U8*)(reginfo->strbeg)),
2028 (U8*) reginfo->strend);
2029 while (s < strend) {
2030 PL_GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2031 (U8*) reginfo->strend);
2032 if (to_complement ^ isGCB(before, after)) {
2033 if (reginfo->intuit || regtry(reginfo, &s)) {
2034 goto got_it;
2035 }
2036 before = after;
2037 }
2038 s += UTF8SKIP(s);
2039 }
2040 }
2041 else { /* Not utf8. Everything is a GCB except between CR and
2042 LF */
2043 while (s < strend) {
2044 if (to_complement ^ (UCHARAT(s - 1) != '\r'
2045 || UCHARAT(s) != '\n'))
2046 {
2047 if (reginfo->intuit || regtry(reginfo, &s)) {
2048 goto got_it;
2049 }
2050 s++;
2051 }
2052 }
2053 }
2054
2055 if (to_complement ^ cBOOL(reginfo->intuit || regtry(reginfo, &s))) {
2056 goto got_it;
2057 }
2058 break;
2059 }
73104a1b 2060 break;
64935bc6 2061
73104a1b
KW
2062 case LNBREAK:
2063 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2064 is_LNBREAK_latin1_safe(s, strend)
2065 );
2066 break;
3018b823
KW
2067
2068 /* The argument to all the POSIX node types is the class number to pass to
2069 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2070
2071 case NPOSIXL:
2072 to_complement = 1;
2073 /* FALLTHROUGH */
2074
2075 case POSIXL:
780fcc9f 2076 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
3018b823
KW
2077 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2078 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
73104a1b 2079 break;
3018b823
KW
2080
2081 case NPOSIXD:
2082 to_complement = 1;
2083 /* FALLTHROUGH */
2084
2085 case POSIXD:
2086 if (utf8_target) {
2087 goto posix_utf8;
2088 }
2089 goto posixa;
2090
2091 case NPOSIXA:
2092 if (utf8_target) {
2093 /* The complement of something that matches only ASCII matches all
837226c8
KW
2094 * non-ASCII, plus everything in ASCII that isn't in the class. */
2095 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
3018b823
KW
2096 || ! _generic_isCC_A(*s, FLAGS(c)));
2097 break;
2098 }
2099
2100 to_complement = 1;
2101 /* FALLTHROUGH */
2102
73104a1b 2103 case POSIXA:
3018b823 2104 posixa:
73104a1b 2105 /* Don't need to worry about utf8, as it can match only a single
3018b823
KW
2106 * byte invariant character. */
2107 REXEC_FBC_CLASS_SCAN(
2108 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
73104a1b 2109 break;
3018b823
KW
2110
2111 case NPOSIXU:
2112 to_complement = 1;
2113 /* FALLTHROUGH */
2114
2115 case POSIXU:
2116 if (! utf8_target) {
2117 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2118 FLAGS(c))));
2119 }
2120 else {
2121
c52b8b12 2122 posix_utf8:
3018b823
KW
2123 classnum = (_char_class_number) FLAGS(c);
2124 if (classnum < _FIRST_NON_SWASH_CC) {
2125 while (s < strend) {
2126
2127 /* We avoid loading in the swash as long as possible, but
2128 * should we have to, we jump to a separate loop. This
2129 * extra 'if' statement is what keeps this code from being
2130 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2131 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2132 goto found_above_latin1;
2133 }
2134 if ((UTF8_IS_INVARIANT(*s)
2135 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2136 classnum)))
2137 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2138 && to_complement ^ cBOOL(
94bb8c36
KW
2139 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2140 *(s + 1)),
3018b823
KW
2141 classnum))))
2142 {
02d5137b 2143 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
3018b823
KW
2144 goto got_it;
2145 else {
2146 tmp = doevery;
2147 }
2148 }
2149 else {
2150 tmp = 1;
2151 }
2152 s += UTF8SKIP(s);
2153 }
2154 }
2155 else switch (classnum) { /* These classes are implemented as
2156 macros */
2157 case _CC_ENUM_SPACE: /* XXX would require separate code if we
2158 revert the change of \v matching this */
924ba076 2159 /* FALLTHROUGH */
3018b823
KW
2160
2161 case _CC_ENUM_PSXSPC:
2162 REXEC_FBC_UTF8_CLASS_SCAN(
2163 to_complement ^ cBOOL(isSPACE_utf8(s)));
2164 break;
2165
2166 case _CC_ENUM_BLANK:
2167 REXEC_FBC_UTF8_CLASS_SCAN(
2168 to_complement ^ cBOOL(isBLANK_utf8(s)));
2169 break;
2170
2171 case _CC_ENUM_XDIGIT:
2172 REXEC_FBC_UTF8_CLASS_SCAN(
2173 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2174 break;
2175
2176 case _CC_ENUM_VERTSPACE:
2177 REXEC_FBC_UTF8_CLASS_SCAN(
2178 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2179 break;
2180
2181 case _CC_ENUM_CNTRL:
2182 REXEC_FBC_UTF8_CLASS_SCAN(
2183 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2184 break;
2185
2186 default:
2187 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
e5964223 2188 NOT_REACHED; /* NOTREACHED */
3018b823
KW
2189 }
2190 }
2191 break;
2192
2193 found_above_latin1: /* Here we have to load a swash to get the result
2194 for the current code point */
2195 if (! PL_utf8_swash_ptrs[classnum]) {
2196 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2197 PL_utf8_swash_ptrs[classnum] =
2a16ac92
KW
2198 _core_swash_init("utf8",
2199 "",
2200 &PL_sv_undef, 1, 0,
2201 PL_XPosix_ptrs[classnum], &flags);
3018b823
KW
2202 }
2203
2204 /* This is a copy of the loop above for swash classes, though using the
2205 * FBC macro instead of being expanded out. Since we've loaded the
2206 * swash, we don't have to check for that each time through the loop */
2207 REXEC_FBC_UTF8_CLASS_SCAN(
2208 to_complement ^ cBOOL(_generic_utf8(
2209 classnum,
2210 s,
2211 swash_fetch(PL_utf8_swash_ptrs[classnum],
2212 (U8 *) s, TRUE))));
73104a1b
KW
2213 break;
2214
2215 case AHOCORASICKC:
2216 case AHOCORASICK:
2217 {
2218 DECL_TRIE_TYPE(c);
2219 /* what trie are we using right now */
2220 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2221 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2222 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2223
2224 const char *last_start = strend - trie->minlen;
6148ee25 2225#ifdef DEBUGGING
73104a1b 2226 const char *real_start = s;
6148ee25 2227#endif
73104a1b
KW
2228 STRLEN maxlen = trie->maxlen;
2229 SV *sv_points;
2230 U8 **points; /* map of where we were in the input string
2231 when reading a given char. For ASCII this
2232 is unnecessary overhead as the relationship
2233 is always 1:1, but for Unicode, especially
2234 case folded Unicode this is not true. */
2235 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2236 U8 *bitmap=NULL;
2237
2238
2239 GET_RE_DEBUG_FLAGS_DECL;
2240
2241 /* We can't just allocate points here. We need to wrap it in
2242 * an SV so it gets freed properly if there is a croak while
2243 * running the match */
2244 ENTER;
2245 SAVETMPS;
2246 sv_points=newSV(maxlen * sizeof(U8 *));
2247 SvCUR_set(sv_points,
2248 maxlen * sizeof(U8 *));
2249 SvPOK_on(sv_points);
2250 sv_2mortal(sv_points);
2251 points=(U8**)SvPV_nolen(sv_points );
2252 if ( trie_type != trie_utf8_fold
2253 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2254 {
2255 if (trie->bitmap)
2256 bitmap=(U8*)trie->bitmap;
2257 else
2258 bitmap=(U8*)ANYOF_BITMAP(c);
2259 }
2260 /* this is the Aho-Corasick algorithm modified a touch
2261 to include special handling for long "unknown char" sequences.
2262 The basic idea being that we use AC as long as we are dealing
2263 with a possible matching char, when we encounter an unknown char
2264 (and we have not encountered an accepting state) we scan forward
2265 until we find a legal starting char.
2266 AC matching is basically that of trie matching, except that when
2267 we encounter a failing transition, we fall back to the current
2268 states "fail state", and try the current char again, a process
2269 we repeat until we reach the root state, state 1, or a legal
2270 transition. If we fail on the root state then we can either
2271 terminate if we have reached an accepting state previously, or
2272 restart the entire process from the beginning if we have not.
2273
2274 */
2275 while (s <= last_start) {
2276 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2277 U8 *uc = (U8*)s;
2278 U16 charid = 0;
2279 U32 base = 1;
2280 U32 state = 1;
2281 UV uvc = 0;
2282 STRLEN len = 0;
2283 STRLEN foldlen = 0;
2284 U8 *uscan = (U8*)NULL;
2285 U8 *leftmost = NULL;
2286#ifdef DEBUGGING
2287 U32 accepted_word= 0;
786e8c11 2288#endif
73104a1b
KW
2289 U32 pointpos = 0;
2290
2291 while ( state && uc <= (U8*)strend ) {
2292 int failed=0;
2293 U32 word = aho->states[ state ].wordnum;
2294
2295 if( state==1 ) {
2296 if ( bitmap ) {
2297 DEBUG_TRIE_EXECUTE_r(
2298 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2299 dump_exec_pos( (char *)uc, c, strend, real_start,
2300 (char *)uc, utf8_target );
2301 PerlIO_printf( Perl_debug_log,
2302 " Scanning for legal start char...\n");
2303 }
2304 );
2305 if (utf8_target) {
2306 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2307 uc += UTF8SKIP(uc);
2308 }
2309 } else {
2310 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2311 uc++;
2312 }
786e8c11 2313 }
73104a1b 2314 s= (char *)uc;
07be1b83 2315 }
73104a1b
KW
2316 if (uc >(U8*)last_start) break;
2317 }
2318
2319 if ( word ) {
2320 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2321 if (!leftmost || lpos < leftmost) {
2322 DEBUG_r(accepted_word=word);
2323 leftmost= lpos;
7016d6eb 2324 }
73104a1b 2325 if (base==0) break;
7016d6eb 2326
73104a1b
KW
2327 }
2328 points[pointpos++ % maxlen]= uc;
2329 if (foldlen || uc < (U8*)strend) {
2330 REXEC_TRIE_READ_CHAR(trie_type, trie,
2331 widecharmap, uc,
2332 uscan, len, uvc, charid, foldlen,
2333 foldbuf, uniflags);
2334 DEBUG_TRIE_EXECUTE_r({
2335 dump_exec_pos( (char *)uc, c, strend,
2336 real_start, s, utf8_target);
2337 PerlIO_printf(Perl_debug_log,
2338 " Charid:%3u CP:%4"UVxf" ",
2339 charid, uvc);
2340 });
2341 }
2342 else {
2343 len = 0;
2344 charid = 0;
2345 }
07be1b83 2346
73104a1b
KW
2347
2348 do {
6148ee25 2349#ifdef DEBUGGING
73104a1b 2350 word = aho->states[ state ].wordnum;
6148ee25 2351#endif
73104a1b
KW
2352 base = aho->states[ state ].trans.base;
2353
2354 DEBUG_TRIE_EXECUTE_r({
2355 if (failed)
2356 dump_exec_pos( (char *)uc, c, strend, real_start,
2357 s, utf8_target );
2358 PerlIO_printf( Perl_debug_log,
2359 "%sState: %4"UVxf", word=%"UVxf,
2360 failed ? " Fail transition to " : "",
2361 (UV)state, (UV)word);
2362 });
2363 if ( base ) {
2364 U32 tmp;
2365 I32 offset;
2366 if (charid &&
2367 ( ((offset = base + charid
2368 - 1 - trie->uniquecharcount)) >= 0)
2369 && ((U32)offset < trie->lasttrans)
2370 && trie->trans[offset].check == state
2371 && (tmp=trie->trans[offset].next))
2372 {
2373 DEBUG_TRIE_EXECUTE_r(
2374 PerlIO_printf( Perl_debug_log," - legal\n"));
2375 state = tmp;
2376 break;
07be1b83
YO
2377 }
2378 else {
786e8c11 2379 DEBUG_TRIE_EXECUTE_r(
73104a1b 2380 PerlIO_printf( Perl_debug_log," - fail\n"));
786e8c11 2381 failed = 1;
73104a1b 2382 state = aho->fail[state];
07be1b83 2383 }
07be1b83 2384 }
73104a1b
KW
2385 else {
2386 /* we must be accepting here */
2387 DEBUG_TRIE_EXECUTE_r(
2388 PerlIO_printf( Perl_debug_log," - accepting\n"));
2389 failed = 1;
2390 break;
786e8c11 2391 }
73104a1b
KW
2392 } while(state);
2393 uc += len;
2394 if (failed) {
2395 if (leftmost)
2396 break;
2397 if (!state) state = 1;
07be1b83 2398 }
73104a1b
KW
2399 }
2400 if ( aho->states[ state ].wordnum ) {
2401 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2402 if (!leftmost || lpos < leftmost) {
2403 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2404 leftmost = lpos;
07be1b83
YO
2405 }
2406 }
73104a1b
KW
2407 if (leftmost) {
2408 s = (char*)leftmost;
2409 DEBUG_TRIE_EXECUTE_r({
2410 PerlIO_printf(
2411 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2412 (UV)accepted_word, (IV)(s - real_start)
2413 );
2414 });
02d5137b 2415 if (reginfo->intuit || regtry(reginfo, &s)) {
73104a1b
KW
2416 FREETMPS;
2417 LEAVE;
2418 goto got_it;
2419 }
2420 s = HOPc(s,1);
2421 DEBUG_TRIE_EXECUTE_r({
2422 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2423 });
2424 } else {
2425 DEBUG_TRIE_EXECUTE_r(
2426 PerlIO_printf( Perl_debug_log,"No match.\n"));
2427 break;
2428 }
2429 }
2430 FREETMPS;
2431 LEAVE;
2432 }
2433 break;
2434 default:
2435 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
73104a1b
KW
2436 }
2437 return 0;
2438 got_it:
2439 return s;
6eb5f6b9
JH
2440}
2441
60165aa4
DM
2442/* set RX_SAVED_COPY, RX_SUBBEG etc.
2443 * flags have same meanings as with regexec_flags() */
2444
749f4950
DM
2445static void
2446S_reg_set_capture_string(pTHX_ REGEXP * const rx,
60165aa4
DM
2447 char *strbeg,
2448 char *strend,
2449 SV *sv,
2450 U32 flags,
2451 bool utf8_target)
2452{
2453 struct regexp *const prog = ReANY(rx);
2454
60165aa4
DM
2455 if (flags & REXEC_COPY_STR) {
2456#ifdef PERL_ANY_COW
2457 if (SvCANCOW(sv)) {
2458 if (DEBUG_C_TEST) {
2459 PerlIO_printf(Perl_debug_log,
2460 "Copy on write: regexp capture, type %d\n",
2461 (int) SvTYPE(sv));
2462 }
5411a0e5
DM
2463 /* Create a new COW SV to share the match string and store
2464 * in saved_copy, unless the current COW SV in saved_copy
2465 * is valid and suitable for our purpose */
2466 if (( prog->saved_copy
2467 && SvIsCOW(prog->saved_copy)
2468 && SvPOKp(prog->saved_copy)
2469 && SvIsCOW(sv)
2470 && SvPOKp(sv)
2471 && SvPVX(sv) == SvPVX(prog->saved_copy)))
a76b0e90 2472 {
5411a0e5
DM
2473 /* just reuse saved_copy SV */
2474 if (RXp_MATCH_COPIED(prog)) {
2475 Safefree(prog->subbeg);
2476 RXp_MATCH_COPIED_off(prog);
2477 }
2478 }
2479 else {
2480 /* create new COW SV to share string */
a76b0e90
DM
2481 RX_MATCH_COPY_FREE(rx);
2482 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
a76b0e90 2483 }
5411a0e5
DM
2484 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2485 assert (SvPOKp(prog->saved_copy));
60165aa4
DM
2486 prog->sublen = strend - strbeg;
2487 prog->suboffset = 0;
2488 prog->subcoffset = 0;
2489 } else
2490#endif
2491 {
99a90e59
FC
2492 SSize_t min = 0;
2493 SSize_t max = strend - strbeg;
ea3daa5d 2494 SSize_t sublen;
60165aa4
DM
2495
2496 if ( (flags & REXEC_COPY_SKIP_POST)
e322109a 2497 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
60165aa4
DM
2498 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2499 ) { /* don't copy $' part of string */
2500 U32 n = 0;
2501 max = -1;
2502 /* calculate the right-most part of the string covered
2503 * by a capture. Due to look-ahead, this may be to
2504 * the right of $&, so we have to scan all captures */
2505 while (n <= prog->lastparen) {
2506 if (prog->offs[n].end > max)
2507 max = prog->offs[n].end;
2508 n++;
2509 }
2510 if (max == -1)
2511 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2512 ? prog->offs[0].start
2513 : 0;
2514 assert(max >= 0 && max <= strend - strbeg);
2515 }
2516
2517 if ( (flags & REXEC_COPY_SKIP_PRE)
e322109a 2518 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
60165aa4
DM
2519 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2520 ) { /* don't copy $` part of string */
2521 U32 n = 0;
2522 min = max;
2523 /* calculate the left-most part of the string covered
2524 * by a capture. Due to look-behind, this may be to
2525 * the left of $&, so we have to scan all captures */
2526 while (min && n <= prog->lastparen) {
2527 if ( prog->offs[n].start != -1
2528 && prog->offs[n].start < min)
2529 {
2530 min = prog->offs[n].start;
2531 }
2532 n++;
2533 }
2534 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2535 && min > prog->offs[0].end
2536 )
2537 min = prog->offs[0].end;
2538
2539 }
2540
2541 assert(min >= 0 && min <= max && min <= strend - strbeg);
2542 sublen = max - min;
2543
2544 if (RX_MATCH_COPIED(rx)) {
2545 if (sublen > prog->sublen)
2546 prog->subbeg =
2547 (char*)saferealloc(prog->subbeg, sublen+1);
2548 }
2549 else
2550 prog->subbeg = (char*)safemalloc(sublen+1);
2551 Copy(strbeg + min, prog->subbeg, sublen, char);
2552 prog->subbeg[sublen] = '\0';
2553 prog->suboffset = min;
2554 prog->sublen = sublen;
2555 RX_MATCH_COPIED_on(rx);
2556 }
2557 prog->subcoffset = prog->suboffset;
2558 if (prog->suboffset && utf8_target) {
2559 /* Convert byte offset to chars.
2560 * XXX ideally should only compute this if @-/@+
2561 * has been seen, a la PL_sawampersand ??? */
2562
2563 /* If there's a direct correspondence between the
2564 * string which we're matching and the original SV,
2565 * then we can use the utf8 len cache associated with
2566 * the SV. In particular, it means that under //g,
2567 * sv_pos_b2u() will use the previously cached
2568 * position to speed up working out the new length of
2569 * subcoffset, rather than counting from the start of
2570 * the string each time. This stops
2571 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2572 * from going quadratic */
2573 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
ea3daa5d
FC
2574 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2575 SV_GMAGIC|SV_CONST_RETURN);
60165aa4
DM
2576 else
2577 prog->subcoffset = utf8_length((U8*)strbeg,
2578 (U8*)(strbeg+prog->suboffset));
2579 }
2580 }
2581 else {
2582 RX_MATCH_COPY_FREE(rx);
2583 prog->subbeg = strbeg;
2584 prog->suboffset = 0;
2585 prog->subcoffset = 0;
2586 prog->sublen = strend - strbeg;
2587 }
2588}
2589
2590
2591
fae667d5 2592
6eb5f6b9
JH
2593/*
2594 - regexec_flags - match a regexp against a string
2595 */
2596I32
5aaab254 2597Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
ea3daa5d 2598 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
8fd1a950
DM
2599/* stringarg: the point in the string at which to begin matching */
2600/* strend: pointer to null at end of string */
2601/* strbeg: real beginning of string */
2602/* minend: end of match must be >= minend bytes after stringarg. */
2603/* sv: SV being matched: only used for utf8 flag, pos() etc; string
2604 * itself is accessed via the pointers above */
2605/* data: May be used for some additional optimizations.
d058ec57 2606 Currently unused. */
a340edde 2607/* flags: For optimizations. See REXEC_* in regexp.h */
8fd1a950 2608
6eb5f6b9 2609{
8d919b0a 2610 struct regexp *const prog = ReANY(rx);
5aaab254 2611 char *s;
eb578fdb 2612 regnode *c;
03c83e26 2613 char *startpos;
ea3daa5d
FC
2614 SSize_t minlen; /* must match at least this many chars */
2615 SSize_t dontbother = 0; /* how many characters not to try at end */
f2ed9b32 2616 const bool utf8_target = cBOOL(DO_UTF8(sv));
2757e526 2617 I32 multiline;
f8fc2ecf 2618 RXi_GET_DECL(prog,progi);
02d5137b
DM
2619 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2620 regmatch_info *const reginfo = &reginfo_buf;
e9105d30 2621 regexp_paren_pair *swap = NULL;
006f26b2 2622 I32 oldsave;
a3621e74
YO
2623 GET_RE_DEBUG_FLAGS_DECL;
2624
7918f24d 2625 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
9d4ba2ae 2626 PERL_UNUSED_ARG(data);
6eb5f6b9
JH
2627
2628 /* Be paranoid... */
03c83e26 2629 if (prog == NULL || stringarg == NULL) {
6eb5f6b9 2630 Perl_croak(aTHX_ "NULL regexp parameter");
6eb5f6b9
JH
2631 }
2632
6c3fea77 2633 DEBUG_EXECUTE_r(
03c83e26 2634 debug_start_match(rx, utf8_target, stringarg, strend,
6c3fea77
DM
2635 "Matching");
2636 );
8adc0f72 2637
b342a604
DM
2638 startpos = stringarg;
2639
58430ea8 2640 if (prog->intflags & PREGf_GPOS_SEEN) {
d307c076
DM
2641 MAGIC *mg;
2642
fef7148b
DM
2643 /* set reginfo->ganch, the position where \G can match */
2644
2645 reginfo->ganch =
2646 (flags & REXEC_IGNOREPOS)
2647 ? stringarg /* use start pos rather than pos() */
2648 : (sv && (mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
25fdce4a
FC
2649 /* Defined pos(): */
2650 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
fef7148b
DM
2651 : strbeg; /* pos() not defined; use start of string */
2652
2653 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
7b0eb0b8 2654 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
fef7148b 2655
03c83e26
DM
2656 /* in the presence of \G, we may need to start looking earlier in
2657 * the string than the suggested start point of stringarg:
0b2c2a84 2658 * if prog->gofs is set, then that's a known, fixed minimum
03c83e26
DM
2659 * offset, such as
2660 * /..\G/: gofs = 2
2661 * /ab|c\G/: gofs = 1
2662 * or if the minimum offset isn't known, then we have to go back
2663 * to the start of the string, e.g. /w+\G/
2664 */
2bfbe302 2665
8e1490ee 2666 if (prog->intflags & PREGf_ANCH_GPOS) {
2bfbe302
DM
2667 startpos = reginfo->ganch - prog->gofs;
2668 if (startpos <
2669 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2670 {
2671 DEBUG_r(PerlIO_printf(Perl_debug_log,
2672 "fail: ganch-gofs before earliest possible start\n"));
2673 return 0;
2674 }
2675 }
2676 else if (prog->gofs) {
b342a604
DM
2677 if (startpos - prog->gofs < strbeg)
2678 startpos = strbeg;
2679 else
2680 startpos -= prog->gofs;
03c83e26 2681 }
58430ea8 2682 else if (prog->intflags & PREGf_GPOS_FLOAT)
b342a604 2683 startpos = strbeg;
03c83e26
DM
2684 }
2685
2686 minlen = prog->minlen;
b342a604 2687 if ((startpos + minlen) > strend || startpos < strbeg) {
03c83e26
DM
2688 DEBUG_r(PerlIO_printf(Perl_debug_log,
2689 "Regex match can't succeed, so not even tried\n"));
2690 return 0;
2691 }
2692
63a3746a
DM
2693 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2694 * which will call destuctors to reset PL_regmatch_state, free higher
2695 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2696 * regmatch_info_aux_eval */
2697
2698 oldsave = PL_savestack_ix;
2699
dfa77d06
DM
2700 s = startpos;
2701
e322109a 2702 if ((prog->extflags & RXf_USE_INTUIT)
7fadf4a7
DM
2703 && !(flags & REXEC_CHECKED))
2704 {
dfa77d06 2705 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
7fadf4a7 2706 flags, NULL);
dfa77d06 2707 if (!s)
7fadf4a7
DM
2708 return 0;
2709
e322109a 2710 if (prog->extflags & RXf_CHECK_ALL) {
7fadf4a7
DM
2711 /* we can match based purely on the result of INTUIT.
2712 * Set up captures etc just for $& and $-[0]
2713 * (an intuit-only match wont have $1,$2,..) */
2714 assert(!prog->nparens);
d5e7783a
DM
2715
2716 /* s/// doesn't like it if $& is earlier than where we asked it to
2717 * start searching (which can happen on something like /.\G/) */
2718 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2719 && (s < stringarg))
2720 {
2721 /* this should only be possible under \G */
58430ea8 2722 assert(prog->intflags & PREGf_GPOS_SEEN);
d5e7783a
DM
2723 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2724 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2725 goto phooey;
2726 }
2727
7fadf4a7
DM
2728 /* match via INTUIT shouldn't have any captures.
2729 * Let @-, @+, $^N know */
2730 prog->lastparen = prog->lastcloseparen = 0;
2731 RX_MATCH_UTF8_set(rx, utf8_target);
3ff69bd6
DM
2732 prog->offs[0].start = s - strbeg;
2733 prog->offs[0].end = utf8_target
2734 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2735 : s - strbeg + prog->minlenret;
7fadf4a7 2736 if ( !(flags & REXEC_NOT_FIRST) )
749f4950 2737 S_reg_set_capture_string(aTHX_ rx,
7fadf4a7
DM
2738 strbeg, strend,
2739 sv, flags, utf8_target);
2740
7fadf4a7
DM
2741 return 1;
2742 }
2743 }
2744
6c3fea77 2745 multiline = prog->extflags & RXf_PMf_MULTILINE;
1de06328 2746
dfa77d06 2747 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
a3621e74 2748 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
a72c7584
JH
2749 "String too short [regexec_flags]...\n"));
2750 goto phooey;
1aa99e6b 2751 }
1de06328 2752
6eb5f6b9 2753 /* Check validity of program. */
f8fc2ecf 2754 if (UCHARAT(progi->program) != REG_MAGIC) {
6eb5f6b9
JH
2755 Perl_croak(aTHX_ "corrupted regexp program");
2756 }
2757
1738e041 2758 RX_MATCH_TAINTED_off(rx);
ab4e48c1 2759 RX_MATCH_UTF8_set(rx, utf8_target);
1738e041 2760
6c3fea77
DM
2761 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2762 reginfo->intuit = 0;
2763 reginfo->is_utf8_target = cBOOL(utf8_target);
02d5137b
DM
2764 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2765 reginfo->warned = FALSE;
9d9163fb 2766 reginfo->strbeg = strbeg;
02d5137b 2767 reginfo->sv = sv;
1cb48e53 2768 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
220db18a 2769 reginfo->strend = strend;
6eb5f6b9 2770 /* see how far we have to get to not match where we matched before */
fe3974be 2771 reginfo->till = stringarg + minend;
6eb5f6b9 2772
60779a30 2773 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
82c23608
FC
2774 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2775 S_cleanup_regmatch_info_aux has executed (registered by
2776 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2777 magic belonging to this SV.
2778 Not newSVsv, either, as it does not COW.
2779 */
2780 reginfo->sv = newSV(0);
4cba5ac0 2781 SvSetSV_nosteal(reginfo->sv, sv);
82c23608
FC
2782 SAVEFREESV(reginfo->sv);
2783 }
2784
331b2dcc
DM
2785 /* reserve next 2 or 3 slots in PL_regmatch_state:
2786 * slot N+0: may currently be in use: skip it
2787 * slot N+1: use for regmatch_info_aux struct
2788 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2789 * slot N+3: ready for use by regmatch()
2790 */
bf2039a9 2791
331b2dcc
DM
2792 {
2793 regmatch_state *old_regmatch_state;
2794 regmatch_slab *old_regmatch_slab;
2795 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2796
2797 /* on first ever match, allocate first slab */
2798 if (!PL_regmatch_slab) {
2799 Newx(PL_regmatch_slab, 1, regmatch_slab);
2800 PL_regmatch_slab->prev = NULL;
2801 PL_regmatch_slab->next = NULL;
2802 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2803 }
bf2039a9 2804
331b2dcc
DM
2805 old_regmatch_state = PL_regmatch_state;
2806 old_regmatch_slab = PL_regmatch_slab;
bf2039a9 2807
331b2dcc
DM
2808 for (i=0; i <= max; i++) {
2809 if (i == 1)
2810 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2811 else if (i ==2)
2812 reginfo->info_aux_eval =
2813 reginfo->info_aux->info_aux_eval =
2814 &(PL_regmatch_state->u.info_aux_eval);
bf2039a9 2815
331b2dcc
DM
2816 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2817 PL_regmatch_state = S_push_slab(aTHX);
2818 }
bf2039a9 2819
331b2dcc
DM
2820 /* note initial PL_regmatch_state position; at end of match we'll
2821 * pop back to there and free any higher slabs */
bf2039a9 2822
331b2dcc
DM
2823 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
2824 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
2ac8ff4b 2825 reginfo->info_aux->poscache = NULL;
bf2039a9 2826
331b2dcc 2827 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
bf2039a9 2828
331b2dcc
DM
2829 if ((prog->extflags & RXf_EVAL_SEEN))
2830 S_setup_eval_state(aTHX_ reginfo);
2831 else
2832 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
bf2039a9 2833 }
d3aa529c 2834
6eb5f6b9 2835 /* If there is a "must appear" string, look for it. */
6eb5f6b9 2836
288b8c02 2837 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
e9105d30
GG
2838 /* We have to be careful. If the previous successful match
2839 was from this regex we don't want a subsequent partially
2840 successful match to clobber the old results.
2841 So when we detect this possibility we add a swap buffer
d8da0584
KW
2842 to the re, and switch the buffer each match. If we fail,
2843 we switch it back; otherwise we leave it swapped.
e9105d30
GG
2844 */
2845 swap = prog->offs;
2846 /* do we need a save destructor here for eval dies? */
2847 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
495f47a5
DM
2848 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2849 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2850 PTR2UV(prog),
2851 PTR2UV(swap),
2852 PTR2UV(prog->offs)
2853 ));
c74340f9 2854 }
6eb5f6b9 2855
0fa70a06
DM
2856 /* Simplest case: anchored match need be tried only once, or with
2857 * MBOL, only at the beginning of each line.
2858 *
2859 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
2860 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
2861 * match at the start of the string then it won't match anywhere else
2862 * either; while with /.*.../, if it doesn't match at the beginning,
2863 * the earliest it could match is at the start of the next line */
2864
8e1490ee 2865 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
0fa70a06
DM
2866 char *end;
2867
2868 if (regtry(reginfo, &s))
6eb5f6b9 2869 goto got_it;
0fa70a06
DM
2870
2871 if (!(prog->intflags & PREGf_ANCH_MBOL))
2872 goto phooey;
2873
2874 /* didn't match at start, try at other newline positions */
2875
2876 if (minlen)
2877 dontbother = minlen - 1;
2878 end = HOP3c(strend, -dontbother, strbeg) - 1;
2879
2880 /* skip to next newline */
2881
2882 while (s <= end) { /* note it could be possible to match at the end of the string */
2883 /* NB: newlines are the same in unicode as they are in latin */
2884 if (*s++ != '\n')
2885 continue;
2886 if (prog->check_substr || prog->check_utf8) {
2887 /* note that with PREGf_IMPLICIT, intuit can only fail
2888 * or return the start position, so it's of limited utility.
2889 * Nevertheless, I made the decision that the potential for
2890 * quick fail was still worth it - DAPM */
2891 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
2892 if (!s)
2893 goto phooey;
2894 }
2895 if (regtry(reginfo, &s))
2896 goto got_it;
2897 }
2898 goto phooey;
2899 } /* end anchored search */
2900
2901 if (prog->intflags & PREGf_ANCH_GPOS)
f9f4320a 2902 {
a8430a8b
YO
2903 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
2904 assert(prog->intflags & PREGf_GPOS_SEEN);
2bfbe302
DM
2905 /* For anchored \G, the only position it can match from is
2906 * (ganch-gofs); we already set startpos to this above; if intuit
2907 * moved us on from there, we can't possibly succeed */
2908 assert(startpos == reginfo->ganch - prog->gofs);
2909 if (s == startpos && regtry(reginfo, &s))
6eb5f6b9
JH
2910 goto got_it;
2911 goto phooey;
2912 }
2913
2914 /* Messy cases: unanchored match. */
bbe252da 2915 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
6eb5f6b9 2916 /* we have /x+whatever/ */
984e6dd1 2917 /* it must be a one character string (XXXX Except is_utf8_pat?) */
33b8afdf 2918 char ch;
bf93d4cc
GS
2919#ifdef DEBUGGING
2920 int did_match = 0;
2921#endif
f2ed9b32 2922 if (utf8_target) {
7e0d5ad7
KW
2923 if (! prog->anchored_utf8) {
2924 to_utf8_substr(prog);
2925 }
2926 ch = SvPVX_const(prog->anchored_utf8)[0];
4cadc6a9 2927 REXEC_FBC_SCAN(
6eb5f6b9 2928 if (*s == ch) {
a3621e74 2929 DEBUG_EXECUTE_r( did_match = 1 );
02d5137b 2930 if (regtry(reginfo, &s)) goto got_it;
6eb5f6b9
JH
2931 s += UTF8SKIP(s);
2932 while (s < strend && *s == ch)
2933 s += UTF8SKIP(s);
2934 }
4cadc6a9 2935 );
7e0d5ad7 2936
6eb5f6b9
JH
2937 }
2938 else {
7e0d5ad7
KW
2939 if (! prog->anchored_substr) {
2940 if (! to_byte_substr(prog)) {
6b54ddc5 2941 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
2942 }
2943 }
2944 ch = SvPVX_const(prog->anchored_substr)[0];
4cadc6a9 2945 REXEC_FBC_SCAN(
6eb5f6b9 2946 if (*s == ch) {
a3621e74 2947 DEBUG_EXECUTE_r( did_match = 1 );
02d5137b 2948 if (regtry(reginfo, &s)) goto got_it;
6eb5f6b9
JH
2949 s++;
2950 while (s < strend && *s == ch)
2951 s++;
2952 }
4cadc6a9 2953 );
6eb5f6b9 2954 }
a3621e74 2955 DEBUG_EXECUTE_r(if (!did_match)
bf93d4cc 2956 PerlIO_printf(Perl_debug_log,
b7953727
JH
2957 "Did not find anchored character...\n")
2958 );
6eb5f6b9 2959 }
a0714e2c
SS
2960 else if (prog->anchored_substr != NULL
2961 || prog->anchored_utf8 != NULL
2962 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
33b8afdf
JH
2963 && prog->float_max_offset < strend - s)) {
2964 SV *must;
ea3daa5d
FC
2965 SSize_t back_max;
2966 SSize_t back_min;
33b8afdf 2967 char *last;
6eb5f6b9 2968 char *last1; /* Last position checked before */
bf93d4cc
GS
2969#ifdef DEBUGGING
2970 int did_match = 0;
2971#endif
33b8afdf 2972 if (prog->anchored_substr || prog->anchored_utf8) {
7e0d5ad7
KW
2973 if (utf8_target) {
2974 if (! prog->anchored_utf8) {
2975 to_utf8_substr(prog);
2976 }
2977 must = prog->anchored_utf8;
2978 }
2979 else {
2980 if (! prog->anchored_substr) {
2981 if (! to_byte_substr(prog)) {
6b54ddc5 2982 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
2983 }
2984 }
2985 must = prog->anchored_substr;
2986 }
33b8afdf
JH
2987 back_max = back_min = prog->anchored_offset;
2988 } else {
7e0d5ad7
KW
2989 if (utf8_target) {
2990 if (! prog->float_utf8) {
2991 to_utf8_substr(prog);
2992 }
2993 must = prog->float_utf8;
2994 }
2995 else {
2996 if (! prog->float_substr) {
2997 if (! to_byte_substr(prog)) {
6b54ddc5 2998 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
2999 }
3000 }
3001 must = prog->float_substr;
3002 }
33b8afdf
JH
3003 back_max = prog->float_max_offset;
3004 back_min = prog->float_min_offset;
3005 }
1de06328 3006
1de06328
YO
3007 if (back_min<0) {
3008 last = strend;
3009 } else {
3010 last = HOP3c(strend, /* Cannot start after this */
ea3daa5d 3011 -(SSize_t)(CHR_SVLEN(must)
1de06328
YO
3012 - (SvTAIL(must) != 0) + back_min), strbeg);
3013 }
9d9163fb 3014 if (s > reginfo->strbeg)
6eb5f6b9
JH
3015 last1 = HOPc(s, -1);
3016 else
3017 last1 = s - 1; /* bogus */
3018
a0288114 3019 /* XXXX check_substr already used to find "s", can optimize if
6eb5f6b9 3020 check_substr==must. */
bf05793b 3021 dontbother = 0;
6eb5f6b9
JH
3022 strend = HOPc(strend, -dontbother);
3023 while ( (s <= last) &&
e50d57d4 3024 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
9041c2e3 3025 (unsigned char*)strend, must,
c33e64f0 3026 multiline ? FBMrf_MULTILINE : 0)) ) {
a3621e74 3027 DEBUG_EXECUTE_r( did_match = 1 );
6eb5f6b9
JH
3028 if (HOPc(s, -back_max) > last1) {
3029 last1 = HOPc(s, -back_min);
3030 s = HOPc(s, -back_max);
3031 }
3032 else {
9d9163fb
DM
3033 char * const t = (last1 >= reginfo->strbeg)
3034 ? HOPc(last1, 1) : last1 + 1;
6eb5f6b9
JH
3035
3036 last1 = HOPc(s, -back_min);
52657f30 3037 s = t;
6eb5f6b9 3038 }
f2ed9b32 3039 if (utf8_target) {
6eb5f6b9 3040 while (s <= last1) {
02d5137b 3041 if (regtry(reginfo, &s))
6eb5f6b9 3042 goto got_it;
7016d6eb
DM
3043 if (s >= last1) {
3044 s++; /* to break out of outer loop */
3045 break;
3046 }
3047 s += UTF8SKIP(s);
6eb5f6b9
JH
3048 }
3049 }
3050 else {
3051 while (s <= last1) {
02d5137b 3052 if (regtry(reginfo, &s))
6eb5f6b9
JH
3053 goto got_it;
3054 s++;
3055 }
3056 }
3057 }
ab3bbdeb 3058 DEBUG_EXECUTE_r(if (!did_match) {
f2ed9b32 3059 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
ab3bbdeb
YO
3060 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3061 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
33b8afdf 3062 ((must == prog->anchored_substr || must == prog->anchored_utf8)
bf93d4cc 3063 ? "anchored" : "floating"),
ab3bbdeb
YO
3064 quoted, RE_SV_TAIL(must));
3065 });
6eb5f6b9
JH
3066 goto phooey;
3067 }
f8fc2ecf 3068 else if ( (c = progi->regstclass) ) {
f14c76ed 3069 if (minlen) {
f8fc2ecf 3070 const OPCODE op = OP(progi->regstclass);
66e933ab 3071 /* don't bother with what can't match */
786e8c11 3072 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
f14c76ed
RGS
3073 strend = HOPc(strend, -(minlen - 1));
3074 }
a3621e74 3075 DEBUG_EXECUTE_r({
be8e71aa 3076 SV * const prop = sv_newmortal();
8b9781c9 3077 regprop(prog, prop, c, reginfo, NULL);
0df25f3d 3078 {
f2ed9b32 3079 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
ab3bbdeb 3080 s,strend-s,60);
0df25f3d 3081 PerlIO_printf(Perl_debug_log,
1c8f8eb1 3082 "Matching stclass %.*s against %s (%d bytes)\n",
e4f74956 3083 (int)SvCUR(prop), SvPVX_const(prop),
ab3bbdeb 3084 quoted, (int)(strend - s));
0df25f3d 3085 }
ffc61ed2 3086 });
f9176b44 3087 if (find_byclass(prog, c, s, strend, reginfo))
6eb5f6b9 3088 goto got_it;
07be1b83 3089 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
d6a28714
JH
3090 }
3091 else {
3092 dontbother = 0;
a0714e2c 3093 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
33b8afdf 3094 /* Trim the end. */
6af40bd7 3095 char *last= NULL;
33b8afdf 3096 SV* float_real;
c33e64f0
FC
3097 STRLEN len;
3098 const char *little;
33b8afdf 3099
7e0d5ad7
KW
3100 if (utf8_target) {
3101 if (! prog->float_utf8) {
3102 to_utf8_substr(prog);
3103 }
3104 float_real = prog->float_utf8;
3105 }
3106 else {
3107 if (! prog->float_substr) {
3108 if (! to_byte_substr(prog)) {
6b54ddc5 3109 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
3110 }
3111 }
3112 float_real = prog->float_substr;
3113 }
d6a28714 3114
c33e64f0
FC
3115 little = SvPV_const(float_real, len);
3116 if (SvTAIL(float_real)) {
7f18ad16
KW
3117 /* This means that float_real contains an artificial \n on
3118 * the end due to the presence of something like this:
3119 * /foo$/ where we can match both "foo" and "foo\n" at the
3120 * end of the string. So we have to compare the end of the
3121 * string first against the float_real without the \n and
3122 * then against the full float_real with the string. We
3123 * have to watch out for cases where the string might be
3124 * smaller than the float_real or the float_real without
3125 * the \n. */
1a13b075
YO
3126 char *checkpos= strend - len;
3127 DEBUG_OPTIMISE_r(
3128 PerlIO_printf(Perl_debug_log,
3129 "%sChecking for float_real.%s\n",
3130 PL_colors[4], PL_colors[5]));
3131 if (checkpos + 1 < strbeg) {
7f18ad16
KW
3132 /* can't match, even if we remove the trailing \n
3133 * string is too short to match */
1a13b075
YO
3134 DEBUG_EXECUTE_r(
3135 PerlIO_printf(Perl_debug_log,
3136 "%sString shorter than required trailing substring, cannot match.%s\n",
3137 PL_colors[4], PL_colors[5]));
3138 goto phooey;
3139 } else if (memEQ(checkpos + 1, little, len - 1)) {
7f18ad16
KW
3140 /* can match, the end of the string matches without the
3141 * "\n" */
1a13b075
YO
3142 last = checkpos + 1;
3143 } else if (checkpos < strbeg) {
7f18ad16
KW
3144 /* cant match, string is too short when the "\n" is
3145 * included */
1a13b075
YO
3146 DEBUG_EXECUTE_r(
3147 PerlIO_printf(Perl_debug_log,
3148 "%sString does not contain required trailing substring, cannot match.%s\n",
3149 PL_colors[4], PL_colors[5]));
3150 goto phooey;
3151 } else if (!multiline) {
7f18ad16
KW
3152 /* non multiline match, so compare with the "\n" at the
3153 * end of the string */
1a13b075
YO
3154 if (memEQ(checkpos, little, len)) {
3155 last= checkpos;
3156 } else {
3157 DEBUG_EXECUTE_r(
3158 PerlIO_printf(Perl_debug_log,
3159 "%sString does not contain required trailing substring, cannot match.%s\n",
3160 PL_colors[4], PL_colors[5]));
3161 goto phooey;
3162 }
3163 } else {
7f18ad16
KW
3164 /* multiline match, so we have to search for a place
3165 * where the full string is located */
d6a28714 3166 goto find_last;
1a13b075 3167 }
c33e64f0 3168 } else {
d6a28714 3169 find_last:
9041c2e3 3170 if (len)
d6a28714 3171 last = rninstr(s, strend, little, little + len);
b8c5462f 3172 else
a0288114 3173 last = strend; /* matching "$" */
b8c5462f 3174 }
6af40bd7 3175 if (!last) {
7f18ad16
KW
3176 /* at one point this block contained a comment which was
3177 * probably incorrect, which said that this was a "should not
3178 * happen" case. Even if it was true when it was written I am
3179 * pretty sure it is not anymore, so I have removed the comment
3180 * and replaced it with this one. Yves */
6bda09f9
YO
3181 DEBUG_EXECUTE_r(
3182 PerlIO_printf(Perl_debug_log,
b729e729
YO
3183 "%sString does not contain required substring, cannot match.%s\n",
3184 PL_colors[4], PL_colors[5]
6af40bd7
YO
3185 ));
3186 goto phooey;
bf93d4cc 3187 }
d6a28714
JH
3188 dontbother = strend - last + prog->float_min_offset;
3189 }
3190 if (minlen && (dontbother < minlen))
3191 dontbother = minlen - 1;
3192 strend -= dontbother; /* this one's always in bytes! */
3193 /* We don't know much -- general case. */
f2ed9b32 3194 if (utf8_target) {
d6a28714 3195 for (;;) {
02d5137b 3196 if (regtry(reginfo, &s))
d6a28714
JH
3197 goto got_it;
3198 if (s >= strend)
3199 break;
b8c5462f 3200 s += UTF8SKIP(s);
d6a28714
JH
3201 };
3202 }
3203 else {
3204 do {
02d5137b 3205 if (regtry(reginfo, &s))
d6a28714
JH
3206 goto got_it;
3207 } while (s++ < strend);
3208 }
3209 }
3210
3211 /* Failure. */
3212 goto phooey;
3213
7b52d656 3214 got_it:
d5e7783a
DM
3215 /* s/// doesn't like it if $& is earlier than where we asked it to
3216 * start searching (which can happen on something like /.\G/) */
3217 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3218 && (prog->offs[0].start < stringarg - strbeg))
3219 {
3220 /* this should only be possible under \G */
58430ea8 3221 assert(prog->intflags & PREGf_GPOS_SEEN);
d5e7783a
DM
3222 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3223 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3224 goto phooey;
3225 }
3226
495f47a5
DM
3227 DEBUG_BUFFERS_r(
3228 if (swap)
3229 PerlIO_printf(Perl_debug_log,
3230 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3231 PTR2UV(prog),
3232 PTR2UV(swap)
3233 );
3234 );
e9105d30 3235 Safefree(swap);
d6a28714 3236
bf2039a9
DM
3237 /* clean up; this will trigger destructors that will free all slabs
3238 * above the current one, and cleanup the regmatch_info_aux
3239 * and regmatch_info_aux_eval sructs */
8adc0f72 3240
006f26b2
DM
3241 LEAVE_SCOPE(oldsave);
3242
5daac39c
NC
3243 if (RXp_PAREN_NAMES(prog))
3244 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
d6a28714
JH
3245
3246 /* make sure $`, $&, $', and $digit will work later */
60165aa4 3247 if ( !(flags & REXEC_NOT_FIRST) )
749f4950 3248 S_reg_set_capture_string(aTHX_ rx,
60165aa4
DM
3249 strbeg, reginfo->strend,
3250 sv, flags, utf8_target);
9041c2e3 3251
d6a28714
JH
3252 return 1;
3253
7b52d656 3254 phooey:
a3621e74 3255 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
e4584336 3256 PL_colors[4], PL_colors[5]));
8adc0f72 3257
bf2039a9
DM
3258 /* clean up; this will trigger destructors that will free all slabs
3259 * above the current one, and cleanup the regmatch_info_aux
3260 * and regmatch_info_aux_eval sructs */
8adc0f72 3261
006f26b2
DM
3262 LEAVE_SCOPE(oldsave);
3263
e9105d30 3264 if (swap) {
c74340f9 3265 /* we failed :-( roll it back */
495f47a5
DM
3266 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3267 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3268 PTR2UV(prog),
3269 PTR2UV(prog->offs),
3270 PTR2UV(swap)
3271 ));
e9105d30
GG
3272 Safefree(prog->offs);
3273 prog->offs = swap;
3274 }
d6a28714
JH
3275 return 0;
3276}
3277
6bda09f9 3278
b3d298be 3279/* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
ec43f78b 3280 * Do inc before dec, in case old and new rex are the same */
baa60164 3281#define SET_reg_curpm(Re2) \
bf2039a9 3282 if (reginfo->info_aux_eval) { \
ec43f78b
DM
3283 (void)ReREFCNT_inc(Re2); \
3284 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3285 PM_SETRE((PL_reg_curpm), (Re2)); \
3286 }
3287
3288
d6a28714
JH
3289/*
3290 - regtry - try match at specific point
3291 */
3292STATIC I32 /* 0 failure, 1 success */
f73aaa43 3293S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
d6a28714 3294{
d6a28714 3295 CHECKPOINT lastcp;
288b8c02 3296 REGEXP *const rx = reginfo->prog;
8d919b0a 3297 regexp *const prog = ReANY(rx);
99a90e59 3298 SSize_t result;
f8fc2ecf 3299 RXi_GET_DECL(prog,progi);
a3621e74 3300 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
3301
3302 PERL_ARGS_ASSERT_REGTRY;
3303
24b23f37 3304 reginfo->cutpoint=NULL;
d6a28714 3305
9d9163fb 3306 prog->offs[0].start = *startposp - reginfo->strbeg;
d6a28714 3307 prog->lastparen = 0;
03994de8 3308 prog->lastcloseparen = 0;
d6a28714
JH
3309
3310 /* XXXX What this code is doing here?!!! There should be no need
b93070ed 3311 to do this again and again, prog->lastparen should take care of
3dd2943c 3312 this! --ilya*/
dafc8851
JH
3313
3314 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3315 * Actually, the code in regcppop() (which Ilya may be meaning by
b93070ed 3316 * prog->lastparen), is not needed at all by the test suite
225593e1
DM
3317 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3318 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3319 * Meanwhile, this code *is* needed for the
daf18116
JH
3320 * above-mentioned test suite tests to succeed. The common theme
3321 * on those tests seems to be returning null fields from matches.
225593e1 3322 * --jhi updated by dapm */
dafc8851 3323#if 1
d6a28714 3324 if (prog->nparens) {
b93070ed 3325 regexp_paren_pair *pp = prog->offs;
eb578fdb 3326 I32 i;
b93070ed 3327 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
f0ab9afb
NC
3328 ++pp;
3329 pp->start = -1;
3330 pp->end = -1;
d6a28714
JH
3331 }
3332 }
dafc8851 3333#endif
02db2b7b 3334 REGCP_SET(lastcp);
f73aaa43
DM
3335 result = regmatch(reginfo, *startposp, progi->program + 1);
3336 if (result != -1) {
3337 prog->offs[0].end = result;
d6a28714
JH
3338 return 1;
3339 }
24b23f37 3340 if (reginfo->cutpoint)
f73aaa43 3341 *startposp= reginfo->cutpoint;
02db2b7b 3342 REGCP_UNWIND(lastcp);
d6a28714
JH
3343 return 0;
3344}
3345
02db2b7b 3346
8ba1375e
MJD
3347#define sayYES goto yes
3348#define sayNO goto no
262b90c4 3349#define sayNO_SILENT goto no_silent
8ba1375e 3350
f9f4320a
YO
3351/* we dont use STMT_START/END here because it leads to
3352 "unreachable code" warnings, which are bogus, but distracting. */
3353#define CACHEsayNO \
c476f425 3354 if (ST.cache_mask) \
2ac8ff4b 3355 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
f9f4320a 3356 sayNO
3298f257 3357
a3621e74 3358/* this is used to determine how far from the left messages like
265c4333
YO
3359 'failed...' are printed. It should be set such that messages
3360 are inline with the regop output that created them.
a3621e74 3361*/
265c4333 3362#define REPORT_CODE_OFF 32
a3621e74
YO
3363
3364
40a82448
DM
3365#define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3366#define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
79a2a0e8
KW
3367#define CHRTEST_NOT_A_CP_1 -999
3368#define CHRTEST_NOT_A_CP_2 -998
9e137952 3369
5d9a96ca
DM
3370/* grab a new slab and return the first slot in it */
3371
3372STATIC regmatch_state *
3373S_push_slab(pTHX)
3374{
a35a87e7 3375#if PERL_VERSION < 9 && !defined(PERL_CORE)
54df2634
NC
3376 dMY_CXT;
3377#endif
5d9a96ca
DM
3378 regmatch_slab *s = PL_regmatch_slab->next;
3379 if (!s) {
3380 Newx(s, 1, regmatch_slab);
3381 s->prev = PL_regmatch_slab;
3382 s->next = NULL;
3383 PL_regmatch_slab->next = s;
3384 }
3385 PL_regmatch_slab = s;
86545054 3386 return SLAB_FIRST(s);
5d9a96ca 3387}
5b47454d 3388
95b24440 3389
40a82448
DM
3390/* push a new state then goto it */
3391
4d5016e5
DM
3392#define PUSH_STATE_GOTO(state, node, input) \
3393 pushinput = input; \
40a82448
DM
3394 scan = node; \
3395 st->resume_state = state; \
3396 goto push_state;
3397
3398/* push a new state with success backtracking, then goto it */
3399
4d5016e5
DM
3400#define PUSH_YES_STATE_GOTO(state, node, input) \
3401 pushinput = input; \
40a82448
DM
3402 scan = node; \
3403 st->resume_state = state; \
3404 goto push_yes_state;
3405
aa283a38 3406
aa283a38 3407
4d5016e5 3408
d6a28714 3409/*
95b24440 3410
bf1f174e
DM
3411regmatch() - main matching routine
3412
3413This is basically one big switch statement in a loop. We execute an op,
3414set 'next' to point the next op, and continue. If we come to a point which
3415we may need to backtrack to on failure such as (A|B|C), we push a
3416backtrack state onto the backtrack stack. On failure, we pop the top
3417state, and re-enter the loop at the state indicated. If there are no more
3418states to pop, we return failure.
3419
3420Sometimes we also need to backtrack on success; for example /A+/, where
3421after successfully matching one A, we need to go back and try to
3422match another one; similarly for lookahead assertions: if the assertion
3423completes successfully, we backtrack to the state just before the assertion
3424and then carry on. In these cases, the pushed state is marked as
3425'backtrack on success too'. This marking is in fact done by a chain of
3426pointers, each pointing to the previous 'yes' state. On success, we pop to
3427the nearest yes state, discarding any intermediate failure-only states.
3428Sometimes a yes state is pushed just to force some cleanup code to be
3429called at the end of a successful match or submatch; e.g. (??{$re}) uses
3430it to free the inner regex.
3431
3432Note that failure backtracking rewinds the cursor position, while
3433success backtracking leaves it alone.
3434
3435A pattern is complete when the END op is executed, while a subpattern
3436such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3437ops trigger the "pop to last yes state if any, otherwise return true"
3438behaviour.
3439
3440A common convention in this function is to use A and B to refer to the two
3441subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3442the subpattern to be matched possibly multiple times, while B is the entire
3443rest of the pattern. Variable and state names reflect this convention.
3444
3445The states in the main switch are the union of ops and failure/success of
3446substates associated with with that op. For example, IFMATCH is the op
3447that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3448'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3449successfully matched A and IFMATCH_A_fail is a state saying that we have
3450just failed to match A. Resume states always come in pairs. The backtrack
3451state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3452at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3453on success or failure.
3454
3455The struct that holds a backtracking state is actually a big union, with
3456one variant for each major type of op. The variable st points to the
3457top-most backtrack struct. To make the code clearer, within each
3458block of code we #define ST to alias the relevant union.
3459
3460Here's a concrete example of a (vastly oversimplified) IFMATCH
3461implementation:
3462
3463 switch (state) {
3464 ....
3465
3466#define ST st->u.ifmatch
3467
3468 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3469 ST.foo = ...; // some state we wish to save
95b24440 3470 ...
bf1f174e
DM
3471 // push a yes backtrack state with a resume value of
3472 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3473 // first node of A:
4d5016e5 3474 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
bf1f174e
DM
3475 // NOTREACHED
3476
3477 case IFMATCH_A: // we have successfully executed A; now continue with B
3478 next = B;
3479 bar = ST.foo; // do something with the preserved value
3480 break;
3481
3482 case IFMATCH_A_fail: // A failed, so the assertion failed
3483 ...; // do some housekeeping, then ...
3484 sayNO; // propagate the failure
3485
3486#undef ST
95b24440 3487
bf1f174e
DM
3488 ...
3489 }
95b24440 3490
bf1f174e
DM
3491For any old-timers reading this who are familiar with the old recursive
3492approach, the code above is equivalent to:
95b24440 3493
bf1f174e
DM
3494 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3495 {
3496 int foo = ...
95b24440 3497 ...
bf1f174e
DM
3498 if (regmatch(A)) {
3499 next = B;
3500 bar = foo;
3501 break;
95b24440 3502 }
bf1f174e
DM
3503 ...; // do some housekeeping, then ...
3504 sayNO; // propagate the failure
95b24440 3505 }
bf1f174e
DM
3506
3507The topmost backtrack state, pointed to by st, is usually free. If you
3508want to claim it, populate any ST.foo fields in it with values you wish to
3509save, then do one of
3510
4d5016e5
DM
3511 PUSH_STATE_GOTO(resume_state, node, newinput);
3512 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
bf1f174e
DM
3513
3514which sets that backtrack state's resume value to 'resume_state', pushes a
3515new free entry to the top of the backtrack stack, then goes to 'node'.
3516On backtracking, the free slot is popped, and the saved state becomes the
3517new free state. An ST.foo field in this new top state can be temporarily
3518accessed to retrieve values, but once the main loop is re-entered, it
3519becomes available for reuse.
3520
3521Note that the depth of the backtrack stack constantly increases during the
3522left-to-right execution of the pattern, rather than going up and down with
3523the pattern nesting. For example the stack is at its maximum at Z at the
3524end of the pattern, rather than at X in the following:
3525
3526 /(((X)+)+)+....(Y)+....Z/
3527
3528The only exceptions to this are lookahead/behind assertions and the cut,
3529(?>A), which pop all the backtrack states associated with A before
3530continuing.
3531
486ec47a 3532Backtrack state structs are allocated in slabs of about 4K in size.
bf1f174e
DM
3533PL_regmatch_state and st always point to the currently active state,
3534and PL_regmatch_slab points to the slab currently containing
3535PL_regmatch_state. The first time regmatch() is called, the first slab is
3536allocated, and is never freed until interpreter destruction. When the slab
3537is full, a new one is allocated and chained to the end. At exit from
3538regmatch(), slabs allocated since entry are freed.
3539
3540*/
95b24440 3541
40a82448 3542
5bc10b2c 3543#define DEBUG_STATE_pp(pp) \
265c4333 3544 DEBUG_STATE_r({ \
baa60164 3545 DUMP_EXEC_POS(locinput, scan, utf8_target); \
5bc10b2c 3546 PerlIO_printf(Perl_debug_log, \
5d458dd8 3547 " %*s"pp" %s%s%s%s%s\n", \
5bc10b2c 3548 depth*2, "", \
baa60164 3549 PL_reg_name[st->resume_state], \
5d458dd8
YO
3550 ((st==yes_state||st==mark_state) ? "[" : ""), \
3551 ((st==yes_state) ? "Y" : ""), \
3552 ((st==mark_state) ? "M" : ""), \
3553 ((st==yes_state||st==mark_state) ? "]" : "") \
3554 ); \
265c4333 3555 });
5bc10b2c 3556
40a82448 3557
3dab1dad 3558#define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
95b24440 3559
3df15adc 3560#ifdef DEBUGGING
5bc10b2c