This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
add UNOP_AUX OP class
[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
a687059c 40/*
e50aee73 41 * pregcomp and pregexec -- regsub and regerror are not used in perl
a687059c
LW
42 *
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
45 *
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
49 *
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
52 * from defects in it.
53 *
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
56 *
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
59 *
60 **** Alterations to Henry's code are...
61 ****
4bb101f2 62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
1129b882
NC
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
a687059c 65 ****
9ef589d8
LW
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
a687059c
LW
68 *
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
72 */
73#include "EXTERN.h"
864dbfa3 74#define PERL_IN_REGEXEC_C
a687059c 75#include "perl.h"
0f5d15d6 76
54df2634
NC
77#ifdef PERL_IN_XSUB_RE
78# include "re_comp.h"
79#else
80# include "regcomp.h"
81#endif
a687059c 82
81e983c1 83#include "inline_invlist.c"
1b0f46bf 84#include "unicode_constants.h"
81e983c1 85
e1cf74e3
CB
86#ifdef DEBUGGING
87/* At least one required character in the target string is expressible only in
88 * UTF-8. */
89static const char* const non_utf8_target_but_utf8_required
90 = "Can't match, because target string needs to be in UTF-8\n";
91#endif
92
93#define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
94 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
95 goto target; \
96} STMT_END
97
c74f6de9
KW
98#define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
99
a687059c
LW
100#ifndef STATIC
101#define STATIC static
102#endif
103
2d66f61e 104/* Valid only for non-utf8 strings: avoids the reginclass
7e2509c1
KW
105 * call if there are no complications: i.e., if everything matchable is
106 * straight forward in the bitmap */
3db24e1e 107#define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
af364d03 108 : ANYOF_BITMAP_TEST(p,*(c)))
7d3e948e 109
c277df42
IZ
110/*
111 * Forwards.
112 */
113
f2ed9b32 114#define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
ba44c216 115#define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
a0ed51b3 116
3dab1dad 117#define HOPc(pos,off) \
ba44c216 118 (char *)(reginfo->is_utf8_target \
220db18a 119 ? reghop3((U8*)pos, off, \
9d9163fb 120 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
3dab1dad 121 : (U8*)(pos + off))
557f47af 122
3dab1dad 123#define HOPBACKc(pos, off) \
ba44c216 124 (char*)(reginfo->is_utf8_target \
9d9163fb
DM
125 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
126 : (pos - off >= reginfo->strbeg) \
8e11feef 127 ? (U8*)pos - off \
3dab1dad 128 : NULL)
efb30f32 129
ba44c216 130#define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
1aa99e6b 131#define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
1aa99e6b 132
557f47af
DM
133/* lim must be +ve. Returns NULL on overshoot */
134#define HOPMAYBE3(pos,off,lim) \
135 (reginfo->is_utf8_target \
136 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
137 : ((U8*)pos + off <= lim) \
138 ? (U8*)pos + off \
139 : NULL)
140
8e9f2289
DM
141/* like HOP3, but limits the result to <= lim even for the non-utf8 case.
142 * off must be >=0; args should be vars rather than expressions */
143#define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
144 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
145 : (U8*)((pos + off) > lim ? lim : (pos + off)))
146
2974eaec
DM
147#define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
148 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
149 : (U8*)(pos + off))
150#define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
7016d6eb
DM
151
152#define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
153#define NEXTCHR_IS_EOS (nextchr < 0)
154
155#define SET_nextchr \
220db18a 156 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
7016d6eb
DM
157
158#define SET_locinput(p) \
159 locinput = (p); \
160 SET_nextchr
161
162
2a16ac92 163#define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
c7304fe2
KW
164 if (!swash_ptr) { \
165 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
c7304fe2 166 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
2a16ac92 167 1, 0, invlist, &flags); \
c7304fe2
KW
168 assert(swash_ptr); \
169 } \
170 } STMT_END
171
172/* If in debug mode, we test that a known character properly matches */
173#ifdef DEBUGGING
174# define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
175 property_name, \
2a16ac92 176 invlist, \
c7304fe2 177 utf8_char_in_property) \
2a16ac92 178 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
c7304fe2
KW
179 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
180#else
181# define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
182 property_name, \
2a16ac92 183 invlist, \
c7304fe2 184 utf8_char_in_property) \
2a16ac92 185 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
c7304fe2 186#endif
d1eb3177 187
c7304fe2
KW
188#define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
189 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
2a16ac92
KW
190 "", \
191 PL_XPosix_ptrs[_CC_WORDCHAR], \
df38da56 192 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
c7304fe2
KW
193
194#define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
195 STMT_START { \
196 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_regular_begin, \
197 "_X_regular_begin", \
2a16ac92 198 NULL, \
df38da56 199 LATIN_CAPITAL_LETTER_SHARP_S_UTF8); \
c7304fe2
KW
200 LOAD_UTF8_CHARCLASS_DEBUG_TEST(PL_utf8_X_extend, \
201 "_X_extend", \
2a16ac92 202 NULL, \
c7304fe2
KW
203 COMBINING_GRAVE_ACCENT_UTF8); \
204 } STMT_END
d1eb3177 205
c7304fe2 206#define PLACEHOLDER /* Something for the preprocessor to grab onto */
3dab1dad
YO
207/* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
208
5f80c4cf 209/* for use after a quantifier and before an EXACT-like node -- japhy */
c35dcbe2
YO
210/* it would be nice to rework regcomp.sym to generate this stuff. sigh
211 *
212 * NOTE that *nothing* that affects backtracking should be in here, specifically
213 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
214 * node that is in between two EXACT like nodes when ascertaining what the required
215 * "follow" character is. This should probably be moved to regex compile time
216 * although it may be done at run time beause of the REF possibility - more
217 * investigation required. -- demerphq
218*/
baa60164
KW
219#define JUMPABLE(rn) ( \
220 OP(rn) == OPEN || \
3e901dc0 221 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
baa60164
KW
222 OP(rn) == EVAL || \
223 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
224 OP(rn) == PLUS || OP(rn) == MINMOD || \
225 OP(rn) == KEEPS || \
226 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
e2d8ce26 227)
ee9b8eae 228#define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
e2d8ce26 229
ee9b8eae
YO
230#define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
231
232#if 0
233/* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
234 we don't need this definition. */
235#define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
098b07d5 236#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
237#define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
238
239#else
240/* ... so we use this as its faster. */
241#define IS_TEXT(rn) ( OP(rn)==EXACT )
098b07d5 242#define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
ee9b8eae
YO
243#define IS_TEXTF(rn) ( OP(rn)==EXACTF )
244#define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
245
246#endif
e2d8ce26 247
a84d97b6
HS
248/*
249 Search for mandatory following text node; for lookahead, the text must
250 follow but for lookbehind (rn->flags != 0) we skip to the next step.
251*/
baa60164 252#define FIND_NEXT_IMPT(rn) STMT_START { \
3dab1dad
YO
253 while (JUMPABLE(rn)) { \
254 const OPCODE type = OP(rn); \
255 if (type == SUSPEND || PL_regkind[type] == CURLY) \
e2d8ce26 256 rn = NEXTOPER(NEXTOPER(rn)); \
3dab1dad 257 else if (type == PLUS) \
cca55fe3 258 rn = NEXTOPER(rn); \
3dab1dad 259 else if (type == IFMATCH) \
a84d97b6 260 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
e2d8ce26 261 else rn += NEXT_OFF(rn); \
3dab1dad 262 } \
5f80c4cf 263} STMT_END
74750237 264
22913b96
KW
265/* These constants are for finding GCB=LV and GCB=LVT in the CLUMP regnode.
266 * These are for the pre-composed Hangul syllables, which are all in a
267 * contiguous block and arranged there in such a way so as to facilitate
268 * alorithmic determination of their characteristics. As such, they don't need
269 * a swash, but can be determined by simple arithmetic. Almost all are
270 * GCB=LVT, but every 28th one is a GCB=LV */
271#define SBASE 0xAC00 /* Start of block */
272#define SCount 11172 /* Length of block */
273#define TCount 28
c476f425 274
006f26b2
DM
275#define SLAB_FIRST(s) (&(s)->states[0])
276#define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
277
a75351a1 278static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
bf2039a9 279static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
bf2039a9 280static regmatch_state * S_push_slab(pTHX);
51371543 281
87c0511b 282#define REGCP_PAREN_ELEMS 3
f067efbf 283#define REGCP_OTHER_ELEMS 3
e0fa7e2b 284#define REGCP_FRAME_ELEMS 1
620d5b66
NC
285/* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
286 * are needed for the regexp context stack bookkeeping. */
287
76e3520e 288STATIC CHECKPOINT
92da3157 289S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
a0d0e21e 290{
a3b680e6 291 const int retval = PL_savestack_ix;
92da3157
DM
292 const int paren_elems_to_push =
293 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
e0fa7e2b
NC
294 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
295 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
87c0511b 296 I32 p;
40a82448 297 GET_RE_DEBUG_FLAGS_DECL;
a0d0e21e 298
b93070ed
DM
299 PERL_ARGS_ASSERT_REGCPPUSH;
300
e49a9654 301 if (paren_elems_to_push < 0)
e8a85d26
JH
302 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
303 (int)paren_elems_to_push, (int)maxopenparen,
304 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
e49a9654 305
e0fa7e2b
NC
306 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
307 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
5df417d0 308 " out of range (%lu-%ld)",
92da3157
DM
309 total_elems,
310 (unsigned long)maxopenparen,
311 (long)parenfloor);
e0fa7e2b 312
620d5b66 313 SSGROW(total_elems + REGCP_FRAME_ELEMS);
7f69552c 314
495f47a5 315 DEBUG_BUFFERS_r(
92da3157 316 if ((int)maxopenparen > (int)parenfloor)
495f47a5
DM
317 PerlIO_printf(Perl_debug_log,
318 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
319 PTR2UV(rex),
320 PTR2UV(rex->offs)
321 );
322 );
92da3157 323 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
b1ce53c5 324/* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
99a90e59
FC
325 SSPUSHIV(rex->offs[p].end);
326 SSPUSHIV(rex->offs[p].start);
1ca2007e 327 SSPUSHINT(rex->offs[p].start_tmp);
e7707071 328 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
495f47a5
DM
329 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
330 (UV)p,
331 (IV)rex->offs[p].start,
332 (IV)rex->offs[p].start_tmp,
333 (IV)rex->offs[p].end
40a82448 334 ));
a0d0e21e 335 }
b1ce53c5 336/* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
92da3157 337 SSPUSHINT(maxopenparen);
b93070ed
DM
338 SSPUSHINT(rex->lastparen);
339 SSPUSHINT(rex->lastcloseparen);
e0fa7e2b 340 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
41123dfd 341
a0d0e21e
LW
342 return retval;
343}
344
c277df42 345/* These are needed since we do not localize EVAL nodes: */
ab3bbdeb
YO
346#define REGCP_SET(cp) \
347 DEBUG_STATE_r( \
ab3bbdeb 348 PerlIO_printf(Perl_debug_log, \
e4f74956 349 " Setting an EVAL scope, savestack=%"IVdf"\n", \
ab3bbdeb
YO
350 (IV)PL_savestack_ix)); \
351 cp = PL_savestack_ix
c3464db5 352
ab3bbdeb 353#define REGCP_UNWIND(cp) \
e4f74956 354 DEBUG_STATE_r( \
ab3bbdeb 355 if (cp != PL_savestack_ix) \
e4f74956
YO
356 PerlIO_printf(Perl_debug_log, \
357 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
ab3bbdeb
YO
358 (IV)(cp), (IV)PL_savestack_ix)); \
359 regcpblow(cp)
c277df42 360
a8d1f4b4
DM
361#define UNWIND_PAREN(lp, lcp) \
362 for (n = rex->lastparen; n > lp; n--) \
363 rex->offs[n].end = -1; \
364 rex->lastparen = n; \
365 rex->lastcloseparen = lcp;
366
367
f067efbf 368STATIC void
92da3157 369S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
a0d0e21e 370{
e0fa7e2b 371 UV i;
87c0511b 372 U32 paren;
a3621e74
YO
373 GET_RE_DEBUG_FLAGS_DECL;
374
7918f24d
NC
375 PERL_ARGS_ASSERT_REGCPPOP;
376
b1ce53c5 377 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
c6bf6a65 378 i = SSPOPUV;
e0fa7e2b
NC
379 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
380 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
b93070ed
DM
381 rex->lastcloseparen = SSPOPINT;
382 rex->lastparen = SSPOPINT;
92da3157 383 *maxopenparen_p = SSPOPINT;
b1ce53c5 384
620d5b66 385 i -= REGCP_OTHER_ELEMS;
b1ce53c5 386 /* Now restore the parentheses context. */
495f47a5
DM
387 DEBUG_BUFFERS_r(
388 if (i || rex->lastparen + 1 <= rex->nparens)
389 PerlIO_printf(Perl_debug_log,
390 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
391 PTR2UV(rex),
392 PTR2UV(rex->offs)
393 );
394 );
92da3157 395 paren = *maxopenparen_p;
620d5b66 396 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
ea3daa5d 397 SSize_t tmps;
1ca2007e 398 rex->offs[paren].start_tmp = SSPOPINT;
99a90e59
FC
399 rex->offs[paren].start = SSPOPIV;
400 tmps = SSPOPIV;
b93070ed
DM
401 if (paren <= rex->lastparen)
402 rex->offs[paren].end = tmps;
495f47a5
DM
403 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
404 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
405 (UV)paren,
406 (IV)rex->offs[paren].start,
407 (IV)rex->offs[paren].start_tmp,
408 (IV)rex->offs[paren].end,
409 (paren > rex->lastparen ? "(skipped)" : ""));
c277df42 410 );
87c0511b 411 paren--;
a0d0e21e 412 }
daf18116 413#if 1
dafc8851
JH
414 /* It would seem that the similar code in regtry()
415 * already takes care of this, and in fact it is in
416 * a better location to since this code can #if 0-ed out
417 * but the code in regtry() is needed or otherwise tests
418 * requiring null fields (pat.t#187 and split.t#{13,14}
daf18116
JH
419 * (as of patchlevel 7877) will fail. Then again,
420 * this code seems to be necessary or otherwise
225593e1
DM
421 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
422 * --jhi updated by dapm */
b93070ed 423 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
92da3157 424 if (i > *maxopenparen_p)
b93070ed
DM
425 rex->offs[i].start = -1;
426 rex->offs[i].end = -1;
495f47a5
DM
427 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
428 " \\%"UVuf": %s ..-1 undeffing\n",
429 (UV)i,
92da3157 430 (i > *maxopenparen_p) ? "-1" : " "
495f47a5 431 ));
a0d0e21e 432 }
dafc8851 433#endif
a0d0e21e
LW
434}
435
74088413
DM
436/* restore the parens and associated vars at savestack position ix,
437 * but without popping the stack */
438
439STATIC void
92da3157 440S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
74088413
DM
441{
442 I32 tmpix = PL_savestack_ix;
443 PL_savestack_ix = ix;
92da3157 444 regcppop(rex, maxopenparen_p);
74088413
DM
445 PL_savestack_ix = tmpix;
446}
447
02db2b7b 448#define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
a0d0e21e 449
31c7f561
KW
450STATIC bool
451S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
452{
453 /* Returns a boolean as to whether or not 'character' is a member of the
454 * Posix character class given by 'classnum' that should be equivalent to a
455 * value in the typedef '_char_class_number'.
456 *
457 * Ideally this could be replaced by a just an array of function pointers
458 * to the C library functions that implement the macros this calls.
459 * However, to compile, the precise function signatures are required, and
460 * these may vary from platform to to platform. To avoid having to figure
461 * out what those all are on each platform, I (khw) am using this method,
7aee35ff
KW
462 * which adds an extra layer of function call overhead (unless the C
463 * optimizer strips it away). But we don't particularly care about
464 * performance with locales anyway. */
31c7f561
KW
465
466 switch ((_char_class_number) classnum) {
15861f94 467 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
31c7f561 468 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
e8d596e0
KW
469 case _CC_ENUM_ASCII: return isASCII_LC(character);
470 case _CC_ENUM_BLANK: return isBLANK_LC(character);
b0d691b2
KW
471 case _CC_ENUM_CASED: return isLOWER_LC(character)
472 || isUPPER_LC(character);
e8d596e0 473 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
31c7f561
KW
474 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
475 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
476 case _CC_ENUM_LOWER: return isLOWER_LC(character);
477 case _CC_ENUM_PRINT: return isPRINT_LC(character);
e8d596e0 478 case _CC_ENUM_PSXSPC: return isPSXSPC_LC(character);
31c7f561 479 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
e8d596e0 480 case _CC_ENUM_SPACE: return isSPACE_LC(character);
31c7f561
KW
481 case _CC_ENUM_UPPER: return isUPPER_LC(character);
482 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
31c7f561 483 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
31c7f561
KW
484 default: /* VERTSPACE should never occur in locales */
485 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
486 }
487
e5964223 488 NOT_REACHED; /* NOTREACHED */
31c7f561
KW
489 return FALSE;
490}
491
3018b823
KW
492STATIC bool
493S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
494{
495 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
496 * 'character' is a member of the Posix character class given by 'classnum'
497 * that should be equivalent to a value in the typedef
498 * '_char_class_number'.
499 *
500 * This just calls isFOO_lc on the code point for the character if it is in
501 * the range 0-255. Outside that range, all characters avoid Unicode
502 * rules, ignoring any locale. So use the Unicode function if this class
503 * requires a swash, and use the Unicode macro otherwise. */
504
505 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
506
507 if (UTF8_IS_INVARIANT(*character)) {
508 return isFOO_lc(classnum, *character);
509 }
510 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
511 return isFOO_lc(classnum,
94bb8c36 512 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
3018b823
KW
513 }
514
515 if (classnum < _FIRST_NON_SWASH_CC) {
516
517 /* Initialize the swash unless done already */
518 if (! PL_utf8_swash_ptrs[classnum]) {
519 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2a16ac92
KW
520 PL_utf8_swash_ptrs[classnum] =
521 _core_swash_init("utf8",
522 "",
523 &PL_sv_undef, 1, 0,
524 PL_XPosix_ptrs[classnum], &flags);
3018b823
KW
525 }
526
92a2046b
KW
527 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
528 character,
529 TRUE /* is UTF */ ));
3018b823
KW
530 }
531
532 switch ((_char_class_number) classnum) {
533 case _CC_ENUM_SPACE:
534 case _CC_ENUM_PSXSPC: return is_XPERLSPACE_high(character);
535
536 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
537 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
538 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
e1ee3960 539 default: break;
3018b823
KW
540 }
541
e1ee3960 542 return FALSE; /* Things like CNTRL are always below 256 */
3018b823
KW
543}
544
a687059c 545/*
e50aee73 546 * pregexec and friends
a687059c
LW
547 */
548
76234dfb 549#ifndef PERL_IN_XSUB_RE
a687059c 550/*
c277df42 551 - pregexec - match a regexp against a string
a687059c 552 */
c277df42 553I32
5aaab254 554Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
ea3daa5d 555 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
8fd1a950
DM
556/* stringarg: the point in the string at which to begin matching */
557/* strend: pointer to null at end of string */
558/* strbeg: real beginning of string */
559/* minend: end of match must be >= minend bytes after stringarg. */
560/* screamer: SV being matched: only used for utf8 flag, pos() etc; string
561 * itself is accessed via the pointers above */
562/* nosave: For optimizations. */
c277df42 563{
7918f24d
NC
564 PERL_ARGS_ASSERT_PREGEXEC;
565
c277df42 566 return
9041c2e3 567 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
c277df42
IZ
568 nosave ? 0 : REXEC_COPY_STR);
569}
76234dfb 570#endif
22e551b9 571
cad2e5aa 572
6eb5f6b9 573
1a4edc3c
DM
574/* re_intuit_start():
575 *
576 * Based on some optimiser hints, try to find the earliest position in the
577 * string where the regex could match.
578 *
579 * rx: the regex to match against
580 * sv: the SV being matched: only used for utf8 flag; the string
581 * itself is accessed via the pointers below. Note that on
582 * something like an overloaded SV, SvPOK(sv) may be false
583 * and the string pointers may point to something unrelated to
584 * the SV itself.
585 * strbeg: real beginning of string
586 * strpos: the point in the string at which to begin matching
587 * strend: pointer to the byte following the last char of the string
588 * flags currently unused; set to 0
589 * data: currently unused; set to NULL
590 *
591 * The basic idea of re_intuit_start() is to use some known information
592 * about the pattern, namely:
593 *
594 * a) the longest known anchored substring (i.e. one that's at a
595 * constant offset from the beginning of the pattern; but not
596 * necessarily at a fixed offset from the beginning of the
597 * string);
598 * b) the longest floating substring (i.e. one that's not at a constant
599 * offset from the beginning of the pattern);
600 * c) Whether the pattern is anchored to the string; either
601 * an absolute anchor: /^../, or anchored to \n: /^.../m,
602 * or anchored to pos(): /\G/;
603 * d) A start class: a real or synthetic character class which
604 * represents which characters are legal at the start of the pattern;
605 *
606 * to either quickly reject the match, or to find the earliest position
607 * within the string at which the pattern might match, thus avoiding
608 * running the full NFA engine at those earlier locations, only to
609 * eventually fail and retry further along.
610 *
611 * Returns NULL if the pattern can't match, or returns the address within
612 * the string which is the earliest place the match could occur.
613 *
614 * The longest of the anchored and floating substrings is called 'check'
615 * and is checked first. The other is called 'other' and is checked
616 * second. The 'other' substring may not be present. For example,
617 *
618 * /(abc|xyz)ABC\d{0,3}DEFG/
619 *
620 * will have
621 *
622 * check substr (float) = "DEFG", offset 6..9 chars
623 * other substr (anchored) = "ABC", offset 3..3 chars
624 * stclass = [ax]
625 *
626 * Be aware that during the course of this function, sometimes 'anchored'
627 * refers to a substring being anchored relative to the start of the
628 * pattern, and sometimes to the pattern itself being anchored relative to
629 * the string. For example:
630 *
631 * /\dabc/: "abc" is anchored to the pattern;
632 * /^\dabc/: "abc" is anchored to the pattern and the string;
633 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
634 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
635 * but the pattern is anchored to the string.
52a21eb3
DM
636 */
637
cad2e5aa 638char *
52a21eb3
DM
639Perl_re_intuit_start(pTHX_
640 REGEXP * const rx,
641 SV *sv,
642 const char * const strbeg,
643 char *strpos,
644 char *strend,
645 const U32 flags,
646 re_scream_pos_data *data)
cad2e5aa 647{
8d919b0a 648 struct regexp *const prog = ReANY(rx);
6b071d16 649 SSize_t start_shift = prog->check_offset_min;
cad2e5aa 650 /* Should be nonnegative! */
ea3daa5d 651 SSize_t end_shift = 0;
0fc004dd
DM
652 /* current lowest pos in string where the regex can start matching */
653 char *rx_origin = strpos;
eb578fdb 654 SV *check;
f2ed9b32 655 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
6480a6c4 656 U8 other_ix = 1 - prog->substrs->check_ix;
6ad5ffb3 657 bool ml_anch = 0;
8f4bf5fc 658 char *other_last = strpos;/* latest pos 'other' substr already checked to */
bd61b366 659 char *check_at = NULL; /* check substr found at this pos */
bbe252da 660 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
f8fc2ecf 661 RXi_GET_DECL(prog,progi);
02d5137b
DM
662 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
663 regmatch_info *const reginfo = &reginfo_buf;
a3621e74
YO
664 GET_RE_DEBUG_FLAGS_DECL;
665
7918f24d 666 PERL_ARGS_ASSERT_RE_INTUIT_START;
c33e64f0
FC
667 PERL_UNUSED_ARG(flags);
668 PERL_UNUSED_ARG(data);
7918f24d 669
1dc475d0
DM
670 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
671 "Intuit: trying to determine minimum start position...\n"));
672
fb9bbddb
DM
673 /* for now, assume that all substr offsets are positive. If at some point
674 * in the future someone wants to do clever things with look-behind and
675 * -ve offsets, they'll need to fix up any code in this function
676 * which uses these offsets. See the thread beginning
677 * <20140113145929.GF27210@iabyn.com>
678 */
679 assert(prog->substrs->data[0].min_offset >= 0);
680 assert(prog->substrs->data[0].max_offset >= 0);
681 assert(prog->substrs->data[1].min_offset >= 0);
682 assert(prog->substrs->data[1].max_offset >= 0);
683 assert(prog->substrs->data[2].min_offset >= 0);
684 assert(prog->substrs->data[2].max_offset >= 0);
685
f7022b5a 686 /* for now, assume that if both present, that the floating substring
83f2232d 687 * doesn't start before the anchored substring.
f7022b5a
DM
688 * If you break this assumption (e.g. doing better optimisations
689 * with lookahead/behind), then you'll need to audit the code in this
690 * function carefully first
691 */
692 assert(
693 ! ( (prog->anchored_utf8 || prog->anchored_substr)
694 && (prog->float_utf8 || prog->float_substr))
695 || (prog->float_min_offset >= prog->anchored_offset));
696
1a4edc3c
DM
697 /* byte rather than char calculation for efficiency. It fails
698 * to quickly reject some cases that can't match, but will reject
699 * them later after doing full char arithmetic */
c344f387 700 if (prog->minlen > strend - strpos) {
a3621e74 701 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 702 " String too short...\n"));
cad2e5aa 703 goto fail;
2c2d71f5 704 }
d8da0584 705
ab4e48c1 706 RX_MATCH_UTF8_set(rx,utf8_target);
6c3fea77 707 reginfo->is_utf8_target = cBOOL(utf8_target);
bf2039a9 708 reginfo->info_aux = NULL;
9d9163fb 709 reginfo->strbeg = strbeg;
220db18a 710 reginfo->strend = strend;
aed7b151 711 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
02d5137b 712 reginfo->intuit = 1;
1cb48e53
DM
713 /* not actually used within intuit, but zero for safety anyway */
714 reginfo->poscache_maxiter = 0;
02d5137b 715
f2ed9b32 716 if (utf8_target) {
33b8afdf
JH
717 if (!prog->check_utf8 && prog->check_substr)
718 to_utf8_substr(prog);
719 check = prog->check_utf8;
720 } else {
7e0d5ad7
KW
721 if (!prog->check_substr && prog->check_utf8) {
722 if (! to_byte_substr(prog)) {
6b54ddc5 723 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
7e0d5ad7
KW
724 }
725 }
33b8afdf
JH
726 check = prog->check_substr;
727 }
274cd312 728
1dc475d0
DM
729 /* dump the various substring data */
730 DEBUG_OPTIMISE_MORE_r({
731 int i;
732 for (i=0; i<=2; i++) {
733 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
734 : prog->substrs->data[i].substr);
735 if (!sv)
736 continue;
737
738 PerlIO_printf(Perl_debug_log,
739 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
740 " useful=%"IVdf" utf8=%d [%s]\n",
741 i,
742 (IV)prog->substrs->data[i].min_offset,
743 (IV)prog->substrs->data[i].max_offset,
744 (IV)prog->substrs->data[i].end_shift,
745 BmUSEFUL(sv),
746 utf8_target ? 1 : 0,
747 SvPEEK(sv));
748 }
749 });
750
8e1490ee 751 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
9fc7410e
DM
752
753 /* ml_anch: check after \n?
754 *
755 * A note about IMPLICIT: on an un-anchored pattern beginning
756 * with /.*.../, these flags will have been added by the
757 * compiler:
758 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
759 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
760 */
7d2d37f5
DM
761 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
762 && !(prog->intflags & PREGf_IMPLICIT);
cad2e5aa 763
343c8a29 764 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
c889ccc8
DM
765 /* we are only allowed to match at BOS or \G */
766
57fcbfa7 767 /* trivially reject if there's a BOS anchor and we're not at BOS.
7bb3b9eb
DM
768 *
769 * Note that we don't try to do a similar quick reject for
770 * \G, since generally the caller will have calculated strpos
771 * based on pos() and gofs, so the string is already correctly
772 * anchored by definition; and handling the exceptions would
773 * be too fiddly (e.g. REXEC_IGNOREPOS).
57fcbfa7 774 */
7bb3b9eb 775 if ( strpos != strbeg
d3d47aac 776 && (prog->intflags & PREGf_ANCH_SBOL))
c889ccc8
DM
777 {
778 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 779 " Not at start...\n"));
c889ccc8
DM
780 goto fail;
781 }
782
a5d12a4b
DM
783 /* in the presence of an anchor, the anchored (relative to the
784 * start of the regex) substr must also be anchored relative
66b7ec5c
DM
785 * to strpos. So quickly reject if substr isn't found there.
786 * This works for \G too, because the caller will already have
787 * subtracted gofs from pos, and gofs is the offset from the
788 * \G to the start of the regex. For example, in /.abc\Gdef/,
789 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
790 * caller will have set strpos=pos()-4; we look for the substr
791 * at position pos()-4+1, which lines up with the "a" */
a5d12a4b 792
c889ccc8 793 if (prog->check_offset_min == prog->check_offset_max
d0d44648 794 && !(prog->intflags & PREGf_CANY_SEEN))
c889ccc8
DM
795 {
796 /* Substring at constant offset from beg-of-str... */
d307bf57 797 SSize_t slen = SvCUR(check);
343c8a29 798 char *s = HOP3c(strpos, prog->check_offset_min, strend);
1de06328 799
1dc475d0
DM
800 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
801 " Looking for check substr at fixed offset %"IVdf"...\n",
802 (IV)prog->check_offset_min));
803
7742aa66
DM
804 if (SvTAIL(check)) {
805 /* In this case, the regex is anchored at the end too.
806 * Unless it's a multiline match, the lengths must match
807 * exactly, give or take a \n. NB: slen >= 1 since
808 * the last char of check is \n */
809 if (!multiline
810 && ( strend - s > slen
811 || strend - s < slen - 1
812 || (strend - s == slen && strend[-1] != '\n')))
c889ccc8
DM
813 {
814 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 815 " String too long...\n"));
c889ccc8
DM
816 goto fail_finish;
817 }
818 /* Now should match s[0..slen-2] */
819 slen--;
c889ccc8 820 }
d307bf57
DM
821 if (slen && (*SvPVX_const(check) != *s
822 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
823 {
824 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 825 " String not equal...\n"));
d307bf57
DM
826 goto fail_finish;
827 }
c889ccc8
DM
828
829 check_at = s;
830 goto success_at_start;
cad2e5aa 831 }
cad2e5aa 832 }
cad2e5aa 833 }
0fc004dd 834
c0e0ec46 835 end_shift = prog->check_end_shift;
cad2e5aa 836
19188028 837#ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
0033605d 838 if (end_shift < 0)
1de06328 839 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
220fc49f 840 (IV)end_shift, RX_PRECOMP(prog));
2c2d71f5
JH
841#endif
842
2c2d71f5 843 restart:
1de06328 844
66b7ec5c
DM
845 /* This is the (re)entry point of the main loop in this function.
846 * The goal of this loop is to:
847 * 1) find the "check" substring in the region rx_origin..strend
848 * (adjusted by start_shift / end_shift). If not found, reject
849 * immediately.
850 * 2) If it exists, look for the "other" substr too if defined; for
851 * example, if the check substr maps to the anchored substr, then
852 * check the floating substr, and vice-versa. If not found, go
853 * back to (1) with rx_origin suitably incremented.
854 * 3) If we find an rx_origin position that doesn't contradict
855 * either of the substrings, then check the possible additional
856 * constraints on rx_origin of /^.../m or a known start class.
857 * If these fail, then depending on which constraints fail, jump
858 * back to here, or to various other re-entry points further along
859 * that skip some of the first steps.
860 * 4) If we pass all those tests, update the BmUSEFUL() count on the
861 * substring. If the start position was determined to be at the
862 * beginning of the string - so, not rejected, but not optimised,
863 * since we have to run regmatch from position 0 - decrement the
864 * BmUSEFUL() count. Otherwise increment it.
865 */
866
1a4edc3c
DM
867
868 /* first, look for the 'check' substring */
869
1de06328 870 {
c33e64f0
FC
871 U8* start_point;
872 U8* end_point;
c889ccc8 873
c889ccc8 874 DEBUG_OPTIMISE_MORE_r({
1dc475d0 875 PerlIO_printf(Perl_debug_log,
ae5d4331 876 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
1dc475d0 877 " Start shift: %"IVdf" End shift %"IVdf
4d281893 878 " Real end Shift: %"IVdf"\n",
197641b6 879 (IV)(rx_origin - strpos),
c889ccc8 880 (IV)prog->check_offset_min,
12fbc530
DM
881 (IV)start_shift,
882 (IV)end_shift,
c889ccc8
DM
883 (IV)prog->check_end_shift);
884 });
1de06328 885
0d331aaf 886 if (prog->intflags & PREGf_CANY_SEEN) {
0fc004dd 887 start_point= (U8*)(rx_origin + start_shift);
12fbc530 888 end_point= (U8*)(strend - end_shift);
557f47af
DM
889 if (start_point > end_point)
890 goto fail_finish;
1de06328 891 } else {
557f47af
DM
892 end_point = HOP3(strend, -end_shift, strbeg);
893 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
894 if (!start_point)
895 goto fail_finish;
1de06328 896 }
c889ccc8 897
557f47af 898
e0362b86 899 /* If the regex is absolutely anchored to either the start of the
d3d47aac 900 * string (SBOL) or to pos() (ANCH_GPOS), then
e0362b86
DM
901 * check_offset_max represents an upper bound on the string where
902 * the substr could start. For the ANCH_GPOS case, we assume that
903 * the caller of intuit will have already set strpos to
904 * pos()-gofs, so in this case strpos + offset_max will still be
905 * an upper bound on the substr.
906 */
c19c836a
DM
907 if (!ml_anch
908 && prog->intflags & PREGf_ANCH
e0362b86 909 && prog->check_offset_max != SSize_t_MAX)
c19c836a 910 {
1a08ba3a 911 SSize_t len = SvCUR(check) - !!SvTAIL(check);
e0362b86
DM
912 const char * const anchor =
913 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
914
915 /* do a bytes rather than chars comparison. It's conservative;
916 * so it skips doing the HOP if the result can't possibly end
917 * up earlier than the old value of end_point.
918 */
919 if ((char*)end_point - anchor > prog->check_offset_max) {
920 end_point = HOP3lim((U8*)anchor,
921 prog->check_offset_max,
922 end_point -len)
923 + len;
924 }
d6ef1678
DM
925 }
926
6bda09f9 927 DEBUG_OPTIMISE_MORE_r({
1dc475d0 928 PerlIO_printf(Perl_debug_log, " fbm_instr len=%d str=<%.*s>\n",
1de06328 929 (int)(end_point - start_point),
fc8cd66c 930 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
1de06328
YO
931 start_point);
932 });
933
ae5d4331 934 check_at = fbm_instr( start_point, end_point,
7fba1cd6 935 check, multiline ? FBMrf_MULTILINE : 0);
c889ccc8 936
8fd34720
DM
937 /* Update the count-of-usability, remove useless subpatterns,
938 unshift s. */
939
940 DEBUG_EXECUTE_r({
941 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
942 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
943 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
944 (check_at ? "Found" : "Did not find"),
945 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
946 ? "anchored" : "floating"),
947 quoted,
948 RE_SV_TAIL(check),
949 (check_at ? " at offset " : "...\n") );
950 });
2c2d71f5 951
8fd34720
DM
952 if (!check_at)
953 goto fail_finish;
954 /* Finish the diagnostic message */
955 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(check_at - strpos)) );
2c2d71f5 956
8fd34720
DM
957 /* set rx_origin to the minimum position where the regex could start
958 * matching, given the constraint of the just-matched check substring.
959 * But don't set it lower than previously.
960 */
fdc003fd 961
8fd34720
DM
962 if (check_at - rx_origin > prog->check_offset_max)
963 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
964 }
fdc003fd
DM
965
966
1a4edc3c 967 /* now look for the 'other' substring if defined */
2c2d71f5 968
6480a6c4
DM
969 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
970 : prog->substrs->data[other_ix].substr)
1de06328 971 {
30944b6d 972 /* Take into account the "other" substring. */
6c3343a6
DM
973 char *last, *last1;
974 char *s;
975 SV* must;
976 struct reg_substr_datum *other;
977
978 do_other_substr:
979 other = &prog->substrs->data[other_ix];
980
981 /* if "other" is anchored:
982 * we've previously found a floating substr starting at check_at.
983 * This means that the regex origin must lie somewhere
984 * between min (rx_origin): HOP3(check_at, -check_offset_max)
985 * and max: HOP3(check_at, -check_offset_min)
986 * (except that min will be >= strpos)
987 * So the fixed substr must lie somewhere between
988 * HOP3(min, anchored_offset)
989 * HOP3(max, anchored_offset) + SvCUR(substr)
990 */
991
992 /* if "other" is floating
993 * Calculate last1, the absolute latest point where the
994 * floating substr could start in the string, ignoring any
995 * constraints from the earlier fixed match. It is calculated
996 * as follows:
997 *
998 * strend - prog->minlen (in chars) is the absolute latest
999 * position within the string where the origin of the regex
1000 * could appear. The latest start point for the floating
1001 * substr is float_min_offset(*) on from the start of the
1002 * regex. last1 simply combines thee two offsets.
1003 *
1004 * (*) You might think the latest start point should be
1005 * float_max_offset from the regex origin, and technically
1006 * you'd be correct. However, consider
1007 * /a\d{2,4}bcd\w/
1008 * Here, float min, max are 3,5 and minlen is 7.
1009 * This can match either
1010 * /a\d\dbcd\w/
1011 * /a\d\d\dbcd\w/
1012 * /a\d\d\d\dbcd\w/
1013 * In the first case, the regex matches minlen chars; in the
1014 * second, minlen+1, in the third, minlen+2.
1015 * In the first case, the floating offset is 3 (which equals
1016 * float_min), in the second, 4, and in the third, 5 (which
1017 * equals float_max). In all cases, the floating string bcd
1018 * can never start more than 4 chars from the end of the
1019 * string, which equals minlen - float_min. As the substring
1020 * starts to match more than float_min from the start of the
1021 * regex, it makes the regex match more than minlen chars,
1022 * and the two cancel each other out. So we can always use
1023 * float_min - minlen, rather than float_max - minlen for the
1024 * latest position in the string.
1025 *
1026 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1027 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1028 */
1029
e7a14a9c 1030 assert(prog->minlen >= other->min_offset);
6c3343a6
DM
1031 last1 = HOP3c(strend,
1032 other->min_offset - prog->minlen, strbeg);
1033
4d006249 1034 if (other_ix) {/* i.e. if (other-is-float) */
6c3343a6
DM
1035 /* last is the latest point where the floating substr could
1036 * start, *given* any constraints from the earlier fixed
1037 * match. This constraint is that the floating string starts
1038 * <= float_max_offset chars from the regex origin (rx_origin).
1039 * If this value is less than last1, use it instead.
eb3831ce 1040 */
6c3343a6
DM
1041 assert(rx_origin <= last1);
1042 last =
1043 /* this condition handles the offset==infinity case, and
1044 * is a short-cut otherwise. Although it's comparing a
1045 * byte offset to a char length, it does so in a safe way,
1046 * since 1 char always occupies 1 or more bytes,
1047 * so if a string range is (last1 - rx_origin) bytes,
1048 * it will be less than or equal to (last1 - rx_origin)
1049 * chars; meaning it errs towards doing the accurate HOP3
1050 * rather than just using last1 as a short-cut */
1051 (last1 - rx_origin) < other->max_offset
1052 ? last1
1053 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1054 }
1055 else {
1056 assert(strpos + start_shift <= check_at);
1057 last = HOP4c(check_at, other->min_offset - start_shift,
1058 strbeg, strend);
1059 }
ead917d0 1060
6c3343a6
DM
1061 s = HOP3c(rx_origin, other->min_offset, strend);
1062 if (s < other_last) /* These positions already checked */
1063 s = other_last;
1064
1065 must = utf8_target ? other->utf8_substr : other->substr;
1066 assert(SvPOK(must));
1067 s = fbm_instr(
1068 (unsigned char*)s,
1069 (unsigned char*)last + SvCUR(must) - (SvTAIL(must)!=0),
1070 must,
1071 multiline ? FBMrf_MULTILINE : 0
1072 );
1073 DEBUG_EXECUTE_r({
1074 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1075 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1076 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1077 s ? "Found" : "Contradicts",
1078 other_ix ? "floating" : "anchored",
1079 quoted, RE_SV_TAIL(must));
1080 });
ead917d0 1081
ead917d0 1082
6c3343a6
DM
1083 if (!s) {
1084 /* last1 is latest possible substr location. If we didn't
1085 * find it before there, we never will */
1086 if (last >= last1) {
1087 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1088 ", giving up...\n"));
1089 goto fail_finish;
ead917d0
DM
1090 }
1091
6c3343a6
DM
1092 /* try to find the check substr again at a later
1093 * position. Maybe next time we'll find the "other" substr
1094 * in range too */
1095 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1096 ", trying %s at offset %ld...\n",
1097 (other_ix ? "floating" : "anchored"),
197641b6 1098 (long)(HOP3c(check_at, 1, strend) - strpos)));
6c3343a6
DM
1099
1100 other_last = HOP3c(last, 1, strend) /* highest failure */;
1101 rx_origin =
4d006249 1102 other_ix /* i.e. if other-is-float */
6c3343a6
DM
1103 ? HOP3c(rx_origin, 1, strend)
1104 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1105 goto restart;
1106 }
1107 else {
1108 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
197641b6 1109 (long)(s - strpos)));
ead917d0 1110
4d006249 1111 if (other_ix) { /* if (other-is-float) */
6c3343a6
DM
1112 /* other_last is set to s, not s+1, since its possible for
1113 * a floating substr to fail first time, then succeed
1114 * second time at the same floating position; e.g.:
1115 * "-AB--AABZ" =~ /\wAB\d*Z/
1116 * The first time round, anchored and float match at
1117 * "-(AB)--AAB(Z)" then fail on the initial \w character
1118 * class. Second time round, they match at "-AB--A(AB)(Z)".
1119 */
1120 other_last = s;
ead917d0
DM
1121 }
1122 else {
6c3343a6
DM
1123 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1124 other_last = HOP3c(s, 1, strend);
ead917d0 1125 }
6c3343a6 1126 }
cad2e5aa 1127 }
acba93e8
DM
1128 else {
1129 DEBUG_OPTIMISE_MORE_r(
1130 PerlIO_printf(Perl_debug_log,
1131 " Check-only match: offset min:%"IVdf" max:%"IVdf
1c1c599d 1132 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
acba93e8
DM
1133 " strend-strpos:%"IVdf"\n",
1134 (IV)prog->check_offset_min,
1135 (IV)prog->check_offset_max,
1c1c599d 1136 (IV)(check_at-strpos),
acba93e8 1137 (IV)(rx_origin-strpos),
1c1c599d 1138 (IV)(rx_origin-check_at),
acba93e8
DM
1139 (IV)(strend-strpos)
1140 )
1141 );
1142 }
2c2d71f5 1143
acba93e8 1144 postprocess_substr_matches:
0991020e 1145
1a4edc3c 1146 /* handle the extra constraint of /^.../m if present */
e3c6feb0 1147
7d2d37f5 1148 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
4620cb61
DM
1149 char *s;
1150
a62659bd
DM
1151 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1152 " looking for /^/m anchor"));
d0880ea7
DM
1153
1154 /* we have failed the constraint of a \n before rx_origin.
2e759faa
DM
1155 * Find the next \n, if any, even if it's beyond the current
1156 * anchored and/or floating substrings. Whether we should be
1157 * scanning ahead for the next \n or the next substr is debatable.
1158 * On the one hand you'd expect rare substrings to appear less
1159 * often than \n's. On the other hand, searching for \n means
1160 * we're effectively flipping been check_substr and "\n" on each
1161 * iteration as the current "rarest" string candidate, which
1162 * means for example that we'll quickly reject the whole string if
1163 * hasn't got a \n, rather than trying every substr position
1164 * first
1165 */
d0880ea7 1166
4620cb61
DM
1167 s = HOP3c(strend, - prog->minlen, strpos);
1168 if (s <= rx_origin ||
1169 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1170 {
d0880ea7
DM
1171 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1172 " Did not find /%s^%s/m...\n",
1173 PL_colors[0], PL_colors[1]));
a62659bd
DM
1174 goto fail_finish;
1175 }
d0880ea7 1176
4ada1233
DM
1177 /* earliest possible origin is 1 char after the \n.
1178 * (since *rx_origin == '\n', it's safe to ++ here rather than
1179 * HOP(rx_origin, 1)) */
1180 rx_origin++;
d0880ea7 1181
f4f115de 1182 if (prog->substrs->check_ix == 0 /* check is anchored */
4ada1233 1183 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
f4f115de 1184 {
d0880ea7
DM
1185 /* Position contradicts check-string; either because
1186 * check was anchored (and thus has no wiggle room),
4ada1233 1187 * or check was float and rx_origin is above the float range */
d0880ea7
DM
1188 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1189 " Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
4ada1233 1190 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
d0880ea7
DM
1191 goto restart;
1192 }
1193
1194 /* if we get here, the check substr must have been float,
2e759faa 1195 * is in range, and we may or may not have had an anchored
d0880ea7
DM
1196 * "other" substr which still contradicts */
1197 assert(prog->substrs->check_ix); /* check is float */
1198
1199 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1200 /* whoops, the anchored "other" substr exists, so we still
1201 * contradict. On the other hand, the float "check" substr
1202 * didn't contradict, so just retry the anchored "other"
1203 * substr */
1204 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1205 " Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
1206 PL_colors[0], PL_colors[1],
1207 (long)(rx_origin - strpos),
1208 (long)(rx_origin - strpos + prog->anchored_offset)));
1209 goto do_other_substr;
1210 }
1211
1212 /* success: we don't contradict the found floating substring
1213 * (and there's no anchored substr). */
d0880ea7
DM
1214 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1215 " Found /%s^%s/m at offset %ld...\n",
1216 PL_colors[0], PL_colors[1], (long)(rx_origin - strpos)));
e3c6feb0
DM
1217 }
1218 else {
2e759faa 1219 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
fe4f3442 1220 " (multiline anchor test skipped)\n"));
e3c6feb0
DM
1221 }
1222
ffad1e6a 1223 success_at_start:
e3c6feb0 1224
cad2e5aa 1225
dd170ff5
DM
1226 /* if we have a starting character class, then test that extra constraint.
1227 * (trie stclasses are too expensive to use here, we are better off to
1228 * leave it to regmatch itself) */
1229
f8fc2ecf 1230 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
f8fc2ecf 1231 const U8* const str = (U8*)STRING(progi->regstclass);
0991020e 1232
2c75e362 1233 /* XXX this value could be pre-computed */
f8fc2ecf 1234 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
2c75e362
DM
1235 ? (reginfo->is_utf8_pat
1236 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1237 : STR_LEN(progi->regstclass))
66e933ab 1238 : 1);
1de06328 1239 char * endpos;
fa3bb21d 1240 char *s;
000dfd2d
DM
1241 /* latest pos that a matching float substr constrains rx start to */
1242 char *rx_max_float = NULL;
1243
c75a3985
DM
1244 /* if the current rx_origin is anchored, either by satisfying an
1245 * anchored substring constraint, or a /^.../m constraint, then we
1246 * can reject the current origin if the start class isn't found
1247 * at the current position. If we have a float-only match, then
1248 * rx_origin is constrained to a range; so look for the start class
1249 * in that range. if neither, then look for the start class in the
1250 * whole rest of the string */
1251
dd170ff5
DM
1252 /* XXX DAPM it's not clear what the minlen test is for, and why
1253 * it's not used in the floating case. Nothing in the test suite
1254 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1255 * Here are some old comments, which may or may not be correct:
1256 *
1257 * minlen == 0 is possible if regstclass is \b or \B,
1258 * and the fixed substr is ''$.
1259 * Since minlen is already taken into account, rx_origin+1 is
1260 * before strend; accidentally, minlen >= 1 guaranties no false
1261 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1262 * 0) below assumes that regstclass does not come from lookahead...
1263 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1264 * This leaves EXACTF-ish only, which are dealt with in
1265 * find_byclass().
1266 */
1267
7d2d37f5 1268 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
fa3bb21d 1269 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
000dfd2d
DM
1270 else if (prog->float_substr || prog->float_utf8) {
1271 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1272 endpos= HOP3c(rx_max_float, cl_l, strend);
1273 }
1de06328
YO
1274 else
1275 endpos= strend;
1276
1dc475d0
DM
1277 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1278 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
c43b5520 1279 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1dc475d0 1280 (IV)start_shift, (IV)(check_at - strbeg),
c43b5520 1281 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
d8080198 1282
c43b5520 1283 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
f9176b44 1284 reginfo);
be778b1a 1285 if (!s) {
6eb5f6b9 1286 if (endpos == strend) {
a3621e74 1287 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1dc475d0 1288 " Could not match STCLASS...\n") );
6eb5f6b9
JH
1289 goto fail;
1290 }
a3621e74 1291 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1dc475d0 1292 " This position contradicts STCLASS...\n") );
e0eb31e7
DM
1293 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1294 && !(prog->intflags & PREGf_IMPLICIT))
653099ff 1295 goto fail;
9fed8d02 1296
6eb5f6b9 1297 /* Contradict one of substrings */
97136c8a
DM
1298 if (prog->anchored_substr || prog->anchored_utf8) {
1299 if (prog->substrs->check_ix == 1) { /* check is float */
1300 /* Have both, check_string is floating */
1301 assert(rx_origin + start_shift <= check_at);
1302 if (rx_origin + start_shift != check_at) {
1303 /* not at latest position float substr could match:
c75a3985
DM
1304 * Recheck anchored substring, but not floating.
1305 * The condition above is in bytes rather than
1306 * chars for efficiency. It's conservative, in
1307 * that it errs on the side of doing 'goto
1308 * do_other_substr', where a more accurate
1309 * char-based calculation will be done */
97136c8a
DM
1310 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1311 " Looking for anchored substr starting at offset %ld...\n",
1312 (long)(other_last - strpos)) );
1313 goto do_other_substr;
3369914b 1314 }
3369914b
DM
1315 }
1316 }
97136c8a 1317 else {
9fed8d02
DM
1318 /* float-only */
1319
7d2d37f5 1320 if (ml_anch) {
c75a3985
DM
1321 /* In the presence of ml_anch, we might be able to
1322 * find another \n without breaking the current float
1323 * constraint. */
1324
1325 /* strictly speaking this should be HOP3c(..., 1, ...),
1326 * but since we goto a block of code that's going to
1327 * search for the next \n if any, its safe here */
9fed8d02 1328 rx_origin++;
9fed8d02
DM
1329 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1330 " Looking for /%s^%s/m starting at offset %ld...\n",
1331 PL_colors[0], PL_colors[1],
1332 (long)(rx_origin - strpos)) );
9fed8d02 1333 goto postprocess_substr_matches;
ab60c45a 1334 }
c75a3985
DM
1335
1336 /* strictly speaking this can never be true; but might
1337 * be if we ever allow intuit without substrings */
1338 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
9fed8d02 1339 goto fail;
c75a3985 1340
000dfd2d 1341 rx_origin = rx_max_float;
9fed8d02
DM
1342 }
1343
c75a3985
DM
1344 /* at this point, any matching substrings have been
1345 * contradicted. Start again... */
1346
9fed8d02 1347 rx_origin = HOP3c(rx_origin, 1, strend);
557f47af
DM
1348
1349 /* uses bytes rather than char calculations for efficiency.
1350 * It's conservative: it errs on the side of doing 'goto restart',
1351 * where there is code that does a proper char-based test */
9fed8d02 1352 if (rx_origin + start_shift + end_shift > strend) {
40268e5b 1353 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
9fed8d02
DM
1354 " Could not match STCLASS...\n") );
1355 goto fail;
1356 }
1357 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1358 " Looking for %s substr starting at offset %ld...\n",
1359 (prog->substrs->check_ix ? "floating" : "anchored"),
1360 (long)(rx_origin + start_shift - strpos)) );
1361 goto restart;
6eb5f6b9 1362 }
9fed8d02 1363
c75a3985
DM
1364 /* Success !!! */
1365
5f9c6575 1366 if (rx_origin != s) {
a3621e74 1367 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 1368 " By STCLASS: moving %ld --> %ld\n",
5f9c6575 1369 (long)(rx_origin - strpos), (long)(s - strpos))
b7953727
JH
1370 );
1371 }
1372 else {
a3621e74 1373 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1dc475d0 1374 " Does not contradict STCLASS...\n");
b7953727
JH
1375 );
1376 }
6eb5f6b9 1377 }
ffad1e6a
DM
1378
1379 /* Decide whether using the substrings helped */
1380
1381 if (rx_origin != strpos) {
1382 /* Fixed substring is found far enough so that the match
1383 cannot start at strpos. */
1384
1385 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1386 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1387 }
1388 else {
70563e16
DM
1389 /* The found rx_origin position does not prohibit matching at
1390 * strpos, so calling intuit didn't gain us anything. Decrement
1391 * the BmUSEFUL() count on the check substring, and if we reach
1392 * zero, free it. */
1393 if (!(prog->intflags & PREGf_NAUGHTY)
ffad1e6a
DM
1394 && (utf8_target ? (
1395 prog->check_utf8 /* Could be deleted already */
1396 && --BmUSEFUL(prog->check_utf8) < 0
1397 && (prog->check_utf8 == prog->float_utf8)
1398 ) : (
1399 prog->check_substr /* Could be deleted already */
1400 && --BmUSEFUL(prog->check_substr) < 0
1401 && (prog->check_substr == prog->float_substr)
1402 )))
1403 {
1404 /* If flags & SOMETHING - do not do it many times on the same match */
1405 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1406 /* XXX Does the destruction order has to change with utf8_target? */
1407 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1408 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1409 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1410 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1411 check = NULL; /* abort */
ffad1e6a
DM
1412 /* XXXX This is a remnant of the old implementation. It
1413 looks wasteful, since now INTUIT can use many
1414 other heuristics. */
1415 prog->extflags &= ~RXf_USE_INTUIT;
ffad1e6a
DM
1416 }
1417 }
1418
1419 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1420 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1421 PL_colors[4], PL_colors[5], (long)(rx_origin - strpos)) );
1422
c765d6e0 1423 return rx_origin;
2c2d71f5
JH
1424
1425 fail_finish: /* Substring not found */
33b8afdf 1426 if (prog->check_substr || prog->check_utf8) /* could be removed already */
f2ed9b32 1427 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
cad2e5aa 1428 fail:
a3621e74 1429 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
e4584336 1430 PL_colors[4], PL_colors[5]));
bd61b366 1431 return NULL;
cad2e5aa 1432}
9661b544 1433
70563e16 1434
a0a388a1 1435#define DECL_TRIE_TYPE(scan) \
098b07d5
KW
1436 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1437 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold } \
fab2782b
YO
1438 trie_type = ((scan->flags == EXACT) \
1439 ? (utf8_target ? trie_utf8 : trie_plain) \
098b07d5
KW
1440 : (scan->flags == EXACTFA) \
1441 ? (utf8_target ? trie_utf8_exactfa_fold : trie_latin_utf8_exactfa_fold) \
1442 : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
fab2782b 1443
fd3249ee 1444#define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
baa60164 1445STMT_START { \
fab2782b 1446 STRLEN skiplen; \
baa60164 1447 U8 flags = FOLD_FLAGS_FULL; \
fab2782b 1448 switch (trie_type) { \
31f05a37 1449 case trie_utf8_exactfa_fold: \
baa60164 1450 flags |= FOLD_FLAGS_NOMIX_ASCII; \
924ba076 1451 /* FALLTHROUGH */ \
fab2782b
YO
1452 case trie_utf8_fold: \
1453 if ( foldlen>0 ) { \
c80e42f3 1454 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
fab2782b
YO
1455 foldlen -= len; \
1456 uscan += len; \
1457 len=0; \
1458 } else { \
445bf929 1459 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
fab2782b
YO
1460 len = UTF8SKIP(uc); \
1461 skiplen = UNISKIP( uvc ); \
1462 foldlen -= skiplen; \
1463 uscan = foldbuf + skiplen; \
1464 } \
1465 break; \
baa60164
KW
1466 case trie_latin_utf8_exactfa_fold: \
1467 flags |= FOLD_FLAGS_NOMIX_ASCII; \
924ba076 1468 /* FALLTHROUGH */ \
fab2782b
YO
1469 case trie_latin_utf8_fold: \
1470 if ( foldlen>0 ) { \
c80e42f3 1471 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
fab2782b
YO
1472 foldlen -= len; \
1473 uscan += len; \
1474 len=0; \
1475 } else { \
1476 len = 1; \
31f05a37 1477 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
fab2782b
YO
1478 skiplen = UNISKIP( uvc ); \
1479 foldlen -= skiplen; \
1480 uscan = foldbuf + skiplen; \
1481 } \
1482 break; \
1483 case trie_utf8: \
c80e42f3 1484 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
fab2782b
YO
1485 break; \
1486 case trie_plain: \
1487 uvc = (UV)*uc; \
1488 len = 1; \
1489 } \
1490 if (uvc < 256) { \
1491 charid = trie->charmap[ uvc ]; \
1492 } \
1493 else { \
1494 charid = 0; \
1495 if (widecharmap) { \
1496 SV** const svpp = hv_fetch(widecharmap, \
1497 (char*)&uvc, sizeof(UV), 0); \
1498 if (svpp) \
1499 charid = (U16)SvIV(*svpp); \
1500 } \
1501 } \
4cadc6a9
YO
1502} STMT_END
1503
ae7c5b9b
KW
1504#define DUMP_EXEC_POS(li,s,doutf8) \
1505 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1506 startpos, doutf8)
1507
c84a03c5 1508#define REXEC_FBC_EXACTISH_SCAN(COND) \
4cadc6a9
YO
1509STMT_START { \
1510 while (s <= e) { \
c84a03c5 1511 if ( (COND) \
fac1af77 1512 && (ln == 1 || folder(s, pat_string, ln)) \
02d5137b 1513 && (reginfo->intuit || regtry(reginfo, &s)) )\
4cadc6a9
YO
1514 goto got_it; \
1515 s++; \
1516 } \
1517} STMT_END
1518
c84a03c5 1519#define REXEC_FBC_UTF8_SCAN(CODE) \
4cadc6a9 1520STMT_START { \
9a902117 1521 while (s < strend) { \
c84a03c5 1522 CODE \
9a902117 1523 s += UTF8SKIP(s); \
4cadc6a9
YO
1524 } \
1525} STMT_END
1526
c84a03c5 1527#define REXEC_FBC_SCAN(CODE) \
4cadc6a9
YO
1528STMT_START { \
1529 while (s < strend) { \
c84a03c5 1530 CODE \
4cadc6a9
YO
1531 s++; \
1532 } \
1533} STMT_END
1534
05bd126c
KW
1535#define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1536REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1537 if (COND) { \
1538 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1539 goto got_it; \
1540 else \
1541 tmp = doevery; \
1542 } \
1543 else \
1544 tmp = 1; \
4cadc6a9
YO
1545)
1546
05bd126c
KW
1547#define REXEC_FBC_CLASS_SCAN(COND) \
1548REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1549 if (COND) { \
1550 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1551 goto got_it; \
1552 else \
1553 tmp = doevery; \
1554 } \
1555 else \
1556 tmp = 1; \
4cadc6a9
YO
1557)
1558
c84a03c5 1559#define REXEC_FBC_CSCAN(CONDUTF8,COND) \
baa60164 1560 if (utf8_target) { \
c84a03c5 1561 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
e1d1eefb
YO
1562 } \
1563 else { \
c84a03c5 1564 REXEC_FBC_CLASS_SCAN(COND); \
d981ef24 1565 }
05bd126c 1566
05bd126c
KW
1567/* The three macros below are slightly different versions of the same logic.
1568 *
1569 * The first is for /a and /aa when the target string is UTF-8. This can only
1570 * match ascii, but it must advance based on UTF-8. The other two handle the
1571 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1572 * for the boundary (or non-boundary) between a word and non-word character.
1573 * The utf8 and non-utf8 cases have the same logic, but the details must be
1574 * different. Find the "wordness" of the character just prior to this one, and
1575 * compare it with the wordness of this one. If they differ, we have a
1576 * boundary. At the beginning of the string, pretend that the previous
1577 * character was a new-line.
1578 *
1579 * All these macros uncleanly have side-effects with each other and outside
1580 * variables. So far it's been too much trouble to clean-up
1581 *
1582 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1583 * a word character or not.
1584 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1585 * word/non-word
1586 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1587 *
1588 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1589 * are looking for a boundary or for a non-boundary. If we are looking for a
1590 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1591 * see if this tentative match actually works, and if so, to quit the loop
1592 * here. And vice-versa if we are looking for a non-boundary.
1593 *
1594 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1595 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1596 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1597 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1598 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1599 * complement. But in that branch we complement tmp, meaning that at the
1600 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1601 * which means at the top of the loop in the next iteration, it is
1602 * TEST_NON_UTF8(s-1) */
b2f4e957 1603#define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
05bd126c
KW
1604 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1605 tmp = TEST_NON_UTF8(tmp); \
1606 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1607 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1608 tmp = !tmp; \
1609 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1610 } \
1611 else { \
1612 IF_FAIL; \
1613 } \
1614 ); \
1615
1616/* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1617 * TEST_UTF8 is a macro that for the same input code points returns identically
1618 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
236d82fd 1619#define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
05bd126c
KW
1620 if (s == reginfo->strbeg) { \
1621 tmp = '\n'; \
1622 } \
1623 else { /* Back-up to the start of the previous character */ \
1624 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1625 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
3db24e1e 1626 0, UTF8_ALLOW_DEFAULT); \
05bd126c
KW
1627 } \
1628 tmp = TEST_UV(tmp); \
1629 LOAD_UTF8_CHARCLASS_ALNUM(); \
1630 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1631 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1632 tmp = !tmp; \
1633 IF_SUCCESS; \
1634 } \
1635 else { \
1636 IF_FAIL; \
1637 } \
1638 );
cfaf538b 1639
05bd126c
KW
1640/* Like the above two macros. UTF8_CODE is the complete code for handling
1641 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1642 * macros below */
baa60164 1643#define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
63ac0dad 1644 if (utf8_target) { \
05bd126c 1645 UTF8_CODE \
63ac0dad
KW
1646 } \
1647 else { /* Not utf8 */ \
9d9163fb 1648 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
63ac0dad 1649 tmp = TEST_NON_UTF8(tmp); \
05bd126c 1650 REXEC_FBC_SCAN( /* advances s while s < strend */ \
63ac0dad 1651 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
63ac0dad 1652 IF_SUCCESS; \
760cfa8e 1653 tmp = !tmp; \
63ac0dad
KW
1654 } \
1655 else { \
1656 IF_FAIL; \
1657 } \
1658 ); \
1659 } \
c8519dc7
KW
1660 /* Here, things have been set up by the previous code so that tmp is the \
1661 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1662 * utf8ness of the target). We also have to check if this matches against \
1663 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1664 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1665 * string */ \
1666 if (tmp == ! TEST_NON_UTF8('\n')) { \
1667 IF_SUCCESS; \
1668 } \
1669 else { \
1670 IF_FAIL; \
1671 }
63ac0dad 1672
ae7c5b9b
KW
1673/* This is the macro to use when we want to see if something that looks like it
1674 * could match, actually does, and if so exits the loop */
1675#define REXEC_FBC_TRYIT \
1676 if ((reginfo->intuit || regtry(reginfo, &s))) \
1677 goto got_it
1678
1679/* The only difference between the BOUND and NBOUND cases is that
1680 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1681 * NBOUND. This is accomplished by passing it as either the if or else clause,
1682 * with the other one being empty (PLACEHOLDER is defined as empty).
1683 *
1684 * The TEST_FOO parameters are for operating on different forms of input, but
1685 * all should be ones that return identically for the same underlying code
1686 * points */
1687#define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1688 FBC_BOUND_COMMON( \
1689 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1690 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1691
1692#define FBC_BOUND_A(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1693 FBC_BOUND_COMMON( \
1694 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1695 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1696
1697#define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1698 FBC_BOUND_COMMON( \
1699 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1700 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1701
1702#define FBC_NBOUND_A(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1703 FBC_BOUND_COMMON( \
1704 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1705 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1706
05bd126c 1707
786e8c11 1708/* We know what class REx starts with. Try to find this position... */
02d5137b 1709/* if reginfo->intuit, its a dryrun */
786e8c11
YO
1710/* annoyingly all the vars in this routine have different names from their counterparts
1711 in regmatch. /grrr */
3c3eec57 1712STATIC char *
07be1b83 1713S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
f9176b44 1714 const char *strend, regmatch_info *reginfo)
a687059c 1715{
73104a1b
KW
1716 dVAR;
1717 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1718 char *pat_string; /* The pattern's exactish string */
1719 char *pat_end; /* ptr to end char of pat_string */
1720 re_fold_t folder; /* Function for computing non-utf8 folds */
1721 const U8 *fold_array; /* array for folding ords < 256 */
1722 STRLEN ln;
1723 STRLEN lnc;
73104a1b
KW
1724 U8 c1;
1725 U8 c2;
1726 char *e;
1727 I32 tmp = 1; /* Scratch variable? */
ba44c216 1728 const bool utf8_target = reginfo->is_utf8_target;
73104a1b 1729 UV utf8_fold_flags = 0;
f9176b44 1730 const bool is_utf8_pat = reginfo->is_utf8_pat;
3018b823
KW
1731 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1732 with a result inverts that result, as 0^1 =
1733 1 and 1^1 = 0 */
1734 _char_class_number classnum;
1735
73104a1b 1736 RXi_GET_DECL(prog,progi);
2f7f8cb1 1737
73104a1b 1738 PERL_ARGS_ASSERT_FIND_BYCLASS;
2f7f8cb1 1739
73104a1b
KW
1740 /* We know what class it must start with. */
1741 switch (OP(c)) {
1742 case ANYOF:
1743 if (utf8_target) {
1744 REXEC_FBC_UTF8_CLASS_SCAN(
3db24e1e 1745 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
73104a1b
KW
1746 }
1747 else {
1748 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1749 }
1750 break;
1751 case CANY:
1752 REXEC_FBC_SCAN(
02d5137b 1753 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
73104a1b
KW
1754 goto got_it;
1755 else
1756 tmp = doevery;
1757 );
1758 break;
1759
098b07d5
KW
1760 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1761 assert(! is_utf8_pat);
924ba076 1762 /* FALLTHROUGH */
73104a1b 1763 case EXACTFA:
984e6dd1 1764 if (is_utf8_pat || utf8_target) {
73104a1b
KW
1765 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1766 goto do_exactf_utf8;
1767 }
1768 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1769 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1770 goto do_exactf_non_utf8; /* isn't dealt with by these */
77a6d856 1771
2fdb7295
KW
1772 case EXACTF: /* This node only generated for non-utf8 patterns */
1773 assert(! is_utf8_pat);
73104a1b 1774 if (utf8_target) {
73104a1b
KW
1775 utf8_fold_flags = 0;
1776 goto do_exactf_utf8;
1777 }
1778 fold_array = PL_fold;
1779 folder = foldEQ;
1780 goto do_exactf_non_utf8;
1781
1782 case EXACTFL:
31f05a37 1783 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
cea315b6 1784 utf8_fold_flags = FOLDEQ_LOCALE;
73104a1b
KW
1785 goto do_exactf_utf8;
1786 }
1787 fold_array = PL_fold_locale;
1788 folder = foldEQ_locale;
1789 goto do_exactf_non_utf8;
3c760661 1790
73104a1b 1791 case EXACTFU_SS:
984e6dd1 1792 if (is_utf8_pat) {
73104a1b
KW
1793 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1794 }
1795 goto do_exactf_utf8;
16d951b7 1796
73104a1b 1797 case EXACTFU:
984e6dd1
DM
1798 if (is_utf8_pat || utf8_target) {
1799 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
73104a1b
KW
1800 goto do_exactf_utf8;
1801 }
fac1af77 1802
73104a1b
KW
1803 /* Any 'ss' in the pattern should have been replaced by regcomp,
1804 * so we don't have to worry here about this single special case
1805 * in the Latin1 range */
1806 fold_array = PL_fold_latin1;
1807 folder = foldEQ_latin1;
1808
924ba076 1809 /* FALLTHROUGH */
73104a1b
KW
1810
1811 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1812 are no glitches with fold-length differences
1813 between the target string and pattern */
1814
1815 /* The idea in the non-utf8 EXACTF* cases is to first find the
1816 * first character of the EXACTF* node and then, if necessary,
1817 * case-insensitively compare the full text of the node. c1 is the
1818 * first character. c2 is its fold. This logic will not work for
1819 * Unicode semantics and the german sharp ss, which hence should
1820 * not be compiled into a node that gets here. */
1821 pat_string = STRING(c);
1822 ln = STR_LEN(c); /* length to match in octets/bytes */
1823
1824 /* We know that we have to match at least 'ln' bytes (which is the
1825 * same as characters, since not utf8). If we have to match 3
1826 * characters, and there are only 2 availabe, we know without
1827 * trying that it will fail; so don't start a match past the
1828 * required minimum number from the far end */
ea3daa5d 1829 e = HOP3c(strend, -((SSize_t)ln), s);
73104a1b 1830
02d5137b 1831 if (reginfo->intuit && e < s) {
73104a1b
KW
1832 e = s; /* Due to minlen logic of intuit() */
1833 }
fac1af77 1834
73104a1b
KW
1835 c1 = *pat_string;
1836 c2 = fold_array[c1];
1837 if (c1 == c2) { /* If char and fold are the same */
1838 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1839 }
1840 else {
1841 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1842 }
1843 break;
fac1af77 1844
73104a1b
KW
1845 do_exactf_utf8:
1846 {
1847 unsigned expansion;
1848
1849 /* If one of the operands is in utf8, we can't use the simpler folding
1850 * above, due to the fact that many different characters can have the
1851 * same fold, or portion of a fold, or different- length fold */
1852 pat_string = STRING(c);
1853 ln = STR_LEN(c); /* length to match in octets/bytes */
1854 pat_end = pat_string + ln;
984e6dd1 1855 lnc = is_utf8_pat /* length to match in characters */
73104a1b
KW
1856 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1857 : ln;
1858
1859 /* We have 'lnc' characters to match in the pattern, but because of
1860 * multi-character folding, each character in the target can match
1861 * up to 3 characters (Unicode guarantees it will never exceed
1862 * this) if it is utf8-encoded; and up to 2 if not (based on the
1863 * fact that the Latin 1 folds are already determined, and the
1864 * only multi-char fold in that range is the sharp-s folding to
1865 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1866 * string character. Adjust lnc accordingly, rounding up, so that
1867 * if we need to match at least 4+1/3 chars, that really is 5. */
1868 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1869 lnc = (lnc + expansion - 1) / expansion;
1870
1871 /* As in the non-UTF8 case, if we have to match 3 characters, and
1872 * only 2 are left, it's guaranteed to fail, so don't start a
1873 * match that would require us to go beyond the end of the string
1874 */
ea3daa5d 1875 e = HOP3c(strend, -((SSize_t)lnc), s);
73104a1b 1876
02d5137b 1877 if (reginfo->intuit && e < s) {
73104a1b
KW
1878 e = s; /* Due to minlen logic of intuit() */
1879 }
0658cdde 1880
73104a1b
KW
1881 /* XXX Note that we could recalculate e to stop the loop earlier,
1882 * as the worst case expansion above will rarely be met, and as we
1883 * go along we would usually find that e moves further to the left.
1884 * This would happen only after we reached the point in the loop
1885 * where if there were no expansion we should fail. Unclear if
1886 * worth the expense */
1887
1888 while (s <= e) {
1889 char *my_strend= (char *)strend;
1890 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
984e6dd1 1891 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
02d5137b 1892 && (reginfo->intuit || regtry(reginfo, &s)) )
73104a1b
KW
1893 {
1894 goto got_it;
1895 }
1896 s += (utf8_target) ? UTF8SKIP(s) : 1;
1897 }
1898 break;
1899 }
236d82fd 1900
73104a1b 1901 case BOUNDL:
236d82fd 1902 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
73104a1b
KW
1903 break;
1904 case NBOUNDL:
236d82fd 1905 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
73104a1b
KW
1906 break;
1907 case BOUND:
236d82fd 1908 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
73104a1b
KW
1909 break;
1910 case BOUNDA:
236d82fd 1911 FBC_BOUND_A(isWORDCHAR_A, isWORDCHAR_A, isWORDCHAR_A);
73104a1b
KW
1912 break;
1913 case NBOUND:
236d82fd 1914 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
73104a1b
KW
1915 break;
1916 case NBOUNDA:
236d82fd 1917 FBC_NBOUND_A(isWORDCHAR_A, isWORDCHAR_A, isWORDCHAR_A);
73104a1b
KW
1918 break;
1919 case BOUNDU:
236d82fd 1920 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
73104a1b
KW
1921 break;
1922 case NBOUNDU:
236d82fd 1923 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
73104a1b 1924 break;
73104a1b
KW
1925 case LNBREAK:
1926 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
1927 is_LNBREAK_latin1_safe(s, strend)
1928 );
1929 break;
3018b823
KW
1930
1931 /* The argument to all the POSIX node types is the class number to pass to
1932 * _generic_isCC() to build a mask for searching in PL_charclass[] */
1933
1934 case NPOSIXL:
1935 to_complement = 1;
1936 /* FALLTHROUGH */
1937
1938 case POSIXL:
3018b823
KW
1939 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
1940 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
73104a1b 1941 break;
3018b823
KW
1942
1943 case NPOSIXD:
1944 to_complement = 1;
1945 /* FALLTHROUGH */
1946
1947 case POSIXD:
1948 if (utf8_target) {
1949 goto posix_utf8;
1950 }
1951 goto posixa;
1952
1953 case NPOSIXA:
1954 if (utf8_target) {
1955 /* The complement of something that matches only ASCII matches all
837226c8
KW
1956 * non-ASCII, plus everything in ASCII that isn't in the class. */
1957 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
3018b823
KW
1958 || ! _generic_isCC_A(*s, FLAGS(c)));
1959 break;
1960 }
1961
1962 to_complement = 1;
1963 /* FALLTHROUGH */
1964
73104a1b 1965 case POSIXA:
3018b823 1966 posixa:
73104a1b 1967 /* Don't need to worry about utf8, as it can match only a single
3018b823
KW
1968 * byte invariant character. */
1969 REXEC_FBC_CLASS_SCAN(
1970 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
73104a1b 1971 break;
3018b823
KW
1972
1973 case NPOSIXU:
1974 to_complement = 1;
1975 /* FALLTHROUGH */
1976
1977 case POSIXU:
1978 if (! utf8_target) {
1979 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
1980 FLAGS(c))));
1981 }
1982 else {
1983
1984 posix_utf8:
1985 classnum = (_char_class_number) FLAGS(c);
1986 if (classnum < _FIRST_NON_SWASH_CC) {
1987 while (s < strend) {
1988
1989 /* We avoid loading in the swash as long as possible, but
1990 * should we have to, we jump to a separate loop. This
1991 * extra 'if' statement is what keeps this code from being
1992 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
1993 if (UTF8_IS_ABOVE_LATIN1(*s)) {
1994 goto found_above_latin1;
1995 }
1996 if ((UTF8_IS_INVARIANT(*s)
1997 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
1998 classnum)))
1999 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2000 && to_complement ^ cBOOL(
94bb8c36
KW
2001 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2002 *(s + 1)),
3018b823
KW
2003 classnum))))
2004 {
02d5137b 2005 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
3018b823
KW
2006 goto got_it;
2007 else {
2008 tmp = doevery;
2009 }
2010 }
2011 else {
2012 tmp = 1;
2013 }
2014 s += UTF8SKIP(s);
2015 }
2016 }
2017 else switch (classnum) { /* These classes are implemented as
2018 macros */
2019 case _CC_ENUM_SPACE: /* XXX would require separate code if we
2020 revert the change of \v matching this */
924ba076 2021 /* FALLTHROUGH */
3018b823
KW
2022
2023 case _CC_ENUM_PSXSPC:
2024 REXEC_FBC_UTF8_CLASS_SCAN(
2025 to_complement ^ cBOOL(isSPACE_utf8(s)));
2026 break;
2027
2028 case _CC_ENUM_BLANK:
2029 REXEC_FBC_UTF8_CLASS_SCAN(
2030 to_complement ^ cBOOL(isBLANK_utf8(s)));
2031 break;
2032
2033 case _CC_ENUM_XDIGIT:
2034 REXEC_FBC_UTF8_CLASS_SCAN(
2035 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2036 break;
2037
2038 case _CC_ENUM_VERTSPACE:
2039 REXEC_FBC_UTF8_CLASS_SCAN(
2040 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2041 break;
2042
2043 case _CC_ENUM_CNTRL:
2044 REXEC_FBC_UTF8_CLASS_SCAN(
2045 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2046 break;
2047
2048 default:
2049 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
e5964223 2050 NOT_REACHED; /* NOTREACHED */
3018b823
KW
2051 }
2052 }
2053 break;
2054
2055 found_above_latin1: /* Here we have to load a swash to get the result
2056 for the current code point */
2057 if (! PL_utf8_swash_ptrs[classnum]) {
2058 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2059 PL_utf8_swash_ptrs[classnum] =
2a16ac92
KW
2060 _core_swash_init("utf8",
2061 "",
2062 &PL_sv_undef, 1, 0,
2063 PL_XPosix_ptrs[classnum], &flags);
3018b823
KW
2064 }
2065
2066 /* This is a copy of the loop above for swash classes, though using the
2067 * FBC macro instead of being expanded out. Since we've loaded the
2068 * swash, we don't have to check for that each time through the loop */
2069 REXEC_FBC_UTF8_CLASS_SCAN(
2070 to_complement ^ cBOOL(_generic_utf8(
2071 classnum,
2072 s,
2073 swash_fetch(PL_utf8_swash_ptrs[classnum],
2074 (U8 *) s, TRUE))));
73104a1b
KW
2075 break;
2076
2077 case AHOCORASICKC:
2078 case AHOCORASICK:
2079 {
2080 DECL_TRIE_TYPE(c);
2081 /* what trie are we using right now */
2082 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2083 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2084 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2085
2086 const char *last_start = strend - trie->minlen;
6148ee25 2087#ifdef DEBUGGING
73104a1b 2088 const char *real_start = s;
6148ee25 2089#endif
73104a1b
KW
2090 STRLEN maxlen = trie->maxlen;
2091 SV *sv_points;
2092 U8 **points; /* map of where we were in the input string
2093 when reading a given char. For ASCII this
2094 is unnecessary overhead as the relationship
2095 is always 1:1, but for Unicode, especially
2096 case folded Unicode this is not true. */
2097 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2098 U8 *bitmap=NULL;
2099
2100
2101 GET_RE_DEBUG_FLAGS_DECL;
2102
2103 /* We can't just allocate points here. We need to wrap it in
2104 * an SV so it gets freed properly if there is a croak while
2105 * running the match */
2106 ENTER;
2107 SAVETMPS;
2108 sv_points=newSV(maxlen * sizeof(U8 *));
2109 SvCUR_set(sv_points,
2110 maxlen * sizeof(U8 *));
2111 SvPOK_on(sv_points);
2112 sv_2mortal(sv_points);
2113 points=(U8**)SvPV_nolen(sv_points );
2114 if ( trie_type != trie_utf8_fold
2115 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2116 {
2117 if (trie->bitmap)
2118 bitmap=(U8*)trie->bitmap;
2119 else
2120 bitmap=(U8*)ANYOF_BITMAP(c);
2121 }
2122 /* this is the Aho-Corasick algorithm modified a touch
2123 to include special handling for long "unknown char" sequences.
2124 The basic idea being that we use AC as long as we are dealing
2125 with a possible matching char, when we encounter an unknown char
2126 (and we have not encountered an accepting state) we scan forward
2127 until we find a legal starting char.
2128 AC matching is basically that of trie matching, except that when
2129 we encounter a failing transition, we fall back to the current
2130 states "fail state", and try the current char again, a process
2131 we repeat until we reach the root state, state 1, or a legal
2132 transition. If we fail on the root state then we can either
2133 terminate if we have reached an accepting state previously, or
2134 restart the entire process from the beginning if we have not.
2135
2136 */
2137 while (s <= last_start) {
2138 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2139 U8 *uc = (U8*)s;
2140 U16 charid = 0;
2141 U32 base = 1;
2142 U32 state = 1;
2143 UV uvc = 0;
2144 STRLEN len = 0;
2145 STRLEN foldlen = 0;
2146 U8 *uscan = (U8*)NULL;
2147 U8 *leftmost = NULL;
2148#ifdef DEBUGGING
2149 U32 accepted_word= 0;
786e8c11 2150#endif
73104a1b
KW
2151 U32 pointpos = 0;
2152
2153 while ( state && uc <= (U8*)strend ) {
2154 int failed=0;
2155 U32 word = aho->states[ state ].wordnum;
2156
2157 if( state==1 ) {
2158 if ( bitmap ) {
2159 DEBUG_TRIE_EXECUTE_r(
2160 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2161 dump_exec_pos( (char *)uc, c, strend, real_start,
2162 (char *)uc, utf8_target );
2163 PerlIO_printf( Perl_debug_log,
2164 " Scanning for legal start char...\n");
2165 }
2166 );
2167 if (utf8_target) {
2168 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2169 uc += UTF8SKIP(uc);
2170 }
2171 } else {
2172 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2173 uc++;
2174 }
786e8c11 2175 }
73104a1b 2176 s= (char *)uc;
07be1b83 2177 }
73104a1b
KW
2178 if (uc >(U8*)last_start) break;
2179 }
2180
2181 if ( word ) {
2182 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2183 if (!leftmost || lpos < leftmost) {
2184 DEBUG_r(accepted_word=word);
2185 leftmost= lpos;
7016d6eb 2186 }
73104a1b 2187 if (base==0) break;
7016d6eb 2188
73104a1b
KW
2189 }
2190 points[pointpos++ % maxlen]= uc;
2191 if (foldlen || uc < (U8*)strend) {
2192 REXEC_TRIE_READ_CHAR(trie_type, trie,
2193 widecharmap, uc,
2194 uscan, len, uvc, charid, foldlen,
2195 foldbuf, uniflags);
2196 DEBUG_TRIE_EXECUTE_r({
2197 dump_exec_pos( (char *)uc, c, strend,
2198 real_start, s, utf8_target);
2199 PerlIO_printf(Perl_debug_log,
2200 " Charid:%3u CP:%4"UVxf" ",
2201 charid, uvc);
2202 });
2203 }
2204 else {
2205 len = 0;
2206 charid = 0;
2207 }
07be1b83 2208
73104a1b
KW
2209
2210 do {
6148ee25 2211#ifdef DEBUGGING
73104a1b 2212 word = aho->states[ state ].wordnum;
6148ee25 2213#endif
73104a1b
KW
2214 base = aho->states[ state ].trans.base;
2215
2216 DEBUG_TRIE_EXECUTE_r({
2217 if (failed)
2218 dump_exec_pos( (char *)uc, c, strend, real_start,
2219 s, utf8_target );
2220 PerlIO_printf( Perl_debug_log,
2221 "%sState: %4"UVxf", word=%"UVxf,
2222 failed ? " Fail transition to " : "",
2223 (UV)state, (UV)word);
2224 });
2225 if ( base ) {
2226 U32 tmp;
2227 I32 offset;
2228 if (charid &&
2229 ( ((offset = base + charid
2230 - 1 - trie->uniquecharcount)) >= 0)
2231 && ((U32)offset < trie->lasttrans)
2232 && trie->trans[offset].check == state
2233 && (tmp=trie->trans[offset].next))
2234 {
2235 DEBUG_TRIE_EXECUTE_r(
2236 PerlIO_printf( Perl_debug_log," - legal\n"));
2237 state = tmp;
2238 break;
07be1b83
YO
2239 }
2240 else {
786e8c11 2241 DEBUG_TRIE_EXECUTE_r(
73104a1b 2242 PerlIO_printf( Perl_debug_log," - fail\n"));
786e8c11 2243 failed = 1;
73104a1b 2244 state = aho->fail[state];
07be1b83 2245 }
07be1b83 2246 }
73104a1b
KW
2247 else {
2248 /* we must be accepting here */
2249 DEBUG_TRIE_EXECUTE_r(
2250 PerlIO_printf( Perl_debug_log," - accepting\n"));
2251 failed = 1;
2252 break;
786e8c11 2253 }
73104a1b
KW
2254 } while(state);
2255 uc += len;
2256 if (failed) {
2257 if (leftmost)
2258 break;
2259 if (!state) state = 1;
07be1b83 2260 }
73104a1b
KW
2261 }
2262 if ( aho->states[ state ].wordnum ) {
2263 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2264 if (!leftmost || lpos < leftmost) {
2265 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2266 leftmost = lpos;
07be1b83
YO
2267 }
2268 }
73104a1b
KW
2269 if (leftmost) {
2270 s = (char*)leftmost;
2271 DEBUG_TRIE_EXECUTE_r({
2272 PerlIO_printf(
2273 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2274 (UV)accepted_word, (IV)(s - real_start)
2275 );
2276 });
02d5137b 2277 if (reginfo->intuit || regtry(reginfo, &s)) {
73104a1b
KW
2278 FREETMPS;
2279 LEAVE;
2280 goto got_it;
2281 }
2282 s = HOPc(s,1);
2283 DEBUG_TRIE_EXECUTE_r({
2284 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2285 });
2286 } else {
2287 DEBUG_TRIE_EXECUTE_r(
2288 PerlIO_printf( Perl_debug_log,"No match.\n"));
2289 break;
2290 }
2291 }
2292 FREETMPS;
2293 LEAVE;
2294 }
2295 break;
2296 default:
2297 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
73104a1b
KW
2298 }
2299 return 0;
2300 got_it:
2301 return s;
6eb5f6b9
JH
2302}
2303
60165aa4
DM
2304/* set RX_SAVED_COPY, RX_SUBBEG etc.
2305 * flags have same meanings as with regexec_flags() */
2306
749f4950
DM
2307static void
2308S_reg_set_capture_string(pTHX_ REGEXP * const rx,
60165aa4
DM
2309 char *strbeg,
2310 char *strend,
2311 SV *sv,
2312 U32 flags,
2313 bool utf8_target)
2314{
2315 struct regexp *const prog = ReANY(rx);
2316
60165aa4
DM
2317 if (flags & REXEC_COPY_STR) {
2318#ifdef PERL_ANY_COW
2319 if (SvCANCOW(sv)) {
2320 if (DEBUG_C_TEST) {
2321 PerlIO_printf(Perl_debug_log,
2322 "Copy on write: regexp capture, type %d\n",
2323 (int) SvTYPE(sv));
2324 }
5411a0e5
DM
2325 /* Create a new COW SV to share the match string and store
2326 * in saved_copy, unless the current COW SV in saved_copy
2327 * is valid and suitable for our purpose */
2328 if (( prog->saved_copy
2329 && SvIsCOW(prog->saved_copy)
2330 && SvPOKp(prog->saved_copy)
2331 && SvIsCOW(sv)
2332 && SvPOKp(sv)
2333 && SvPVX(sv) == SvPVX(prog->saved_copy)))
a76b0e90 2334 {
5411a0e5
DM
2335 /* just reuse saved_copy SV */
2336 if (RXp_MATCH_COPIED(prog)) {
2337 Safefree(prog->subbeg);
2338 RXp_MATCH_COPIED_off(prog);
2339 }
2340 }
2341 else {
2342 /* create new COW SV to share string */
a76b0e90
DM
2343 RX_MATCH_COPY_FREE(rx);
2344 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
a76b0e90 2345 }
5411a0e5
DM
2346 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2347 assert (SvPOKp(prog->saved_copy));
60165aa4
DM
2348 prog->sublen = strend - strbeg;
2349 prog->suboffset = 0;
2350 prog->subcoffset = 0;
2351 } else
2352#endif
2353 {
99a90e59
FC
2354 SSize_t min = 0;
2355 SSize_t max = strend - strbeg;
ea3daa5d 2356 SSize_t sublen;
60165aa4
DM
2357
2358 if ( (flags & REXEC_COPY_SKIP_POST)
e322109a 2359 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
60165aa4
DM
2360 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2361 ) { /* don't copy $' part of string */
2362 U32 n = 0;
2363 max = -1;
2364 /* calculate the right-most part of the string covered
2365 * by a capture. Due to look-ahead, this may be to
2366 * the right of $&, so we have to scan all captures */
2367 while (n <= prog->lastparen) {
2368 if (prog->offs[n].end > max)
2369 max = prog->offs[n].end;
2370 n++;
2371 }
2372 if (max == -1)
2373 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2374 ? prog->offs[0].start
2375 : 0;
2376 assert(max >= 0 && max <= strend - strbeg);
2377 }
2378
2379 if ( (flags & REXEC_COPY_SKIP_PRE)
e322109a 2380 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
60165aa4
DM
2381 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2382 ) { /* don't copy $` part of string */
2383 U32 n = 0;
2384 min = max;
2385 /* calculate the left-most part of the string covered
2386 * by a capture. Due to look-behind, this may be to
2387 * the left of $&, so we have to scan all captures */
2388 while (min && n <= prog->lastparen) {
2389 if ( prog->offs[n].start != -1
2390 && prog->offs[n].start < min)
2391 {
2392 min = prog->offs[n].start;
2393 }
2394 n++;
2395 }
2396 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2397 && min > prog->offs[0].end
2398 )
2399 min = prog->offs[0].end;
2400
2401 }
2402
2403 assert(min >= 0 && min <= max && min <= strend - strbeg);
2404 sublen = max - min;
2405
2406 if (RX_MATCH_COPIED(rx)) {
2407 if (sublen > prog->sublen)
2408 prog->subbeg =
2409 (char*)saferealloc(prog->subbeg, sublen+1);
2410 }
2411 else
2412 prog->subbeg = (char*)safemalloc(sublen+1);
2413 Copy(strbeg + min, prog->subbeg, sublen, char);
2414 prog->subbeg[sublen] = '\0';
2415 prog->suboffset = min;
2416 prog->sublen = sublen;
2417 RX_MATCH_COPIED_on(rx);
2418 }
2419 prog->subcoffset = prog->suboffset;
2420 if (prog->suboffset && utf8_target) {
2421 /* Convert byte offset to chars.
2422 * XXX ideally should only compute this if @-/@+
2423 * has been seen, a la PL_sawampersand ??? */
2424
2425 /* If there's a direct correspondence between the
2426 * string which we're matching and the original SV,
2427 * then we can use the utf8 len cache associated with
2428 * the SV. In particular, it means that under //g,
2429 * sv_pos_b2u() will use the previously cached
2430 * position to speed up working out the new length of
2431 * subcoffset, rather than counting from the start of
2432 * the string each time. This stops
2433 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2434 * from going quadratic */
2435 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
ea3daa5d
FC
2436 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2437 SV_GMAGIC|SV_CONST_RETURN);
60165aa4
DM
2438 else
2439 prog->subcoffset = utf8_length((U8*)strbeg,
2440 (U8*)(strbeg+prog->suboffset));
2441 }
2442 }
2443 else {
2444 RX_MATCH_COPY_FREE(rx);
2445 prog->subbeg = strbeg;
2446 prog->suboffset = 0;
2447 prog->subcoffset = 0;
2448 prog->sublen = strend - strbeg;
2449 }
2450}
2451
2452
2453
fae667d5 2454
6eb5f6b9
JH
2455/*
2456 - regexec_flags - match a regexp against a string
2457 */
2458I32
5aaab254 2459Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
ea3daa5d 2460 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
8fd1a950
DM
2461/* stringarg: the point in the string at which to begin matching */
2462/* strend: pointer to null at end of string */
2463/* strbeg: real beginning of string */
2464/* minend: end of match must be >= minend bytes after stringarg. */
2465/* sv: SV being matched: only used for utf8 flag, pos() etc; string
2466 * itself is accessed via the pointers above */
2467/* data: May be used for some additional optimizations.
d058ec57 2468 Currently unused. */
a340edde 2469/* flags: For optimizations. See REXEC_* in regexp.h */
8fd1a950 2470
6eb5f6b9 2471{
8d919b0a 2472 struct regexp *const prog = ReANY(rx);
5aaab254 2473 char *s;
eb578fdb 2474 regnode *c;
03c83e26 2475 char *startpos;
ea3daa5d
FC
2476 SSize_t minlen; /* must match at least this many chars */
2477 SSize_t dontbother = 0; /* how many characters not to try at end */
f2ed9b32 2478 const bool utf8_target = cBOOL(DO_UTF8(sv));
2757e526 2479 I32 multiline;
f8fc2ecf 2480 RXi_GET_DECL(prog,progi);
02d5137b
DM
2481 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2482 regmatch_info *const reginfo = &reginfo_buf;
e9105d30 2483 regexp_paren_pair *swap = NULL;
006f26b2 2484 I32 oldsave;
a3621e74
YO
2485 GET_RE_DEBUG_FLAGS_DECL;
2486
7918f24d 2487 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
9d4ba2ae 2488 PERL_UNUSED_ARG(data);
6eb5f6b9
JH
2489
2490 /* Be paranoid... */
03c83e26 2491 if (prog == NULL || stringarg == NULL) {
6eb5f6b9 2492 Perl_croak(aTHX_ "NULL regexp parameter");
6eb5f6b9
JH
2493 }
2494
6c3fea77 2495 DEBUG_EXECUTE_r(
03c83e26 2496 debug_start_match(rx, utf8_target, stringarg, strend,
6c3fea77
DM
2497 "Matching");
2498 );
8adc0f72 2499
b342a604
DM
2500 startpos = stringarg;
2501
58430ea8 2502 if (prog->intflags & PREGf_GPOS_SEEN) {
d307c076
DM
2503 MAGIC *mg;
2504
fef7148b
DM
2505 /* set reginfo->ganch, the position where \G can match */
2506
2507 reginfo->ganch =
2508 (flags & REXEC_IGNOREPOS)
2509 ? stringarg /* use start pos rather than pos() */
2510 : (sv && (mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
25fdce4a
FC
2511 /* Defined pos(): */
2512 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
fef7148b
DM
2513 : strbeg; /* pos() not defined; use start of string */
2514
2515 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
7b0eb0b8 2516 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
fef7148b 2517
03c83e26
DM
2518 /* in the presence of \G, we may need to start looking earlier in
2519 * the string than the suggested start point of stringarg:
0b2c2a84 2520 * if prog->gofs is set, then that's a known, fixed minimum
03c83e26
DM
2521 * offset, such as
2522 * /..\G/: gofs = 2
2523 * /ab|c\G/: gofs = 1
2524 * or if the minimum offset isn't known, then we have to go back
2525 * to the start of the string, e.g. /w+\G/
2526 */
2bfbe302 2527
8e1490ee 2528 if (prog->intflags & PREGf_ANCH_GPOS) {
2bfbe302
DM
2529 startpos = reginfo->ganch - prog->gofs;
2530 if (startpos <
2531 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2532 {
2533 DEBUG_r(PerlIO_printf(Perl_debug_log,
2534 "fail: ganch-gofs before earliest possible start\n"));
2535 return 0;
2536 }
2537 }
2538 else if (prog->gofs) {
b342a604
DM
2539 if (startpos - prog->gofs < strbeg)
2540 startpos = strbeg;
2541 else
2542 startpos -= prog->gofs;
03c83e26 2543 }
58430ea8 2544 else if (prog->intflags & PREGf_GPOS_FLOAT)
b342a604 2545 startpos = strbeg;
03c83e26
DM
2546 }
2547
2548 minlen = prog->minlen;
b342a604 2549 if ((startpos + minlen) > strend || startpos < strbeg) {
03c83e26
DM
2550 DEBUG_r(PerlIO_printf(Perl_debug_log,
2551 "Regex match can't succeed, so not even tried\n"));
2552 return 0;
2553 }
2554
63a3746a
DM
2555 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2556 * which will call destuctors to reset PL_regmatch_state, free higher
2557 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2558 * regmatch_info_aux_eval */
2559
2560 oldsave = PL_savestack_ix;
2561
dfa77d06
DM
2562 s = startpos;
2563
e322109a 2564 if ((prog->extflags & RXf_USE_INTUIT)
7fadf4a7
DM
2565 && !(flags & REXEC_CHECKED))
2566 {
dfa77d06 2567 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
7fadf4a7 2568 flags, NULL);
dfa77d06 2569 if (!s)
7fadf4a7
DM
2570 return 0;
2571
e322109a 2572 if (prog->extflags & RXf_CHECK_ALL) {
7fadf4a7
DM
2573 /* we can match based purely on the result of INTUIT.
2574 * Set up captures etc just for $& and $-[0]
2575 * (an intuit-only match wont have $1,$2,..) */
2576 assert(!prog->nparens);
d5e7783a
DM
2577
2578 /* s/// doesn't like it if $& is earlier than where we asked it to
2579 * start searching (which can happen on something like /.\G/) */
2580 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2581 && (s < stringarg))
2582 {
2583 /* this should only be possible under \G */
58430ea8 2584 assert(prog->intflags & PREGf_GPOS_SEEN);
d5e7783a
DM
2585 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2586 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2587 goto phooey;
2588 }
2589
7fadf4a7
DM
2590 /* match via INTUIT shouldn't have any captures.
2591 * Let @-, @+, $^N know */
2592 prog->lastparen = prog->lastcloseparen = 0;
2593 RX_MATCH_UTF8_set(rx, utf8_target);
3ff69bd6
DM
2594 prog->offs[0].start = s - strbeg;
2595 prog->offs[0].end = utf8_target
2596 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2597 : s - strbeg + prog->minlenret;
7fadf4a7 2598 if ( !(flags & REXEC_NOT_FIRST) )
749f4950 2599 S_reg_set_capture_string(aTHX_ rx,
7fadf4a7
DM
2600 strbeg, strend,
2601 sv, flags, utf8_target);
2602
7fadf4a7
DM
2603 return 1;
2604 }
2605 }
2606
6c3fea77 2607 multiline = prog->extflags & RXf_PMf_MULTILINE;
1de06328 2608
dfa77d06 2609 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
a3621e74 2610 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
a72c7584
JH
2611 "String too short [regexec_flags]...\n"));
2612 goto phooey;
1aa99e6b 2613 }
1de06328 2614
6eb5f6b9 2615 /* Check validity of program. */
f8fc2ecf 2616 if (UCHARAT(progi->program) != REG_MAGIC) {
6eb5f6b9
JH
2617 Perl_croak(aTHX_ "corrupted regexp program");
2618 }
2619
1738e041 2620 RX_MATCH_TAINTED_off(rx);
ab4e48c1 2621 RX_MATCH_UTF8_set(rx, utf8_target);
1738e041 2622
6c3fea77
DM
2623 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2624 reginfo->intuit = 0;
2625 reginfo->is_utf8_target = cBOOL(utf8_target);
02d5137b
DM
2626 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2627 reginfo->warned = FALSE;
9d9163fb 2628 reginfo->strbeg = strbeg;
02d5137b 2629 reginfo->sv = sv;
1cb48e53 2630 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
220db18a 2631 reginfo->strend = strend;
6eb5f6b9 2632 /* see how far we have to get to not match where we matched before */
fe3974be 2633 reginfo->till = stringarg + minend;
6eb5f6b9 2634
60779a30 2635 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
82c23608
FC
2636 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2637 S_cleanup_regmatch_info_aux has executed (registered by
2638 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2639 magic belonging to this SV.
2640 Not newSVsv, either, as it does not COW.
2641 */
2642 reginfo->sv = newSV(0);
4cba5ac0 2643 SvSetSV_nosteal(reginfo->sv, sv);
82c23608
FC
2644 SAVEFREESV(reginfo->sv);
2645 }
2646
331b2dcc
DM
2647 /* reserve next 2 or 3 slots in PL_regmatch_state:
2648 * slot N+0: may currently be in use: skip it
2649 * slot N+1: use for regmatch_info_aux struct
2650 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2651 * slot N+3: ready for use by regmatch()
2652 */
bf2039a9 2653
331b2dcc
DM
2654 {
2655 regmatch_state *old_regmatch_state;
2656 regmatch_slab *old_regmatch_slab;
2657 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2658
2659 /* on first ever match, allocate first slab */
2660 if (!PL_regmatch_slab) {
2661 Newx(PL_regmatch_slab, 1, regmatch_slab);
2662 PL_regmatch_slab->prev = NULL;
2663 PL_regmatch_slab->next = NULL;
2664 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2665 }
bf2039a9 2666
331b2dcc
DM
2667 old_regmatch_state = PL_regmatch_state;
2668 old_regmatch_slab = PL_regmatch_slab;
bf2039a9 2669
331b2dcc
DM
2670 for (i=0; i <= max; i++) {
2671 if (i == 1)
2672 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
2673 else if (i ==2)
2674 reginfo->info_aux_eval =
2675 reginfo->info_aux->info_aux_eval =
2676 &(PL_regmatch_state->u.info_aux_eval);
bf2039a9 2677
331b2dcc
DM
2678 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
2679 PL_regmatch_state = S_push_slab(aTHX);
2680 }
bf2039a9 2681
331b2dcc
DM
2682 /* note initial PL_regmatch_state position; at end of match we'll
2683 * pop back to there and free any higher slabs */
bf2039a9 2684
331b2dcc
DM
2685 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
2686 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
2ac8ff4b 2687 reginfo->info_aux->poscache = NULL;
bf2039a9 2688
331b2dcc 2689 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
bf2039a9 2690
331b2dcc
DM
2691 if ((prog->extflags & RXf_EVAL_SEEN))
2692 S_setup_eval_state(aTHX_ reginfo);
2693 else
2694 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
bf2039a9 2695 }
d3aa529c 2696
6eb5f6b9 2697 /* If there is a "must appear" string, look for it. */
6eb5f6b9 2698
288b8c02 2699 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
e9105d30
GG
2700 /* We have to be careful. If the previous successful match
2701 was from this regex we don't want a subsequent partially
2702 successful match to clobber the old results.
2703 So when we detect this possibility we add a swap buffer
d8da0584
KW
2704 to the re, and switch the buffer each match. If we fail,
2705 we switch it back; otherwise we leave it swapped.
e9105d30
GG
2706 */
2707 swap = prog->offs;
2708 /* do we need a save destructor here for eval dies? */
2709 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
495f47a5
DM
2710 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2711 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2712 PTR2UV(prog),
2713 PTR2UV(swap),
2714 PTR2UV(prog->offs)
2715 ));
c74340f9 2716 }
6eb5f6b9
JH
2717
2718 /* Simplest case: anchored match need be tried only once. */
d3d47aac 2719 /* [unless only anchor is MBOL - implying multiline is set] */
8e1490ee 2720 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3542935d 2721 if (s == startpos && regtry(reginfo, &s))
6eb5f6b9 2722 goto got_it;
8e1490ee 2723 else if (multiline || (prog->intflags & (PREGf_IMPLICIT | PREGf_ANCH_MBOL))) /* XXXX SBOL? */
6eb5f6b9
JH
2724 {
2725 char *end;
2726
2727 if (minlen)
2728 dontbother = minlen - 1;
1aa99e6b 2729 end = HOP3c(strend, -dontbother, strbeg) - 1;
6eb5f6b9 2730 /* for multiline we only have to try after newlines */
33b8afdf 2731 if (prog->check_substr || prog->check_utf8) {
92f3d482
YO
2732 /* because of the goto we can not easily reuse the macros for bifurcating the
2733 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2734 if (utf8_target) {
2735 if (s == startpos)
2736 goto after_try_utf8;
2737 while (1) {
02d5137b 2738 if (regtry(reginfo, &s)) {
92f3d482
YO
2739 goto got_it;
2740 }
2741 after_try_utf8:
2742 if (s > end) {
2743 goto phooey;
2744 }
2745 if (prog->extflags & RXf_USE_INTUIT) {
52a21eb3
DM
2746 s = re_intuit_start(rx, sv, strbeg,
2747 s + UTF8SKIP(s), strend, flags, NULL);
92f3d482
YO
2748 if (!s) {
2749 goto phooey;
2750 }
2751 }
2752 else {
2753 s += UTF8SKIP(s);
2754 }
2755 }
2756 } /* end search for check string in unicode */
2757 else {
2758 if (s == startpos) {
2759 goto after_try_latin;
2760 }
2761 while (1) {
02d5137b 2762 if (regtry(reginfo, &s)) {
92f3d482
YO
2763 goto got_it;
2764 }
2765 after_try_latin:
2766 if (s > end) {
2767 goto phooey;
2768 }
2769 if (prog->extflags & RXf_USE_INTUIT) {
52a21eb3
DM
2770 s = re_intuit_start(rx, sv, strbeg,
2771 s + 1, strend, flags, NULL);
92f3d482
YO
2772 if (!s) {
2773 goto phooey;
2774 }
2775 }
2776 else {
2777 s++;
2778 }
2779 }
2780 } /* end search for check string in latin*/
2781 } /* end search for check string */
2782 else { /* search for newline */
2783 if (s > startpos) {
2784 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
6eb5f6b9 2785 s--;
92f3d482 2786 }
21eede78
YO
2787 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2788 while (s <= end) { /* note it could be possible to match at the end of the string */
6eb5f6b9 2789 if (*s++ == '\n') { /* don't need PL_utf8skip here */
02d5137b 2790 if (regtry(reginfo, &s))
6eb5f6b9
JH
2791 goto got_it;
2792 }
92f3d482
YO
2793 }
2794 } /* end search for newline */
2795 } /* end anchored/multiline check string search */
6eb5f6b9 2796 goto phooey;
a8430a8b 2797 } else if (prog->intflags & PREGf_ANCH_GPOS)
f9f4320a 2798 {
a8430a8b
YO
2799 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
2800 assert(prog->intflags & PREGf_GPOS_SEEN);
2bfbe302
DM
2801 /* For anchored \G, the only position it can match from is
2802 * (ganch-gofs); we already set startpos to this above; if intuit
2803 * moved us on from there, we can't possibly succeed */
2804 assert(startpos == reginfo->ganch - prog->gofs);
2805 if (s == startpos && regtry(reginfo, &s))
6eb5f6b9
JH
2806 goto got_it;
2807 goto phooey;
2808 }
2809
2810 /* Messy cases: unanchored match. */
bbe252da 2811 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
6eb5f6b9 2812 /* we have /x+whatever/ */
984e6dd1 2813 /* it must be a one character string (XXXX Except is_utf8_pat?) */
33b8afdf 2814 char ch;
bf93d4cc
GS
2815#ifdef DEBUGGING
2816 int did_match = 0;
2817#endif
f2ed9b32 2818 if (utf8_target) {
7e0d5ad7
KW
2819 if (! prog->anchored_utf8) {
2820 to_utf8_substr(prog);
2821 }
2822 ch = SvPVX_const(prog->anchored_utf8)[0];
4cadc6a9 2823 REXEC_FBC_SCAN(
6eb5f6b9 2824 if (*s == ch) {
a3621e74 2825 DEBUG_EXECUTE_r( did_match = 1 );
02d5137b 2826 if (regtry(reginfo, &s)) goto got_it;
6eb5f6b9
JH
2827 s += UTF8SKIP(s);
2828 while (s < strend && *s == ch)
2829 s += UTF8SKIP(s);
2830 }
4cadc6a9 2831 );
7e0d5ad7 2832
6eb5f6b9
JH
2833 }
2834 else {
7e0d5ad7
KW
2835 if (! prog->anchored_substr) {
2836 if (! to_byte_substr(prog)) {
6b54ddc5 2837 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
2838 }
2839 }
2840 ch = SvPVX_const(prog->anchored_substr)[0];
4cadc6a9 2841 REXEC_FBC_SCAN(
6eb5f6b9 2842 if (*s == ch) {
a3621e74 2843 DEBUG_EXECUTE_r( did_match = 1 );
02d5137b 2844 if (regtry(reginfo, &s)) goto got_it;
6eb5f6b9
JH
2845 s++;
2846 while (s < strend && *s == ch)
2847 s++;
2848 }
4cadc6a9 2849 );
6eb5f6b9 2850 }
a3621e74 2851 DEBUG_EXECUTE_r(if (!did_match)
bf93d4cc 2852 PerlIO_printf(Perl_debug_log,
b7953727
JH
2853 "Did not find anchored character...\n")
2854 );
6eb5f6b9 2855 }
a0714e2c
SS
2856 else if (prog->anchored_substr != NULL
2857 || prog->anchored_utf8 != NULL
2858 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
33b8afdf
JH
2859 && prog->float_max_offset < strend - s)) {
2860 SV *must;
ea3daa5d
FC
2861 SSize_t back_max;
2862 SSize_t back_min;
33b8afdf 2863 char *last;
6eb5f6b9 2864 char *last1; /* Last position checked before */
bf93d4cc
GS
2865#ifdef DEBUGGING
2866 int did_match = 0;
2867#endif
33b8afdf 2868 if (prog->anchored_substr || prog->anchored_utf8) {
7e0d5ad7
KW
2869 if (utf8_target) {
2870 if (! prog->anchored_utf8) {
2871 to_utf8_substr(prog);
2872 }
2873 must = prog->anchored_utf8;
2874 }
2875 else {
2876 if (! prog->anchored_substr) {
2877 if (! to_byte_substr(prog)) {
6b54ddc5 2878 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
2879 }
2880 }
2881 must = prog->anchored_substr;
2882 }
33b8afdf
JH
2883 back_max = back_min = prog->anchored_offset;
2884 } else {
7e0d5ad7
KW
2885 if (utf8_target) {
2886 if (! prog->float_utf8) {
2887 to_utf8_substr(prog);
2888 }
2889 must = prog->float_utf8;
2890 }
2891 else {
2892 if (! prog->float_substr) {
2893 if (! to_byte_substr(prog)) {
6b54ddc5 2894 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
2895 }
2896 }
2897 must = prog->float_substr;
2898 }
33b8afdf
JH
2899 back_max = prog->float_max_offset;
2900 back_min = prog->float_min_offset;
2901 }
1de06328 2902
1de06328
YO
2903 if (back_min<0) {
2904 last = strend;
2905 } else {
2906 last = HOP3c(strend, /* Cannot start after this */
ea3daa5d 2907 -(SSize_t)(CHR_SVLEN(must)
1de06328
YO
2908 - (SvTAIL(must) != 0) + back_min), strbeg);
2909 }
9d9163fb 2910 if (s > reginfo->strbeg)
6eb5f6b9
JH
2911 last1 = HOPc(s, -1);
2912 else
2913 last1 = s - 1; /* bogus */
2914
a0288114 2915 /* XXXX check_substr already used to find "s", can optimize if
6eb5f6b9 2916 check_substr==must. */
bf05793b 2917 dontbother = 0;
6eb5f6b9
JH
2918 strend = HOPc(strend, -dontbother);
2919 while ( (s <= last) &&
e50d57d4 2920 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
9041c2e3 2921 (unsigned char*)strend, must,
c33e64f0 2922 multiline ? FBMrf_MULTILINE : 0)) ) {
a3621e74 2923 DEBUG_EXECUTE_r( did_match = 1 );
6eb5f6b9
JH
2924 if (HOPc(s, -back_max) > last1) {
2925 last1 = HOPc(s, -back_min);
2926 s = HOPc(s, -back_max);
2927 }
2928 else {
9d9163fb
DM
2929 char * const t = (last1 >= reginfo->strbeg)
2930 ? HOPc(last1, 1) : last1 + 1;
6eb5f6b9
JH
2931
2932 last1 = HOPc(s, -back_min);
52657f30 2933 s = t;
6eb5f6b9 2934 }
f2ed9b32 2935 if (utf8_target) {
6eb5f6b9 2936 while (s <= last1) {
02d5137b 2937 if (regtry(reginfo, &s))
6eb5f6b9 2938 goto got_it;
7016d6eb
DM
2939 if (s >= last1) {
2940 s++; /* to break out of outer loop */
2941 break;
2942 }
2943 s += UTF8SKIP(s);
6eb5f6b9
JH
2944 }
2945 }
2946 else {
2947 while (s <= last1) {
02d5137b 2948 if (regtry(reginfo, &s))
6eb5f6b9
JH
2949 goto got_it;
2950 s++;
2951 }
2952 }
2953 }
ab3bbdeb 2954 DEBUG_EXECUTE_r(if (!did_match) {
f2ed9b32 2955 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
ab3bbdeb
YO
2956 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2957 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
33b8afdf 2958 ((must == prog->anchored_substr || must == prog->anchored_utf8)
bf93d4cc 2959 ? "anchored" : "floating"),
ab3bbdeb
YO
2960 quoted, RE_SV_TAIL(must));
2961 });
6eb5f6b9
JH
2962 goto phooey;
2963 }
f8fc2ecf 2964 else if ( (c = progi->regstclass) ) {
f14c76ed 2965 if (minlen) {
f8fc2ecf 2966 const OPCODE op = OP(progi->regstclass);
66e933ab 2967 /* don't bother with what can't match */
786e8c11 2968 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
f14c76ed
RGS
2969 strend = HOPc(strend, -(minlen - 1));
2970 }
a3621e74 2971 DEBUG_EXECUTE_r({
be8e71aa 2972 SV * const prop = sv_newmortal();
8b9781c9 2973 regprop(prog, prop, c, reginfo, NULL);
0df25f3d 2974 {
f2ed9b32 2975 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
ab3bbdeb 2976 s,strend-s,60);
0df25f3d 2977 PerlIO_printf(Perl_debug_log,
1c8f8eb1 2978 "Matching stclass %.*s against %s (%d bytes)\n",
e4f74956 2979 (int)SvCUR(prop), SvPVX_const(prop),
ab3bbdeb 2980 quoted, (int)(strend - s));
0df25f3d 2981 }
ffc61ed2 2982 });
f9176b44 2983 if (find_byclass(prog, c, s, strend, reginfo))
6eb5f6b9 2984 goto got_it;
07be1b83 2985 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
d6a28714
JH
2986 }
2987 else {
2988 dontbother = 0;
a0714e2c 2989 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
33b8afdf 2990 /* Trim the end. */
6af40bd7 2991 char *last= NULL;
33b8afdf 2992 SV* float_real;
c33e64f0
FC
2993 STRLEN len;
2994 const char *little;
33b8afdf 2995
7e0d5ad7
KW
2996 if (utf8_target) {
2997 if (! prog->float_utf8) {
2998 to_utf8_substr(prog);
2999 }
3000 float_real = prog->float_utf8;
3001 }
3002 else {
3003 if (! prog->float_substr) {
3004 if (! to_byte_substr(prog)) {
6b54ddc5 3005 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
7e0d5ad7
KW
3006 }
3007 }
3008 float_real = prog->float_substr;
3009 }
d6a28714 3010
c33e64f0
FC
3011 little = SvPV_const(float_real, len);
3012 if (SvTAIL(float_real)) {
7f18ad16
KW
3013 /* This means that float_real contains an artificial \n on
3014 * the end due to the presence of something like this:
3015 * /foo$/ where we can match both "foo" and "foo\n" at the
3016 * end of the string. So we have to compare the end of the
3017 * string first against the float_real without the \n and
3018 * then against the full float_real with the string. We
3019 * have to watch out for cases where the string might be
3020 * smaller than the float_real or the float_real without
3021 * the \n. */
1a13b075
YO
3022 char *checkpos= strend - len;
3023 DEBUG_OPTIMISE_r(
3024 PerlIO_printf(Perl_debug_log,
3025 "%sChecking for float_real.%s\n",
3026 PL_colors[4], PL_colors[5]));
3027 if (checkpos + 1 < strbeg) {
7f18ad16
KW
3028 /* can't match, even if we remove the trailing \n
3029 * string is too short to match */
1a13b075
YO
3030 DEBUG_EXECUTE_r(
3031 PerlIO_printf(Perl_debug_log,
3032 "%sString shorter than required trailing substring, cannot match.%s\n",
3033 PL_colors[4], PL_colors[5]));
3034 goto phooey;
3035 } else if (memEQ(checkpos + 1, little, len - 1)) {
7f18ad16
KW
3036 /* can match, the end of the string matches without the
3037 * "\n" */
1a13b075
YO
3038 last = checkpos + 1;
3039 } else if (checkpos < strbeg) {
7f18ad16
KW
3040 /* cant match, string is too short when the "\n" is
3041 * included */
1a13b075
YO
3042 DEBUG_EXECUTE_r(
3043 PerlIO_printf(Perl_debug_log,
3044 "%sString does not contain required trailing substring, cannot match.%s\n",
3045 PL_colors[4], PL_colors[5]));
3046 goto phooey;
3047 } else if (!multiline) {
7f18ad16
KW
3048 /* non multiline match, so compare with the "\n" at the
3049 * end of the string */
1a13b075
YO
3050 if (memEQ(checkpos, little, len)) {
3051 last= checkpos;
3052 } else {
3053 DEBUG_EXECUTE_r(
3054 PerlIO_printf(Perl_debug_log,
3055 "%sString does not contain required trailing substring, cannot match.%s\n",
3056 PL_colors[4], PL_colors[5]));
3057 goto phooey;
3058 }
3059 } else {
7f18ad16
KW
3060 /* multiline match, so we have to search for a place
3061 * where the full string is located */
d6a28714 3062 goto find_last;
1a13b075 3063 }
c33e64f0 3064 } else {
d6a28714 3065 find_last:
9041c2e3 3066 if (len)
d6a28714 3067 last = rninstr(s, strend, little, little + len);
b8c5462f 3068 else
a0288114 3069 last = strend; /* matching "$" */
b8c5462f 3070 }
6af40bd7 3071 if (!last) {
7f18ad16
KW
3072 /* at one point this block contained a comment which was
3073 * probably incorrect, which said that this was a "should not
3074 * happen" case. Even if it was true when it was written I am
3075 * pretty sure it is not anymore, so I have removed the comment
3076 * and replaced it with this one. Yves */
6bda09f9
YO
3077 DEBUG_EXECUTE_r(
3078 PerlIO_printf(Perl_debug_log,
b729e729
YO
3079 "%sString does not contain required substring, cannot match.%s\n",
3080 PL_colors[4], PL_colors[5]
6af40bd7
YO
3081 ));
3082 goto phooey;
bf93d4cc 3083 }
d6a28714
JH
3084 dontbother = strend - last + prog->float_min_offset;
3085 }
3086 if (minlen && (dontbother < minlen))
3087 dontbother = minlen - 1;
3088 strend -= dontbother; /* this one's always in bytes! */
3089 /* We don't know much -- general case. */
f2ed9b32 3090 if (utf8_target) {
d6a28714 3091 for (;;) {
02d5137b 3092 if (regtry(reginfo, &s))
d6a28714
JH
3093 goto got_it;
3094 if (s >= strend)
3095 break;
b8c5462f 3096 s += UTF8SKIP(s);
d6a28714
JH
3097 };
3098 }
3099 else {
3100 do {
02d5137b 3101 if (regtry(reginfo, &s))
d6a28714
JH
3102 goto got_it;
3103 } while (s++ < strend);
3104 }
3105 }
3106
3107 /* Failure. */
3108 goto phooey;
3109
3110got_it:
d5e7783a
DM
3111 /* s/// doesn't like it if $& is earlier than where we asked it to
3112 * start searching (which can happen on something like /.\G/) */
3113 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3114 && (prog->offs[0].start < stringarg - strbeg))
3115 {
3116 /* this should only be possible under \G */
58430ea8 3117 assert(prog->intflags & PREGf_GPOS_SEEN);
d5e7783a
DM
3118 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3119 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3120 goto phooey;
3121 }
3122
495f47a5
DM
3123 DEBUG_BUFFERS_r(
3124 if (swap)
3125 PerlIO_printf(Perl_debug_log,
3126 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3127 PTR2UV(prog),
3128 PTR2UV(swap)
3129 );
3130 );
e9105d30 3131 Safefree(swap);
d6a28714 3132
bf2039a9
DM
3133 /* clean up; this will trigger destructors that will free all slabs
3134 * above the current one, and cleanup the regmatch_info_aux
3135 * and regmatch_info_aux_eval sructs */
8adc0f72 3136
006f26b2
DM
3137 LEAVE_SCOPE(oldsave);
3138
5daac39c
NC
3139 if (RXp_PAREN_NAMES(prog))
3140 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
d6a28714
JH
3141
3142 /* make sure $`, $&, $', and $digit will work later */
60165aa4 3143 if ( !(flags & REXEC_NOT_FIRST) )
749f4950 3144 S_reg_set_capture_string(aTHX_ rx,
60165aa4
DM
3145 strbeg, reginfo->strend,
3146 sv, flags, utf8_target);
9041c2e3 3147
d6a28714
JH
3148 return 1;
3149
3150phooey:
a3621e74 3151 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
e4584336 3152 PL_colors[4], PL_colors[5]));
8adc0f72 3153
bf2039a9
DM
3154 /* clean up; this will trigger destructors that will free all slabs
3155 * above the current one, and cleanup the regmatch_info_aux
3156 * and regmatch_info_aux_eval sructs */
8adc0f72 3157
006f26b2
DM
3158 LEAVE_SCOPE(oldsave);
3159
e9105d30 3160 if (swap) {
c74340f9 3161 /* we failed :-( roll it back */
495f47a5
DM
3162 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3163 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3164 PTR2UV(prog),
3165 PTR2UV(prog->offs),
3166 PTR2UV(swap)
3167 ));
e9105d30
GG
3168 Safefree(prog->offs);
3169 prog->offs = swap;
3170 }
d6a28714
JH
3171 return 0;
3172}
3173
6bda09f9 3174
b3d298be 3175/* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
ec43f78b 3176 * Do inc before dec, in case old and new rex are the same */
baa60164 3177#define SET_reg_curpm(Re2) \
bf2039a9 3178 if (reginfo->info_aux_eval) { \
ec43f78b
DM
3179 (void)ReREFCNT_inc(Re2); \
3180 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3181 PM_SETRE((PL_reg_curpm), (Re2)); \
3182 }
3183
3184
d6a28714
JH
3185/*
3186 - regtry - try match at specific point
3187 */
3188STATIC I32 /* 0 failure, 1 success */
f73aaa43 3189S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
d6a28714 3190{
d6a28714 3191 CHECKPOINT lastcp;
288b8c02 3192 REGEXP *const rx = reginfo->prog;
8d919b0a 3193 regexp *const prog = ReANY(rx);
99a90e59 3194 SSize_t result;
f8fc2ecf 3195 RXi_GET_DECL(prog,progi);
a3621e74 3196 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
3197
3198 PERL_ARGS_ASSERT_REGTRY;
3199
24b23f37 3200 reginfo->cutpoint=NULL;
d6a28714 3201
9d9163fb 3202 prog->offs[0].start = *startposp - reginfo->strbeg;
d6a28714 3203 prog->lastparen = 0;
03994de8 3204 prog->lastcloseparen = 0;
d6a28714
JH
3205
3206 /* XXXX What this code is doing here?!!! There should be no need
b93070ed 3207 to do this again and again, prog->lastparen should take care of
3dd2943c 3208 this! --ilya*/
dafc8851
JH
3209
3210 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3211 * Actually, the code in regcppop() (which Ilya may be meaning by
b93070ed 3212 * prog->lastparen), is not needed at all by the test suite
225593e1
DM
3213 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3214 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3215 * Meanwhile, this code *is* needed for the
daf18116
JH
3216 * above-mentioned test suite tests to succeed. The common theme
3217 * on those tests seems to be returning null fields from matches.
225593e1 3218 * --jhi updated by dapm */
dafc8851 3219#if 1
d6a28714 3220 if (prog->nparens) {
b93070ed 3221 regexp_paren_pair *pp = prog->offs;
eb578fdb 3222 I32 i;
b93070ed 3223 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
f0ab9afb
NC
3224 ++pp;
3225 pp->start = -1;
3226 pp->end = -1;
d6a28714
JH
3227 }
3228 }
dafc8851 3229#endif
02db2b7b 3230 REGCP_SET(lastcp);
f73aaa43
DM
3231 result = regmatch(reginfo, *startposp, progi->program + 1);
3232 if (result != -1) {
3233 prog->offs[0].end = result;
d6a28714
JH
3234 return 1;
3235 }
24b23f37 3236 if (reginfo->cutpoint)
f73aaa43 3237 *startposp= reginfo->cutpoint;
02db2b7b 3238 REGCP_UNWIND(lastcp);
d6a28714
JH
3239 return 0;
3240}
3241
02db2b7b 3242
8ba1375e
MJD
3243#define sayYES goto yes
3244#define sayNO goto no
262b90c4 3245#define sayNO_SILENT goto no_silent
8ba1375e 3246
f9f4320a
YO
3247/* we dont use STMT_START/END here because it leads to
3248 "unreachable code" warnings, which are bogus, but distracting. */
3249#define CACHEsayNO \
c476f425 3250 if (ST.cache_mask) \
2ac8ff4b 3251 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
f9f4320a 3252 sayNO
3298f257 3253
a3621e74 3254/* this is used to determine how far from the left messages like
265c4333
YO
3255 'failed...' are printed. It should be set such that messages
3256 are inline with the regop output that created them.
a3621e74 3257*/
265c4333 3258#define REPORT_CODE_OFF 32
a3621e74
YO
3259
3260
40a82448
DM
3261#define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3262#define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
79a2a0e8
KW
3263#define CHRTEST_NOT_A_CP_1 -999
3264#define CHRTEST_NOT_A_CP_2 -998
9e137952 3265
5d9a96ca
DM
3266/* grab a new slab and return the first slot in it */
3267
3268STATIC regmatch_state *
3269S_push_slab(pTHX)
3270{
a35a87e7 3271#if PERL_VERSION < 9 && !defined(PERL_CORE)
54df2634
NC
3272 dMY_CXT;
3273#endif
5d9a96ca
DM
3274 regmatch_slab *s = PL_regmatch_slab->next;
3275 if (!s) {
3276 Newx(s, 1, regmatch_slab);
3277 s->prev = PL_regmatch_slab;
3278 s->next = NULL;
3279 PL_regmatch_slab->next = s;
3280 }
3281 PL_regmatch_slab = s;
86545054 3282 return SLAB_FIRST(s);
5d9a96ca 3283}
5b47454d 3284
95b24440 3285
40a82448
DM
3286/* push a new state then goto it */
3287
4d5016e5
DM
3288#define PUSH_STATE_GOTO(state, node, input) \
3289 pushinput = input; \
40a82448
DM
3290 scan = node; \
3291 st->resume_state = state; \
3292 goto push_state;
3293
3294/* push a new state with success backtracking, then goto it */
3295
4d5016e5
DM
3296#define PUSH_YES_STATE_GOTO(state, node, input) \
3297 pushinput = input; \
40a82448
DM
3298 scan = node; \
3299 st->resume_state = state; \
3300 goto push_yes_state;
3301
aa283a38 3302
aa283a38 3303
4d5016e5 3304
d6a28714 3305/*
95b24440 3306
bf1f174e
DM
3307regmatch() - main matching routine
3308
3309This is basically one big switch statement in a loop. We execute an op,
3310set 'next' to point the next op, and continue. If we come to a point which
3311we may need to backtrack to on failure such as (A|B|C), we push a
3312backtrack state onto the backtrack stack. On failure, we pop the top
3313state, and re-enter the loop at the state indicated. If there are no more
3314states to pop, we return failure.
3315
3316Sometimes we also need to backtrack on success; for example /A+/, where
3317after successfully matching one A, we need to go back and try to
3318match another one; similarly for lookahead assertions: if the assertion
3319completes successfully, we backtrack to the state just before the assertion
3320and then carry on. In these cases, the pushed state is marked as
3321'backtrack on success too'. This marking is in fact done by a chain of
3322pointers, each pointing to the previous 'yes' state. On success, we pop to
3323the nearest yes state, discarding any intermediate failure-only states.
3324Sometimes a yes state is pushed just to force some cleanup code to be
3325called at the end of a successful match or submatch; e.g. (??{$re}) uses
3326it to free the inner regex.
3327
3328Note that failure backtracking rewinds the cursor position, while
3329success backtracking leaves it alone.
3330
3331A pattern is complete when the END op is executed, while a subpattern
3332such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3333ops trigger the "pop to last yes state if any, otherwise return true"
3334behaviour.
3335
3336A common convention in this function is to use A and B to refer to the two
3337subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3338the subpattern to be matched possibly multiple times, while B is the entire
3339rest of the pattern. Variable and state names reflect this convention.
3340
3341The states in the main switch are the union of ops and failure/success of
3342substates associated with with that op. For example, IFMATCH is the op
3343that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3344'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3345successfully matched A and IFMATCH_A_fail is a state saying that we have
3346just failed to match A. Resume states always come in pairs. The backtrack
3347state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3348at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3349on success or failure.
3350
3351The struct that holds a backtracking state is actually a big union, with
3352one variant for each major type of op. The variable st points to the
3353top-most backtrack struct. To make the code clearer, within each
3354block of code we #define ST to alias the relevant union.
3355
3356Here's a concrete example of a (vastly oversimplified) IFMATCH
3357implementation:
3358
3359 switch (state) {
3360 ....
3361
3362#define ST st->u.ifmatch
3363
3364 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3365 ST.foo = ...; // some state we wish to save
95b24440 3366 ...
bf1f174e
DM
3367 // push a yes backtrack state with a resume value of
3368 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3369 // first node of A:
4d5016e5 3370 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
bf1f174e
DM
3371 // NOTREACHED
3372
3373 case IFMATCH_A: // we have successfully executed A; now continue with B
3374 next = B;
3375 bar = ST.foo; // do something with the preserved value
3376 break;
3377
3378 case IFMATCH_A_fail: // A failed, so the assertion failed
3379 ...; // do some housekeeping, then ...
3380 sayNO; // propagate the failure
3381
3382#undef ST
95b24440 3383
bf1f174e
DM
3384 ...
3385 }
95b24440 3386
bf1f174e
DM
3387For any old-timers reading this who are familiar with the old recursive
3388approach, the code above is equivalent to:
95b24440 3389
bf1f174e
DM
3390 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3391 {
3392 int foo = ...
95b24440 3393 ...
bf1f174e
DM
3394 if (regmatch(A)) {
3395 next = B;
3396 bar = foo;
3397 break;
95b24440 3398 }
bf1f174e
DM
3399 ...; // do some housekeeping, then ...
3400 sayNO; // propagate the failure
95b24440 3401 }
bf1f174e
DM
3402
3403The topmost backtrack state, pointed to by st, is usually free. If you
3404want to claim it, populate any ST.foo fields in it with values you wish to
3405save, then do one of
3406
4d5016e5
DM
3407 PUSH_STATE_GOTO(resume_state, node, newinput);
3408 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
bf1f174e
DM
3409
3410which sets that backtrack state's resume value to 'resume_state', pushes a
3411new free entry to the top of the backtrack stack, then goes to 'node'.
3412On backtracking, the free slot is popped, and the saved state becomes the
3413new free state. An ST.foo field in this new top state can be temporarily
3414accessed to retrieve values, but once the main loop is re-entered, it
3415becomes available for reuse.
3416
3417Note that the depth of the backtrack stack constantly increases during the
3418left-to-right execution of the pattern, rather than going up and down with
3419the pattern nesting. For example the stack is at its maximum at Z at the
3420end of the pattern, rather than at X in the following:
3421
3422 /(((X)+)+)+....(Y)+....Z/
3423
3424The only exceptions to this are lookahead/behind assertions and the cut,
3425(?>A), which pop all the backtrack states associated with A before
3426continuing.
3427
486ec47a 3428Backtrack state structs are allocated in slabs of about 4K in size.
bf1f174e
DM
3429PL_regmatch_state and st always point to the currently active state,
3430and PL_regmatch_slab points to the slab currently containing
3431PL_regmatch_state. The first time regmatch() is called, the first slab is
3432allocated, and is never freed until interpreter destruction. When the slab
3433is full, a new one is allocated and chained to the end. At exit from
3434regmatch(), slabs allocated since entry are freed.
3435
3436*/
95b24440 3437
40a82448 3438
5bc10b2c 3439#define DEBUG_STATE_pp(pp) \
265c4333 3440 DEBUG_STATE_r({ \
baa60164 3441 DUMP_EXEC_POS(locinput, scan, utf8_target); \
5bc10b2c 3442 PerlIO_printf(Perl_debug_log, \
5d458dd8 3443 " %*s"pp" %s%s%s%s%s\n", \
5bc10b2c 3444 depth*2, "", \
baa60164 3445 PL_reg_name[st->resume_state], \
5d458dd8
YO
3446 ((st==yes_state||st==mark_state) ? "[" : ""), \
3447 ((st==yes_state) ? "Y" : ""), \
3448 ((st==mark_state) ? "M" : ""), \
3449 ((st==yes_state||st==mark_state) ? "]" : "") \
3450 ); \
265c4333 3451 });
5bc10b2c 3452
40a82448 3453
3dab1dad 3454#define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
95b24440 3455
3df15adc 3456#ifdef DEBUGGING
5bc10b2c 3457
ab3bbdeb 3458STATIC void
f2ed9b32 3459S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
ab3bbdeb
YO
3460 const char *start, const char *end, const char *blurb)
3461{
efd26800 3462 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
7918f24d
NC
3463
3464 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3465
ab3bbdeb
YO
3466 if (!PL_colorset)
3467 reginitcolors();
3468 {
3469 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
d2c6dc5e 3470 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
ab3bbdeb 3471
f2ed9b32 3472 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
ab3bbdeb
YO
3473 start, end - start, 60);
3474
3475 PerlIO_printf(Perl_debug_log,
3476 "%s%s REx%s %s against %s\n",
3477 PL_colors[4], blurb, PL_colors[5], s0, s1);
3478
f2ed9b32 3479 if (utf8_target||utf8_pat)
1de06328
YO
3480 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3481 utf8_pat ? "pattern" : "",
f2ed9b32
KW
3482 utf8_pat && utf8_target ? " and " : "",
3483 utf8_target ? "string" : ""
ab3bbdeb
YO
3484 );
3485 }
3486}
3df15adc
YO
3487
3488STATIC void
786e8c11
YO
3489S_dump_exec_pos(pTHX_ const char *locinput,
3490 const regnode *scan,
3491 const char *loc_regeol,
3492 const char *loc_bostr,
3493 const char *loc_reg_starttry,
f2ed9b32 3494 const bool utf8_target)
07be1b83 3495{
786e8c11 3496 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
07be1b83 3497 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
786e8c11 3498 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
07be1b83
YO
3499 /* The part of the string before starttry has one color
3500 (pref0_len chars), between starttry and current
3501 position another one (pref_len - pref0_len chars),
3502 after the current position the third one.
3503 We assume that pref0_len <= pref_len, otherwise we
3504 decrease pref0_len. */
786e8c11
YO
3505 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3506 ? (5 + taill) - l : locinput - loc_bostr;
07be1b83
YO
3507 int pref0_len;
3508
7918f24d
NC
3509 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3510
f2ed9b32 3511 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
07be1b83 3512 pref_len++;
786e8c11
YO
3513 pref0_len = pref_len - (locinput - loc_reg_starttry);
3514 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3515 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3516 ? (5 + taill) - pref_len : loc_regeol - locinput);
f2ed9b32 3517 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
07be1b83
YO
3518 l--;
3519 if (pref0_len < 0)
3520 pref0_len = 0;
3521 if (pref0_len > pref_len)
3522 pref0_len = pref_len;
3523 {
f2ed9b32 3524 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
0df25f3d 3525
ab3bbdeb 3526 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
1de06328 3527 (locinput - pref_len),pref0_len, 60, 4, 5);
0df25f3d 3528
ab3bbdeb 3529 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3df15adc 3530 (locinput - pref_len + pref0_len),
1de06328 3531 pref_len - pref0_len, 60, 2, 3);
0df25f3d 3532
ab3bbdeb 3533 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
1de06328 3534 locinput, loc_regeol - locinput, 10, 0, 1);
0df25f3d 3535
1de06328 3536 const STRLEN tlen=len0+len1+len2;
3df15adc 3537 PerlIO_printf(Perl_debug_log,
ab3bbdeb 3538 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
786e8c11 3539 (IV)(locinput - loc_bostr),
07be1b83 3540 len0, s0,
07be1b83 3541 len1, s1,
07be1b83 3542 (docolor ? "" : "> <"),
07be1b83 3543 len2, s2,
f9f4320a 3544 (int)(tlen > 19 ? 0 : 19 - tlen),
07be1b83
YO
3545 "");
3546 }
3547}
3df15adc 3548
07be1b83
YO
3549#endif
3550
0a4db386
YO
3551/* reg_check_named_buff_matched()
3552 * Checks to see if a named buffer has matched. The data array of
3553 * buffer numbers corresponding to the buffer is expected to reside
3554 * in the regexp->data->data array in the slot stored in the ARG() of
3555 * node involved. Note that this routine doesn't actually care about the
3556 * name, that information is not preserved from compilation to execution.
3557 * Returns the index of the leftmost defined buffer with the given name
3558 * or 0 if non of the buffers matched.
3559 */
3560STATIC I32
dc3bf405 3561S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
7918f24d 3562{
0a4db386 3563 I32 n;
f8fc2ecf 3564 RXi_GET_DECL(rex,rexi);
ad64d0ec 3565 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
0a4db386 3566 I32 *nums=(I32*)SvPVX(sv_dat);
7918f24d
NC
3567
3568 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3569
0a4db386 3570 for ( n=0; n<SvIVX(sv_dat); n++ ) {
b93070ed
DM
3571 if ((I32)rex->lastparen >= nums[n] &&
3572 rex->offs[nums[n]].end != -1)
0a4db386
YO
3573 {
3574 return nums[n];
3575 }
3576 }
3577 return 0;
3578}
3579
2f554ef7 3580
c74f6de9 3581static bool
984e6dd1 3582S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
aed7b151 3583 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
c74f6de9 3584{
79a2a0e8
KW
3585 /* This function determines if there are one or two characters that match
3586 * the first character of the passed-in EXACTish node <text_node>, and if
3587 * so, returns them in the passed-in pointers.
c74f6de9 3588 *
79a2a0e8
KW
3589 * If it determines that no possible character in the target string can
3590 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3591 * the first character in <text_node> requires UTF-8 to represent, and the
3592 * target string isn't in UTF-8.)
c74f6de9 3593 *
79a2a0e8
KW
3594 * If there are more than two characters that could match the beginning of
3595 * <text_node>, or if more context is required to determine a match or not,
3596 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3597 *
3598 * The motiviation behind this function is to allow the caller to set up
3599 * tight loops for matching. If <text_node> is of type EXACT, there is
3600 * only one possible character that can match its first character, and so
3601 * the situation is quite simple. But things get much more complicated if
3602 * folding is involved. It may be that the first character of an EXACTFish
3603 * node doesn't participate in any possible fold, e.g., punctuation, so it
3604 * can be matched only by itself. The vast majority of characters that are
3605 * in folds match just two things, their lower and upper-case equivalents.
3606 * But not all are like that; some have multiple possible matches, or match
3607 * sequences of more than one character. This function sorts all that out.
3608 *
3609 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3610 * loop of trying to match A*, we know we can't exit where the thing
3611 * following it isn't a B. And something can't be a B unless it is the
3612 * beginning of B. By putting a quick test for that beginning in a tight
3613 * loop, we can rule out things that can't possibly be B without having to
3614 * break out of the loop, thus avoiding work. Similarly, if A is a single
3615 * character, we can make a tight loop matching A*, using the outputs of
3616 * this function.
3617 *
3618 * If the target string to match isn't in UTF-8, and there aren't
3619 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3620 * the one or two possible octets (which are characters in this situation)
3621 * that can match. In all cases, if there is only one character that can
3622 * match, *<c1p> and *<c2p> will be identical.
3623 *
3624 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
3625 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
3626 * can match the beginning of <text_node>. They should be declared with at
3627 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
3628 * undefined what these contain.) If one or both of the buffers are
3629 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
3630 * corresponding invariant. If variant, the corresponding *<c1p> and/or
3631 * *<c2p> will be set to a negative number(s) that shouldn't match any code
3632 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
3633 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
c74f6de9 3634
ba44c216 3635 const bool utf8_target = reginfo->is_utf8_target;
79a2a0e8 3636
9cd990bf
JH
3637 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
3638 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
79a2a0e8 3639 bool use_chrtest_void = FALSE;
aed7b151 3640 const bool is_utf8_pat = reginfo->is_utf8_pat;
79a2a0e8
KW
3641
3642 /* Used when we have both utf8 input and utf8 output, to avoid converting
3643 * to/from code points */
3644 bool utf8_has_been_setup = FALSE;
3645
c74f6de9
KW
3646 dVAR;
3647
b4291290 3648 U8 *pat = (U8*)STRING(text_node);
a6715020 3649 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
c74f6de9 3650
79a2a0e8
KW
3651 if (OP(text_node) == EXACT) {
3652
3653 /* In an exact node, only one thing can be matched, that first
3654 * character. If both the pat and the target are UTF-8, we can just
3655 * copy the input to the output, avoiding finding the code point of
3656 * that character */
984e6dd1 3657 if (!is_utf8_pat) {
79a2a0e8
KW
3658 c2 = c1 = *pat;
3659 }
3660 else if (utf8_target) {
3661 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
3662 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
3663 utf8_has_been_setup = TRUE;
3664 }
3665 else {
3666 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
c74f6de9 3667 }
79a2a0e8 3668 }
31f05a37
KW
3669 else { /* an EXACTFish node */
3670 U8 *pat_end = pat + STR_LEN(text_node);
3671
3672 /* An EXACTFL node has at least some characters unfolded, because what
3673 * they match is not known until now. So, now is the time to fold
3674 * the first few of them, as many as are needed to determine 'c1' and
3675 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
3676 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
3677 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
3678 * need to fold as many characters as a single character can fold to,
3679 * so that later we can check if the first ones are such a multi-char
3680 * fold. But, in such a pattern only locale-problematic characters
3681 * aren't folded, so we can skip this completely if the first character
3682 * in the node isn't one of the tricky ones */
3683 if (OP(text_node) == EXACTFL) {
3684
3685 if (! is_utf8_pat) {
3686 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
3687 {
3688 folded[0] = folded[1] = 's';
3689 pat = folded;
3690 pat_end = folded + 2;
3691 }
3692 }
3693 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
3694 U8 *s = pat;
3695 U8 *d = folded;
3696 int i;
3697
3698 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
3699 if (isASCII(*s)) {
3700 *(d++) = (U8) toFOLD_LC(*s);
3701 s++;
3702 }
3703 else {
3704 STRLEN len;
3705 _to_utf8_fold_flags(s,
3706 d,
3707 &len,
3708 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
3709 d += len;
3710 s += UTF8SKIP(s);
3711 }
3712 }
3713
3714 pat = folded;
3715 pat_end = d;
3716 }
3717 }
3718
251b239f
KW
3719 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
3720 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
baa60164
KW
3721 {
3722 /* Multi-character folds require more context to sort out. Also
3723 * PL_utf8_foldclosures used below doesn't handle them, so have to
3724 * be handled outside this routine */
3725 use_chrtest_void = TRUE;
3726 }
3727 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
3728 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
e8ea8356 3729 if (c1 > 255) {
baa60164
KW
3730 /* Load the folds hash, if not already done */
3731 SV** listp;
3732 if (! PL_utf8_foldclosures) {
31667e6b 3733 _load_PL_utf8_foldclosures();
79a2a0e8 3734 }
79a2a0e8 3735
baa60164
KW
3736 /* The fold closures data structure is a hash with the keys
3737 * being the UTF-8 of every character that is folded to, like
3738 * 'k', and the values each an array of all code points that
3739 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
3740 * Multi-character folds are not included */
3741 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
3742 (char *) pat,
3743 UTF8SKIP(pat),
3744 FALSE))))
3745 {
3746 /* Not found in the hash, therefore there are no folds
3747 * containing it, so there is only a single character that
3748 * could match */
3749 c2 = c1;
79a2a0e8 3750 }
baa60164
KW
3751 else { /* Does participate in folds */
3752 AV* list = (AV*) *listp;
b9f2b683 3753 if (av_tindex(list) != 1) {
79a2a0e8 3754
baa60164
KW
3755 /* If there aren't exactly two folds to this, it is
3756 * outside the scope of this function */
3757 use_chrtest_void = TRUE;
79a2a0e8 3758 }
baa60164
KW
3759 else { /* There are two. Get them */
3760 SV** c_p = av_fetch(list, 0, FALSE);
3761 if (c_p == NULL) {
3762 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3763 }
3764 c1 = SvUV(*c_p);
3765
3766 c_p = av_fetch(list, 1, FALSE);
3767 if (c_p == NULL) {
3768 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
3769 }
3770 c2 = SvUV(*c_p);
3771
3772 /* Folds that cross the 255/256 boundary are forbidden
3773 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
3774 * one is ASCIII. Since the pattern character is above
e8ea8356 3775 * 255, and its only other match is below 256, the only
baa60164
KW
3776 * legal match will be to itself. We have thrown away
3777 * the original, so have to compute which is the one
e8ea8356 3778 * above 255. */
baa60164
KW
3779 if ((c1 < 256) != (c2 < 256)) {
3780 if ((OP(text_node) == EXACTFL
3781 && ! IN_UTF8_CTYPE_LOCALE)
3782 || ((OP(text_node) == EXACTFA
3783 || OP(text_node) == EXACTFA_NO_TRIE)
3784 && (isASCII(c1) || isASCII(c2))))
3785 {
3786 if (c1 < 256) {
3787 c1 = c2;
3788 }
3789 else {
3790 c2 = c1;
3791 }
79a2a0e8
KW
3792 }
3793 }
3794 }
3795 }
3796 }
e8ea8356 3797 else /* Here, c1 is <= 255 */
baa60164
KW
3798 if (utf8_target
3799 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
3800 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
3801 && ((OP(text_node) != EXACTFA
3802 && OP(text_node) != EXACTFA_NO_TRIE)
3803 || ! isASCII(c1)))
3804 {
3805 /* Here, there could be something above Latin1 in the target
3806 * which folds to this character in the pattern. All such
3807 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
3808 * than two characters involved in their folds, so are outside
3809 * the scope of this function */
3810 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
3811 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
3812 }
3813 else {
3814 use_chrtest_void = TRUE;
3815 }
79a2a0e8 3816 }
baa60164
KW
3817 else { /* Here nothing above Latin1 can fold to the pattern
3818 character */
3819 switch (OP(text_node)) {
c74f6de9 3820
baa60164
KW
3821 case EXACTFL: /* /l rules */
3822 c2 = PL_fold_locale[c1];
3823 break;
c74f6de9 3824
baa60164
KW
3825 case EXACTF: /* This node only generated for non-utf8
3826 patterns */
3827 assert(! is_utf8_pat);
3828 if (! utf8_target) { /* /d rules */
3829 c2 = PL_fold[c1];
3830 break;
3831 }
3832 /* FALLTHROUGH */
3833 /* /u rules for all these. This happens to work for
3834 * EXACTFA as nothing in Latin1 folds to ASCII */
3835 case EXACTFA_NO_TRIE: /* This node only generated for
3836 non-utf8 patterns */
3837 assert(! is_utf8_pat);
924ba076 3838 /* FALLTHROUGH */
baa60164
KW
3839 case EXACTFA:
3840 case EXACTFU_SS:
3841 case EXACTFU:
3842 c2 = PL_fold_latin1[c1];
c74f6de9 3843 break;
c74f6de9 3844
baa60164
KW
3845 default:
3846 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
e5964223 3847 NOT_REACHED; /* NOTREACHED */
baa60164 3848 }
c74f6de9
KW
3849 }
3850 }
3851 }
79a2a0e8
KW
3852
3853 /* Here have figured things out. Set up the returns */
3854 if (use_chrtest_void) {
3855 *c2p = *c1p = CHRTEST_VOID;
3856 }
3857 else if (utf8_target) {
3858 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
3859 uvchr_to_utf8(c1_utf8, c1);
3860 uvchr_to_utf8(c2_utf8, c2);
c74f6de9 3861 }
c74f6de9 3862
79a2a0e8
KW
3863 /* Invariants are stored in both the utf8 and byte outputs; Use
3864 * negative numbers otherwise for the byte ones. Make sure that the
3865 * byte ones are the same iff the utf8 ones are the same */
3866 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
3867 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
3868 ? *c2_utf8
3869 : (c1 == c2)
3870 ? CHRTEST_NOT_A_CP_1
3871 : CHRTEST_NOT_A_CP_2;
3872 }
3873 else if (c1 > 255) {
3874 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
3875 can represent */
3876 return FALSE;
3877 }
c74f6de9 3878
79a2a0e8
KW
3879 *c1p = *c2p = c2; /* c2 is the only representable value */
3880 }
3881 else { /* c1 is representable; see about c2 */
3882 *c1p = c1;
3883 *c2p = (c2 < 256) ? c2 : c1;
c74f6de9 3884 }
2f554ef7 3885
c74f6de9
KW
3886 return TRUE;
3887}
2f554ef7 3888
f73aaa43 3889/* returns -1 on failure, $+[0] on success */
99a90e59 3890STATIC SSize_t
f73aaa43 3891S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
d6a28714 3892{
a35a87e7 3893#if PERL_VERSION < 9 && !defined(PERL_CORE)
54df2634
NC
3894 dMY_CXT;
3895#endif
27da23d5 3896 dVAR;
ba44c216 3897 const bool utf8_target = reginfo->is_utf8_target;
4ad0818d 3898 const U32 uniflags = UTF8_ALLOW_DEFAULT;
288b8c02 3899 REGEXP *rex_sv = reginfo->prog;
8d919b0a 3900 regexp *rex = ReANY(rex_sv);
f8fc2ecf 3901 RXi_GET_DECL(rex,rexi);
5d9a96ca 3902 /* the current state. This is a cached copy of PL_regmatch_state */
eb578fdb 3903 regmatch_state *st;
5d9a96ca 3904 /* cache heavy used fields of st in registers */
eb578fdb
KW
3905 regnode *scan;
3906 regnode *next;
3907 U32 n = 0; /* general value; init to avoid compiler warning */
ea3daa5d 3908 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
d60de1d1 3909 char *locinput = startpos;
4d5016e5 3910 char *pushinput; /* where to continue after a PUSH */
eb578fdb 3911 I32 nextchr; /* is always set to UCHARAT(locinput) */
24d3c4a9 3912
b69b0499 3913 bool result = 0; /* return value of S_regmatch */
24d3c4a9 3914 int depth = 0; /* depth of backtrack stack */
4b196cd4
YO
3915 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3916 const U32 max_nochange_depth =
3917 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3918 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
77cb431f
DM
3919 regmatch_state *yes_state = NULL; /* state to pop to on success of
3920 subpattern */
e2e6a0f1
YO
3921 /* mark_state piggy backs on the yes_state logic so that when we unwind
3922 the stack on success we can update the mark_state as we go */
3923 regmatch_state *mark_state = NULL; /* last mark state we have seen */
faec1544 3924 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
b8591aee 3925 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
40a82448 3926 U32 state_num;
5d458dd8
YO
3927 bool no_final = 0; /* prevent failure from backtracking? */
3928 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
d60de1d1 3929 char *startpoint = locinput;
5d458dd8
YO
3930 SV *popmark = NULL; /* are we looking for a mark? */
3931 SV *sv_commit = NULL; /* last mark name seen in failure */
3932 SV *sv_yes_mark = NULL; /* last mark name we have seen
486ec47a 3933 during a successful match */
5d458dd8
YO
3934 U32 lastopen = 0; /* last open we saw */
3935 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
4a2b275c 3936 SV* const oreplsv = GvSVn(PL_replgv);
24d3c4a9
DM
3937 /* these three flags are set by various ops to signal information to
3938 * the very next op. They have a useful lifetime of exactly one loop
3939 * iteration, and are not preserved or restored by state pushes/pops
3940 */
3941 bool sw = 0; /* the condition value in (?(cond)a|b) */
3942 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3943 int logical = 0; /* the following EVAL is:
3944 0: (?{...})
3945 1: (?(?{...})X|Y)
3946 2: (??{...})
3947 or the following IFMATCH/UNLESSM is:
3948 false: plain (?=foo)
3949 true: used as a condition: (?(?=foo))
3950 */
81ed78b2
DM
3951 PAD* last_pad = NULL;
3952 dMULTICALL;
3953 I32 gimme = G_SCALAR;
3954 CV *caller_cv = NULL; /* who called us */
3955 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
74088413 3956 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
92da3157 3957 U32 maxopenparen = 0; /* max '(' index seen so far */
3018b823
KW
3958 int to_complement; /* Invert the result? */
3959 _char_class_number classnum;
984e6dd1 3960 bool is_utf8_pat = reginfo->is_utf8_pat;
81ed78b2 3961
95b24440 3962#ifdef DEBUGGING
e68ec53f 3963 GET_RE_DEBUG_FLAGS_DECL;
d6a28714
JH
3964#endif
3965
7e68f152
FC
3966 /* protect against undef(*^R) */
3967 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
3968
81ed78b2
DM
3969 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3970 multicall_oldcatch = 0;
3971 multicall_cv = NULL;
3972 cx = NULL;
4f8dbb2d
JL
3973 PERL_UNUSED_VAR(multicall_cop);
3974 PERL_UNUSED_VAR(newsp);
81ed78b2
DM
3975
3976
7918f24d
NC
3977 PERL_ARGS_ASSERT_REGMATCH;
3978
3b57cd43 3979 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
24b23f37 3980 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3b57cd43 3981 }));
5d9a96ca 3982
331b2dcc 3983 st = PL_regmatch_state;
5d9a96ca 3984
d6a28714 3985 /* Note that nextchr is a byte even in UTF */
7016d6eb 3986 SET_nextchr;
d6a28714
JH
3987 scan = prog;
3988 while (scan != NULL) {
8ba1375e 3989
a3621e74 3990 DEBUG_EXECUTE_r( {
6136c704 3991 SV * const prop = sv_newmortal();
1de06328 3992 regnode *rnext=regnext(scan);
f2ed9b32 3993 DUMP_EXEC_POS( locinput, scan, utf8_target );
8b9781c9 3994 regprop(rex, prop, scan, reginfo, NULL);
07be1b83
YO
3995
3996 PerlIO_printf(Perl_debug_log,
3997 "%3"IVdf":%*s%s(%"IVdf")\n",
f8fc2ecf 3998 (IV)(scan - rexi->program), depth*2, "",
07be1b83 3999 SvPVX_const(prop),
1de06328 4000 (PL_regkind[OP(scan)] == END || !rnext) ?
f8fc2ecf 4001 0 : (IV)(rnext - rexi->program));
2a782b5b 4002 });
d6a28714
JH
4003
4004 next = scan + NEXT_OFF(scan);
4005 if (next == scan)
4006 next = NULL;
40a82448 4007 state_num = OP(scan);
d6a28714 4008
40a82448 4009 reenter_switch:
3018b823 4010 to_complement = 0;
34a81e2b 4011
7016d6eb 4012 SET_nextchr;
e6ca698c 4013 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
bf798dc4 4014
40a82448 4015 switch (state_num) {
d3d47aac 4016 case SBOL: /* /^../ and /\A../ */
9d9163fb 4017 if (locinput == reginfo->strbeg)
b8c5462f 4018 break;
d6a28714 4019 sayNO;
3c0563b9
DM
4020
4021 case MBOL: /* /^../m */
9d9163fb 4022 if (locinput == reginfo->strbeg ||
7016d6eb 4023 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
d6a28714 4024 {
b8c5462f
JH
4025 break;
4026 }
d6a28714 4027 sayNO;
3c0563b9 4028
3c0563b9 4029 case GPOS: /* \G */
3b0527fe 4030 if (locinput == reginfo->ganch)
d6a28714
JH
4031 break;
4032 sayNO;
ee9b8eae 4033
3c0563b9 4034 case KEEPS: /* \K */
ee9b8eae 4035 /* update the startpoint */
b93070ed 4036 st->u.keeper.val = rex->offs[0].start;
9d9163fb 4037 rex->offs[0].start = locinput - reginfo->strbeg;
4d5016e5 4038 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
a74ff37d 4039 /* NOTREACHED */
e5964223 4040 NOT_REACHED;
a74ff37d 4041
ee9b8eae
YO
4042 case KEEPS_next_fail:
4043 /* rollback the start point change */
b93070ed 4044 rex->offs[0].start = st->u.keeper.val;
ee9b8eae 4045 sayNO_SILENT;
a74ff37d 4046 /* NOTREACHED */
e5964223 4047 NOT_REACHED;
3c0563b9 4048
3c0563b9 4049 case MEOL: /* /..$/m */
7016d6eb 4050 if (!NEXTCHR_IS_EOS && nextchr != '\n')
b8c5462f 4051 sayNO;
b8c5462f 4052 break;
3c0563b9 4053
d3d47aac 4054 case SEOL: /* /..$/ */
7016d6eb 4055 if (!NEXTCHR_IS_EOS && nextchr != '\n')
b8c5462f 4056 sayNO;
220db18a 4057 if (reginfo->strend - locinput > 1)
b8c5462f 4058 sayNO;
b8c5462f 4059 break;
3c0563b9
DM
4060
4061 case EOS: /* \z */
7016d6eb 4062 if (!NEXTCHR_IS_EOS)
b8c5462f 4063 sayNO;
d6a28714 4064 break;
3c0563b9
DM
4065
4066 case SANY: /* /./s */
7016d6eb 4067 if (NEXTCHR_IS_EOS)
4633a7c4 4068 sayNO;
28b98f76 4069 goto increment_locinput;
3c0563b9
DM
4070
4071 case CANY: /* \C */
7016d6eb 4072 if (NEXTCHR_IS_EOS)
f33976b4 4073 sayNO;
3640db6b 4074 locinput++;
a0d0e21e 4075 break;
3c0563b9
DM
4076
4077 case REG_ANY: /* /./ */
7016d6eb 4078 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
1aa99e6b 4079 sayNO;
28b98f76
DM
4080 goto increment_locinput;
4081
166ba7cd
DM
4082
4083#undef ST
4084#define ST st->u.trie
3c0563b9 4085 case TRIEC: /* (ab|cd) with known charclass */
786e8c11
YO
4086 /* In this case the charclass data is available inline so
4087 we can fail fast without a lot of extra overhead.
4088 */
7016d6eb 4089 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
fab2782b
YO
4090 DEBUG_EXECUTE_r(
4091 PerlIO_printf(Perl_debug_log,
4092 "%*s %sfailed to match trie start class...%s\n",
4093 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
4094 );
4095 sayNO_SILENT;
a74ff37d 4096 /* NOTREACHED */
e5964223 4097 NOT_REACHED;
786e8c11 4098 }
924ba076 4099 /* FALLTHROUGH */
3c0563b9 4100 case TRIE: /* (ab|cd) */
2e64971a
DM
4101 /* the basic plan of execution of the trie is:
4102 * At the beginning, run though all the states, and
4103 * find the longest-matching word. Also remember the position
4104 * of the shortest matching word. For example, this pattern:
4105 * 1 2 3 4 5
4106 * ab|a|x|abcd|abc
4107 * when matched against the string "abcde", will generate
4108 * accept states for all words except 3, with the longest
895cc420 4109 * matching word being 4, and the shortest being 2 (with
2e64971a
DM
4110 * the position being after char 1 of the string).
4111 *
4112 * Then for each matching word, in word order (i.e. 1,2,4,5),
4113 * we run the remainder of the pattern; on each try setting
4114 * the current position to the character following the word,
4115 * returning to try the next word on failure.
4116 *
4117 * We avoid having to build a list of words at runtime by
4118 * using a compile-time structure, wordinfo[].prev, which
4119 * gives, for each word, the previous accepting word (if any).
4120 * In the case above it would contain the mappings 1->2, 2->0,
4121 * 3->0, 4->5, 5->1. We can use this table to generate, from
4122 * the longest word (4 above), a list of all words, by
4123 * following the list of prev pointers; this gives us the
4124 * unordered list 4,5,1,2. Then given the current word we have
4125 * just tried, we can go through the list and find the
4126 * next-biggest word to try (so if we just failed on word 2,
4127 * the next in the list is 4).
4128 *
4129 * Since at runtime we don't record the matching position in
4130 * the string for each word, we have to work that out for
4131 * each word we're about to process. The wordinfo table holds
4132 * the character length of each word; given that we recorded
4133 * at the start: the position of the shortest word and its
4134 * length in chars, we just need to move the pointer the
4135 * difference between the two char lengths. Depending on
4136 * Unicode status and folding, that's cheap or expensive.
4137 *
4138 * This algorithm is optimised for the case where are only a
4139 * small number of accept states, i.e. 0,1, or maybe 2.
4140 * With lots of accepts states, and having to try all of them,
4141 * it becomes quadratic on number of accept states to find all
4142 * the next words.
4143 */
4144
3dab1dad 4145 {
07be1b83 4146 /* what type of TRIE am I? (utf8 makes this contextual) */
a0a388a1 4147 DECL_TRIE_TYPE(scan);
3dab1dad
YO
4148
4149 /* what trie are we using right now */
be8e71aa 4150 reg_trie_data * const trie
f8fc2ecf 4151 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
85fbaab2 4152 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3dab1dad 4153 U32 state = trie->startstate;
166ba7cd 4154
7016d6eb
DM
4155 if ( trie->bitmap
4156 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
4157 {
3dab1dad
YO
4158 if (trie->states[ state ].wordnum) {
4159 DEBUG_EXECUTE_r(
4160 PerlIO_printf(Perl_debug_log,
4161 "%*s %smatched empty string...%s\n",
5bc10b2c 4162 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3dab1dad 4163 );
20dbff7c
YO
4164 if (!trie->jump)
4165 break;
3dab1dad
YO
4166 } else {
4167 DEBUG_EXECUTE_r(
4168 PerlIO_printf(Perl_debug_log,
786e8c11 4169 "%*s %sfailed to match trie start class...%s\n",
5bc10b2c 4170 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3dab1dad
YO
4171 );
4172 sayNO_SILENT;
4173 }
4174 }
166ba7cd 4175
786e8c11
YO
4176 {
4177 U8 *uc = ( U8* )locinput;
4178
4179 STRLEN len = 0;
4180 STRLEN foldlen = 0;
4181 U8 *uscan = (U8*)NULL;
786e8c11 4182 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2e64971a
DM
4183 U32 charcount = 0; /* how many input chars we have matched */
4184 U32 accepted = 0; /* have we seen any accepting states? */
786e8c11 4185
786e8c11 4186 ST.jump = trie->jump;
786e8c11 4187 ST.me = scan;
2e64971a
DM
4188 ST.firstpos = NULL;
4189 ST.longfold = FALSE; /* char longer if folded => it's harder */
4190 ST.nextword = 0;
4191
4192 /* fully traverse the TRIE; note the position of the
4193 shortest accept state and the wordnum of the longest
4194 accept state */
07be1b83 4195
220db18a 4196 while ( state && uc <= (U8*)(reginfo->strend) ) {
786e8c11 4197 U32 base = trie->states[ state ].trans.base;
f9f4320a 4198 UV uvc = 0;
acb909b4 4199 U16 charid = 0;
2e64971a
DM
4200 U16 wordnum;
4201 wordnum = trie->states[ state ].wordnum;
4202
4203 if (wordnum) { /* it's an accept state */
4204 if (!accepted) {
4205 accepted = 1;
4206 /* record first match position */
4207 if (ST.longfold) {
4208 ST.firstpos = (U8*)locinput;
4209 ST.firstchars = 0;
5b47454d 4210 }
2e64971a
DM
4211 else {
4212 ST.firstpos = uc;
4213 ST.firstchars = charcount;
4214 }
4215 }
4216 if (!ST.nextword || wordnum < ST.nextword)
4217 ST.nextword = wordnum;
4218 ST.topword = wordnum;
786e8c11 4219 }
a3621e74 4220
07be1b83 4221 DEBUG_TRIE_EXECUTE_r({
f2ed9b32 4222 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
a3621e74 4223 PerlIO_printf( Perl_debug_log,
2e64971a 4224 "%*s %sState: %4"UVxf" Accepted: %c ",
5bc10b2c 4225 2+depth * 2, "", PL_colors[4],
2e64971a 4226 (UV)state, (accepted ? 'Y' : 'N'));
07be1b83 4227 });
a3621e74 4228
2e64971a 4229 /* read a char and goto next state */
220db18a 4230 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
6dd2be57 4231 I32 offset;
55eed653
NC
4232 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
4233 uscan, len, uvc, charid, foldlen,
4234 foldbuf, uniflags);
2e64971a
DM
4235 charcount++;
4236 if (foldlen>0)
4237 ST.longfold = TRUE;
5b47454d 4238 if (charid &&
6dd2be57
DM
4239 ( ((offset =
4240 base + charid - 1 - trie->uniquecharcount)) >= 0)
4241
4242 && ((U32)offset < trie->lasttrans)
4243 && trie->trans[offset].check == state)
5b47454d 4244 {
6dd2be57 4245 state = trie->trans[offset].next;
5b47454d
DM
4246 }
4247 else {
4248 state = 0;
4249 }
4250 uc += len;
4251
4252 }
4253 else {
a3621e74
YO
4254 state = 0;
4255 }
4256 DEBUG_TRIE_EXECUTE_r(
e4584336 4257 PerlIO_printf( Perl_debug_log,
786e8c11 4258 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
e4584336 4259 charid, uvc, (UV)state, PL_colors[5] );
a3621e74
YO
4260 );
4261 }
2e64971a 4262 if (!accepted)
a3621e74 4263 sayNO;
a3621e74 4264
2e64971a
DM
4265 /* calculate total number of accept states */
4266 {
4267 U16 w = ST.topword;
4268 accepted = 0;
4269 while (w) {
4270 w = trie->wordinfo[w].prev;
4271 accepted++;
4272 }
4273 ST.accepted = accepted;
4274 }
4275
166ba7cd
DM
4276 DEBUG_EXECUTE_r(
4277 PerlIO_printf( Perl_debug_log,
4278 "%*s %sgot %"IVdf" possible matches%s\n",
5bc10b2c 4279 REPORT_CODE_OFF + depth * 2, "",
166ba7cd
DM
4280 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
4281 );
2e64971a 4282 goto trie_first_try; /* jump into the fail handler */
786e8c11 4283 }}
a74ff37d 4284 /* NOTREACHED */
e5964223 4285 NOT_REACHED;
2e64971a
DM
4286
4287 case TRIE_next_fail: /* we failed - try next alternative */
a059a757
DM
4288 {
4289 U8 *uc;
fae667d5
YO
4290 if ( ST.jump) {
4291 REGCP_UNWIND(ST.cp);
a8d1f4b4 4292 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
fae667d5 4293 }
2e64971a
DM
4294 if (!--ST.accepted) {
4295 DEBUG_EXECUTE_r({
4296 PerlIO_printf( Perl_debug_log,
4297 "%*s %sTRIE failed...%s\n",
4298 REPORT_CODE_OFF+depth*2, "",
4299 PL_colors[4],
4300 PL_colors[5] );
4301 });
4302 sayNO_SILENT;
4303 }
4304 {
4305 /* Find next-highest word to process. Note that this code
4306 * is O(N^2) per trie run (O(N) per branch), so keep tight */
eb578fdb
KW
4307 U16 min = 0;
4308 U16 word;
4309 U16 const nextword = ST.nextword;
4310 reg_trie_wordinfo * const wordinfo
2e64971a
DM
4311 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
4312 for (word=ST.topword; word; word=wordinfo[word].prev) {
4313 if (word > nextword && (!min || word < min))
4314 min = word;
4315 }
4316 ST.nextword = min;
4317 }
4318
fae667d5 4319 trie_first_try:
5d458dd8
YO
4320 if (do_cutgroup) {
4321 do_cutgroup = 0;
4322 no_final = 0;
4323 }
fae667d5
YO
4324
4325 if ( ST.jump) {
b93070ed 4326 ST.lastparen = rex->lastparen;
f6033a9d 4327 ST.lastcloseparen = rex->lastcloseparen;
fae667d5 4328 REGCP_SET(ST.cp);
2e64971a 4329 }
a3621e74 4330
2e64971a 4331 /* find start char of end of current word */
166ba7cd 4332 {
2e64971a 4333 U32 chars; /* how many chars to skip */
2e64971a
DM
4334 reg_trie_data * const trie
4335 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
4336
4337 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
4338 >= ST.firstchars);
4339 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
4340 - ST.firstchars;
a059a757 4341 uc = ST.firstpos;
2e64971a
DM
4342
4343 if (ST.longfold) {
4344 /* the hard option - fold each char in turn and find
4345 * its folded length (which may be different */
4346 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
4347 STRLEN foldlen;
4348 STRLEN len;
d9a396a3 4349 UV uvc;
2e64971a
DM
4350 U8 *uscan;
4351
4352 while (chars) {
f2ed9b32 4353 if (utf8_target) {
c80e42f3 4354 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
2e64971a
DM
4355 uniflags);
4356 uc += len;
4357 }
4358 else {
4359 uvc = *uc;
4360 uc++;
4361 }
4362 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
4363 uscan = foldbuf;
4364 while (foldlen) {
4365 if (!--chars)
4366 break;
c80e42f3 4367 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
2e64971a
DM
4368 uniflags);
4369 uscan += len;
4370 foldlen -= len;
4371 }
4372 }
a3621e74 4373 }
2e64971a 4374 else {
f2ed9b32 4375 if (utf8_target)
2e64971a
DM
4376 while (chars--)
4377 uc += UTF8SKIP(uc);
4378 else
4379 uc += chars;
4380 }
2e64971a 4381 }
166ba7cd 4382
6603fe3e
DM
4383 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
4384 ? ST.jump[ST.nextword]
4385 : NEXT_OFF(ST.me));
166ba7cd 4386
2e64971a
DM
4387 DEBUG_EXECUTE_r({
4388 PerlIO_printf( Perl_debug_log,
4389 "%*s %sTRIE matched word #%d, continuing%s\n",
4390 REPORT_CODE_OFF+depth*2, "",
4391 PL_colors[4],
4392 ST.nextword,
4393 PL_colors[5]
4394 );
4395 });
4396
4397 if (ST.accepted > 1 || has_cutgroup) {
a059a757 4398 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
a74ff37d 4399 /* NOTREACHED */
e5964223 4400 NOT_REACHED;
166ba7cd 4401 }
2e64971a
DM
4402 /* only one choice left - just continue */
4403 DEBUG_EXECUTE_r({
4404 AV *const trie_words
4405 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
4406 SV ** const tmp = av_fetch( trie_words,
4407 ST.nextword-1, 0 );
4408 SV *sv= tmp ? sv_newmortal() : NULL;
4409
4410 PerlIO_printf( Perl_debug_log,
4411 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
4412 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
4413 ST.nextword,
4414 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
4415 PL_colors[0], PL_colors[1],
c89df6cf 4416 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
2e64971a
DM
4417 )
4418 : "not compiled under -Dr",
4419 PL_colors[5] );
4420 });
4421
a059a757 4422 locinput = (char*)uc;
2e64971a 4423 continue; /* execute rest of RE */
a74ff37d 4424 /* NOTREACHED */
a059a757 4425 }
166ba7cd
DM
4426#undef ST
4427
3c0563b9 4428 case EXACT: { /* /abc/ */
95b24440 4429 char *s = STRING(scan);
24d3c4a9 4430 ln = STR_LEN(scan);
984e6dd1 4431 if (utf8_target != is_utf8_pat) {
bc517b45 4432 /* The target and the pattern have differing utf8ness. */
1aa99e6b 4433 char *l = locinput;
24d3c4a9 4434 const char * const e = s + ln;
a72c7584 4435
f2ed9b32 4436 if (utf8_target) {
e6a3850e
KW
4437 /* The target is utf8, the pattern is not utf8.
4438 * Above-Latin1 code points can't match the pattern;
4439 * invariants match exactly, and the other Latin1 ones need
4440 * to be downgraded to a single byte in order to do the
4441 * comparison. (If we could be confident that the target
4442 * is not malformed, this could be refactored to have fewer
4443 * tests by just assuming that if the first bytes match, it
4444 * is an invariant, but there are tests in the test suite
4445 * dealing with (??{...}) which violate this) */
1aa99e6b 4446 while (s < e) {
220db18a
DM
4447 if (l >= reginfo->strend
4448 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
4449 {
e6a3850e
KW
4450 sayNO;
4451 }
4452 if (UTF8_IS_INVARIANT(*(U8*)l)) {
4453 if (*l != *s) {
4454 sayNO;
4455 }
4456 l++;
4457 }
4458 else {
94bb8c36
KW
4459 if (TWO_BYTE_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
4460 {
e6a3850e
KW
4461 sayNO;
4462 }
4463 l += 2;
4464 }
4465 s++;
1aa99e6b 4466 }
5ff6fc6d
JH
4467 }
4468 else {
4469 /* The target is not utf8, the pattern is utf8. */
1aa99e6b 4470 while (s < e) {
220db18a
DM
4471 if (l >= reginfo->strend
4472 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
e6a3850e
KW
4473 {
4474 sayNO;
4475 }
4476 if (UTF8_IS_INVARIANT(*(U8*)s)) {
4477 if (*s != *l) {
4478 sayNO;
4479 }
4480 s++;
4481 }
4482 else {
94bb8c36
KW
4483 if (TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
4484 {
e6a3850e
KW
4485 sayNO;
4486 }
4487 s += 2;
4488 }
4489 l++;
1aa99e6b 4490 }
5ff6fc6d 4491 }
1aa99e6b 4492 locinput = l;
1aa99e6b 4493 }
5ac65bff
KW
4494 else {
4495 /* The target and the pattern have the same utf8ness. */
4496 /* Inline the first character, for speed. */
220db18a 4497 if (reginfo->strend - locinput < ln
5ac65bff
KW
4498 || UCHARAT(s) != nextchr
4499 || (ln > 1 && memNE(s, locinput, ln)))
4500 {
4501 sayNO;
4502 }
4503 locinput += ln;
4504 }
d6a28714 4505 break;
95b24440 4506 }
7016d6eb 4507
3c0563b9 4508 case EXACTFL: { /* /abc/il */
a932d541 4509 re_fold_t folder;
9a5a5549
KW
4510 const U8 * fold_array;
4511 const char * s;
d513472c 4512 U32 fold_utf8_flags;
9a5a5549 4513
f67f9e53
KW
4514 folder = foldEQ_locale;
4515 fold_array = PL_fold_locale;
cea315b6 4516 fold_utf8_flags = FOLDEQ_LOCALE;
9a5a5549
KW
4517 goto do_exactf;
4518
3c0563b9 4519 case EXACTFU_SS: /* /\x{df}/iu */
3c0563b9 4520 case EXACTFU: /* /abc/iu */
9a5a5549
KW
4521 folder = foldEQ_latin1;
4522 fold_array = PL_fold_latin1;
984e6dd1 4523 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
9a5a5549
KW
4524 goto do_exactf;
4525
098b07d5
KW
4526 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
4527 patterns */
4528 assert(! is_utf8_pat);
924ba076 4529 /* FALLTHROUGH */
3c0563b9 4530 case EXACTFA: /* /abc/iaa */
2f7f8cb1
KW
4531 folder = foldEQ_latin1;
4532 fold_array = PL_fold_latin1;
57014d77 4533 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2f7f8cb1
KW
4534 goto do_exactf;
4535
2fdb7295
KW
4536 case EXACTF: /* /abc/i This node only generated for
4537 non-utf8 patterns */
4538 assert(! is_utf8_pat);
9a5a5549
KW
4539 folder = foldEQ;
4540 fold_array = PL_fold;
62bf7766 4541 fold_utf8_flags = 0;
9a5a5549
KW
4542
4543 do_exactf:
4544 s = STRING(scan);
24d3c4a9 4545 ln = STR_LEN(scan);
d6a28714 4546
31f05a37
KW
4547 if (utf8_target
4548 || is_utf8_pat
4549 || state_num == EXACTFU_SS
4550 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
4551 {
3c760661
KW
4552 /* Either target or the pattern are utf8, or has the issue where
4553 * the fold lengths may differ. */
be8e71aa 4554 const char * const l = locinput;
220db18a 4555 char *e = reginfo->strend;
bc517b45 4556
984e6dd1 4557 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
fa5b1667 4558 l, &e, 0, utf8_target, fold_utf8_flags))
c3e1d013
KW
4559 {
4560 sayNO;
5486206c 4561 }
d07ddd77 4562 locinput = e;
d07ddd77 4563 break;
a0ed51b3 4564 }
d6a28714 4565
0a138b74 4566 /* Neither the target nor the pattern are utf8 */
1443c94c
DM
4567 if (UCHARAT(s) != nextchr
4568 && !NEXTCHR_IS_EOS
4569 && UCHARAT(s) != fold_array[nextchr])
9a5a5549 4570 {
a0ed51b3 4571 sayNO;
9a5a5549 4572 }
220db18a 4573 if (reginfo->strend - locinput < ln)
b8c5462f 4574 sayNO;
9a5a5549 4575 if (ln > 1 && ! folder(s, locinput, ln))
4633a7c4 4576 sayNO;
24d3c4a9 4577 locinput += ln;
a0d0e21e 4578 break;
9a5a5549 4579 }
63ac0dad
KW
4580
4581 /* XXX Could improve efficiency by separating these all out using a
4582 * macro or in-line function. At that point regcomp.c would no longer
4583 * have to set the FLAGS fields of these */
3c0563b9
DM
4584 case BOUNDL: /* /\b/l */
4585 case NBOUNDL: /* /\B/l */
3c0563b9
DM
4586 case BOUND: /* /\b/ */
4587 case BOUNDU: /* /\b/u */
4588 case BOUNDA: /* /\b/a */
4589 case NBOUND: /* /\B/ */
4590 case NBOUNDU: /* /\B/u */
4591 case NBOUNDA: /* /\B/a */
b2680017 4592 /* was last char in word? */
f2e96b5d
KW
4593 if (utf8_target
4594 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
4595 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
4596 {
9d9163fb 4597 if (locinput == reginfo->strbeg)
b2680017
YO
4598 ln = '\n';
4599 else {
9d9163fb
DM
4600 const U8 * const r =
4601 reghop3((U8*)locinput, -1, (U8*)(reginfo->strbeg));
b2680017 4602
3db24e1e
KW
4603 ln = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,
4604 0, uniflags);
b2680017 4605 }
63ac0dad 4606 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
0eb30aeb 4607 ln = isWORDCHAR_uni(ln);
7016d6eb
DM
4608 if (NEXTCHR_IS_EOS)
4609 n = 0;
4610 else {
4611 LOAD_UTF8_CHARCLASS_ALNUM();
03940dc2 4612 n = swash_fetch(PL_utf8_swash_ptrs[_CC_WORDCHAR], (U8*)locinput,
7016d6eb
DM
4613 utf8_target);
4614 }
b2680017
YO
4615 }
4616 else {
f4cd282c 4617 ln = isWORDCHAR_LC_uvchr(ln);
0eb30aeb 4618 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC_utf8((U8*)locinput);
b2680017
YO
4619 }
4620 }
4621 else {
cfaf538b
KW
4622
4623 /* Here the string isn't utf8, or is utf8 and only ascii
4624 * characters are to match \w. In the latter case looking at
4625 * the byte just prior to the current one may be just the final
4626 * byte of a multi-byte character. This is ok. There are two
4627 * cases:
4628 * 1) it is a single byte character, and then the test is doing
4629 * just what it's supposed to.
4630 * 2) it is a multi-byte character, in which case the final
4631 * byte is never mistakable for ASCII, and so the test
4632 * will say it is not a word character, which is the
4633 * correct answer. */
9d9163fb 4634 ln = (locinput != reginfo->strbeg) ?
b2680017 4635 UCHARAT(locinput - 1) : '\n';
63ac0dad
KW
4636 switch (FLAGS(scan)) {
4637 case REGEX_UNICODE_CHARSET:
4638 ln = isWORDCHAR_L1(ln);
7016d6eb 4639 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_L1(nextchr);
63ac0dad
KW
4640 break;
4641 case REGEX_LOCALE_CHARSET:
0eb30aeb
KW
4642 ln = isWORDCHAR_LC(ln);
4643 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_LC(nextchr);
63ac0dad
KW
4644 break;
4645 case REGEX_DEPENDS_CHARSET:
0eb30aeb
KW
4646 ln = isWORDCHAR(ln);
4647 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR(nextchr);
63ac0dad 4648 break;
cfaf538b 4649 case REGEX_ASCII_RESTRICTED_CHARSET:
c973bd4f 4650 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
cfaf538b 4651 ln = isWORDCHAR_A(ln);
7016d6eb 4652 n = NEXTCHR_IS_EOS ? 0 : isWORDCHAR_A(nextchr);
cfaf538b 4653 break;
63ac0dad
KW
4654 default:
4655 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
b2680017
YO
4656 }
4657 }
63ac0dad
KW
4658 /* Note requires that all BOUNDs be lower than all NBOUNDs in
4659 * regcomp.sym */
4660 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
b2680017
YO
4661 sayNO;
4662 break;
3c0563b9 4663
3c0563b9 4664 case ANYOF: /* /[abc]/ */
7016d6eb
DM
4665 if (NEXTCHR_IS_EOS)
4666 sayNO;
e0193e47 4667 if (utf8_target) {
3db24e1e
KW
4668 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
4669 utf8_target))
09b08e9b 4670 sayNO;
635cd5d4 4671 locinput += UTF8SKIP(locinput);
ffc61ed2
JH
4672 }
4673 else {
20ed0b26 4674 if (!REGINCLASS(rex, scan, (U8*)locinput))
09b08e9b 4675 sayNO;
3640db6b 4676 locinput++;
e0f9d4a8 4677 }
b8c5462f 4678 break;
3c0563b9 4679
3018b823
KW
4680 /* The argument (FLAGS) to all the POSIX node types is the class number
4681 * */
ee9a90b8 4682
3018b823
KW
4683 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
4684 to_complement = 1;
4685 /* FALLTHROUGH */
4686
4687 case POSIXL: /* \w or [:punct:] etc. under /l */
4688 if (NEXTCHR_IS_EOS)
bedac28b 4689 sayNO;
bedac28b 4690
3018b823
KW
4691 /* Use isFOO_lc() for characters within Latin1. (Note that
4692 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4693 * wouldn't be invariant) */
4694 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
eb4e9c04 4695 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
bedac28b
KW
4696 sayNO;
4697 }
4698 }
3018b823
KW
4699 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4700 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
94bb8c36 4701 (U8) TWO_BYTE_UTF8_TO_NATIVE(nextchr,
3018b823
KW
4702 *(locinput + 1))))))
4703 {
bedac28b 4704 sayNO;
3018b823 4705 }
bedac28b 4706 }
3018b823
KW
4707 else { /* Here, must be an above Latin-1 code point */
4708 goto utf8_posix_not_eos;
bedac28b 4709 }
3018b823
KW
4710
4711 /* Here, must be utf8 */
4712 locinput += UTF8SKIP(locinput);
bedac28b
KW
4713 break;
4714
3018b823
KW
4715 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
4716 to_complement = 1;
4717 /* FALLTHROUGH */
4718
4719 case POSIXD: /* \w or [:punct:] etc. under /d */
bedac28b 4720 if (utf8_target) {
3018b823 4721 goto utf8_posix;
bedac28b 4722 }
3018b823
KW
4723 goto posixa;
4724
4725 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
bedac28b 4726
3018b823 4727 if (NEXTCHR_IS_EOS) {
bedac28b
KW
4728 sayNO;
4729 }
bedac28b 4730
3018b823
KW
4731 /* All UTF-8 variants match */
4732 if (! UTF8_IS_INVARIANT(nextchr)) {
4733 goto increment_locinput;
bedac28b 4734 }
ee9a90b8 4735
3018b823
KW
4736 to_complement = 1;
4737 /* FALLTHROUGH */
4738
4739 case POSIXA: /* \w or [:punct:] etc. under /a */
4740
4741 posixa:
4742 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
4743 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
4744 * character is a single byte */
20d0b1e9 4745
3018b823
KW
4746 if (NEXTCHR_IS_EOS
4747 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
4748 FLAGS(scan)))))
4749 {
0658cdde
KW
4750 sayNO;
4751 }
3018b823
KW
4752
4753 /* Here we are either not in utf8, or we matched a utf8-invariant,
4754 * so the next char is the next byte */
3640db6b 4755 locinput++;
0658cdde 4756 break;
3c0563b9 4757
3018b823
KW
4758 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
4759 to_complement = 1;
4760 /* FALLTHROUGH */
4761
4762 case POSIXU: /* \w or [:punct:] etc. under /u */
4763 utf8_posix:
4764 if (NEXTCHR_IS_EOS) {
0658cdde
KW
4765 sayNO;
4766 }
3018b823
KW
4767 utf8_posix_not_eos:
4768
4769 /* Use _generic_isCC() for characters within Latin1. (Note that
4770 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
4771 * wouldn't be invariant) */
4772 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
4773 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
4774 FLAGS(scan)))))
4775 {
4776 sayNO;
4777 }
4778 locinput++;
4779 }
4780 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
4781 if (! (to_complement
94bb8c36 4782 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(nextchr,
3018b823 4783 *(locinput + 1)),
94bb8c36 4784 FLAGS(scan)))))
3018b823
KW
4785 {
4786 sayNO;
4787 }
4788 locinput += 2;
4789 }
4790 else { /* Handle above Latin-1 code points */
4791 classnum = (_char_class_number) FLAGS(scan);
4792 if (classnum < _FIRST_NON_SWASH_CC) {
4793
4794 /* Here, uses a swash to find such code points. Load if if
4795 * not done already */
4796 if (! PL_utf8_swash_ptrs[classnum]) {
4797 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
4798 PL_utf8_swash_ptrs[classnum]
4799 = _core_swash_init("utf8",
2a16ac92
KW
4800 "",
4801 &PL_sv_undef, 1, 0,
4802 PL_XPosix_ptrs[classnum], &flags);
3018b823
KW
4803 }
4804 if (! (to_complement
4805 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
4806 (U8 *) locinput, TRUE))))
4807 {
4808 sayNO;
4809 }
4810 }
4811 else { /* Here, uses macros to find above Latin-1 code points */
4812 switch (classnum) {
4813 case _CC_ENUM_SPACE: /* XXX would require separate
4814 code if we revert the change
4815 of \v matching this */
4816 case _CC_ENUM_PSXSPC:
4817 if (! (to_complement
4818 ^ cBOOL(is_XPERLSPACE_high(locinput))))
4819 {
4820 sayNO;
4821 }
4822 break;
4823 case _CC_ENUM_BLANK:
4824 if (! (to_complement
4825 ^ cBOOL(is_HORIZWS_high(locinput))))
4826 {
4827 sayNO;
4828 }
4829 break;
4830 case _CC_ENUM_XDIGIT:
4831 if (! (to_complement
4832 ^ cBOOL(is_XDIGIT_high(locinput))))
4833 {
4834 sayNO;
4835 }
4836 break;
4837 case _CC_ENUM_VERTSPACE:
4838 if (! (to_complement
4839 ^ cBOOL(is_VERTWS_high(locinput))))
4840 {
4841 sayNO;
4842 }
4843 break;
4844 default: /* The rest, e.g. [:cntrl:], can't match
4845 above Latin1 */
4846 if (! to_complement) {
4847 sayNO;
4848 }
4849 break;
4850 }
4851 }
4852 locinput += UTF8SKIP(locinput);
4853 }
4854 break;
0658cdde 4855
37e2e78e
KW
4856 case CLUMP: /* Match \X: logical Unicode character. This is defined as
4857 a Unicode extended Grapheme Cluster */
4858 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
4859 extended Grapheme Cluster is:
4860
7aee35ff
KW
4861 CR LF
4862 | Prepend* Begin Extend*
4863 | .
37e2e78e 4864
7aee35ff
KW
4865 Begin is: ( Special_Begin | ! Control )
4866 Special_Begin is: ( Regional-Indicator+ | Hangul-syllable )
4867 Extend is: ( Grapheme_Extend | Spacing_Mark )
4868 Control is: [ GCB_Control | CR | LF ]
4869 Hangul-syllable is: ( T+ | ( L* ( L | ( LVT | ( V | LV ) V* ) T* ) ))
37e2e78e 4870
27d4fc33
KW
4871 If we create a 'Regular_Begin' = Begin - Special_Begin, then
4872 we can rewrite
4873
4874 Begin is ( Regular_Begin + Special Begin )
4875
4876 It turns out that 98.4% of all Unicode code points match
4877 Regular_Begin. Doing it this way eliminates a table match in
c101f46d 4878 the previous implementation for almost all Unicode code points.
27d4fc33 4879
37e2e78e
KW
4880 There is a subtlety with Prepend* which showed up in testing.
4881 Note that the Begin, and only the Begin is required in:
4882 | Prepend* Begin Extend*
cc3b396d
KW
4883 Also, Begin contains '! Control'. A Prepend must be a
4884 '! Control', which means it must also be a Begin. What it
4885 comes down to is that if we match Prepend* and then find no
4886 suitable Begin afterwards, that if we backtrack the last
4887 Prepend, that one will be a suitable Begin.
37e2e78e
KW
4888 */
4889
7016d6eb 4890 if (NEXTCHR_IS_EOS)
a0ed51b3 4891 sayNO;
f2ed9b32 4892 if (! utf8_target) {
37e2e78e
KW
4893
4894 /* Match either CR LF or '.', as all the other possibilities
4895 * require utf8 */
4896 locinput++; /* Match the . or CR */
cc3b396d
KW
4897 if (nextchr == '\r' /* And if it was CR, and the next is LF,
4898 match the LF */
220db18a 4899 && locinput < reginfo->strend
e699a1d5
KW
4900 && UCHARAT(locinput) == '\n')
4901 {
4902 locinput++;
4903 }
37e2e78e
KW
4904 }
4905 else {
4906
4907 /* Utf8: See if is ( CR LF ); already know that locinput <
220db18a
DM
4908 * reginfo->strend, so locinput+1 is in bounds */
4909 if ( nextchr == '\r' && locinput+1 < reginfo->strend
f67f9e53 4910 && UCHARAT(locinput + 1) == '\n')
7016d6eb 4911 {
37e2e78e
KW
4912 locinput += 2;
4913 }
4914 else {
45fdf108
KW
4915 STRLEN len;
4916
37e2e78e
KW
4917 /* In case have to backtrack to beginning, then match '.' */
4918 char *starting = locinput;
4919
4920 /* In case have to backtrack the last prepend */
e699a1d5 4921 char *previous_prepend = NULL;
37e2e78e
KW
4922
4923 LOAD_UTF8_CHARCLASS_GCB();
4924
45fdf108 4925 /* Match (prepend)* */
220db18a 4926 while (locinput < reginfo->strend
45fdf108
KW
4927 && (len = is_GCB_Prepend_utf8(locinput)))
4928 {
4929 previous_prepend = locinput;
4930 locinput += len;
a1853d78 4931 }
37e2e78e
KW
4932
4933 /* As noted above, if we matched a prepend character, but
4934 * the next thing won't match, back off the last prepend we
4935 * matched, as it is guaranteed to match the begin */
4936 if (previous_prepend
220db18a 4937 && (locinput >= reginfo->strend
c101f46d
KW
4938 || (! swash_fetch(PL_utf8_X_regular_begin,
4939 (U8*)locinput, utf8_target)
bff53399 4940 && ! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)))
c101f46d 4941 )
37e2e78e
KW
4942 {
4943 locinput = previous_prepend;
4944 }
4945
220db18a 4946 /* Note that here we know reginfo->strend > locinput, as we
37e2e78e
KW
4947 * tested that upon input to this switch case, and if we
4948 * moved locinput forward, we tested the result just above
4949 * and it either passed, or we backed off so that it will
4950 * now pass */
11dfcd49
KW
4951 if (swash_fetch(PL_utf8_X_regular_begin,
4952 (U8*)locinput, utf8_target)) {
27d4fc33
KW
4953 locinput += UTF8SKIP(locinput);
4954 }
bff53399 4955 else if (! is_GCB_SPECIAL_BEGIN_START_utf8(locinput)) {
37e2e78e
KW
4956
4957 /* Here did not match the required 'Begin' in the
4958 * second term. So just match the very first
4959 * character, the '.' of the final term of the regex */
4960 locinput = starting + UTF8SKIP(starting);
27d4fc33 4961 goto exit_utf8;
37e2e78e
KW
4962 } else {
4963
11dfcd49
KW
4964 /* Here is a special begin. It can be composed of
4965 * several individual characters. One possibility is
4966 * RI+ */
45fdf108
KW
4967 if ((len = is_GCB_RI_utf8(locinput))) {
4968 locinput += len;
220db18a 4969 while (locinput < reginfo->strend
45fdf108 4970 && (len = is_GCB_RI_utf8(locinput)))
11dfcd49 4971 {
45fdf108 4972 locinput += len;
11dfcd49 4973 }
45fdf108
KW
4974 } else if ((len = is_GCB_T_utf8(locinput))) {
4975 /* Another possibility is T+ */
4976 locinput += len;
220db18a 4977 while (locinput < reginfo->strend
45fdf108 4978 && (len = is_GCB_T_utf8(locinput)))
11dfcd49 4979 {
45fdf108 4980 locinput += len;
11dfcd49
KW
4981 }
4982 } else {
4983
4984 /* Here, neither RI+ nor T+; must be some other
4985 * Hangul. That means it is one of the others: L,
4986 * LV, LVT or V, and matches:
4987 * L* (L | LVT T* | V * V* T* | LV V* T*) */
4988
4989 /* Match L* */
220db18a 4990 while (locinput < reginfo->strend
45fdf108 4991 && (len = is_GCB_L_utf8(locinput)))
11dfcd49 4992 {
45fdf108 4993 locinput += len;
11dfcd49 4994 }
37e2e78e 4995
11dfcd49
KW
4996 /* Here, have exhausted L*. If the next character
4997 * is not an LV, LVT nor V, it means we had to have
4998 * at least one L, so matches L+ in the original
4999 * equation, we have a complete hangul syllable.
5000 * Are done. */
5001
220db18a 5002 if (locinput < reginfo->strend
45fdf108 5003 && is_GCB_LV_LVT_V_utf8(locinput))
11dfcd49 5004 {
11dfcd49 5005 /* Otherwise keep going. Must be LV, LVT or V.
7d43c479
KW
5006 * See if LVT, by first ruling out V, then LV */
5007 if (! is_GCB_V_utf8(locinput)
5008 /* All but every TCount one is LV */
5009 && (valid_utf8_to_uvchr((U8 *) locinput,
5010 NULL)
5011 - SBASE)
5012 % TCount != 0)
5013 {
11dfcd49
KW
5014 locinput += UTF8SKIP(locinput);
5015 } else {
5016
5017 /* Must be V or LV. Take it, then match
5018 * V* */
5019 locinput += UTF8SKIP(locinput);
220db18a 5020 while (locinput < reginfo->strend
45fdf108 5021 && (len = is_GCB_V_utf8(locinput)))
11dfcd49 5022 {
45fdf108 5023 locinput += len;
11dfcd49
KW
5024 }
5025 }
37e2e78e 5026
11dfcd49 5027 /* And any of LV, LVT, or V can be followed
45fdf108 5028 * by T* */
220db18a 5029 while (locinput < reginfo->strend
45fdf108 5030 && (len = is_GCB_T_utf8(locinput)))
11dfcd49 5031 {
45fdf108 5032 locinput += len;
11dfcd49
KW
5033 }
5034 }
cd94d768 5035 }
11dfcd49 5036 }
37e2e78e 5037
11dfcd49 5038 /* Match any extender */
220db18a 5039 while (locinput < reginfo->strend
11dfcd49
KW
5040 && swash_fetch(PL_utf8_X_extend,
5041 (U8*)locinput, utf8_target))
5042 {
5043 locinput += UTF8SKIP(locinput);
5044 }
37e2e78e 5045 }
27d4fc33 5046 exit_utf8:
220db18a 5047 if (locinput > reginfo->strend) sayNO;
37e2e78e 5048 }
a0ed51b3 5049 break;
81714fb9 5050
3c0563b9 5051 case NREFFL: /* /\g{name}/il */
d7ef4b73
KW
5052 { /* The capture buffer cases. The ones beginning with N for the
5053 named buffers just convert to the equivalent numbered and
5054 pretend they were called as the corresponding numbered buffer
5055 op. */
26ecd678
TC
5056 /* don't initialize these in the declaration, it makes C++
5057 unhappy */
9d9163fb 5058 const char *s;
ff1157ca 5059 char type;
8368298a
TC
5060 re_fold_t folder;
5061 const U8 *fold_array;
26ecd678 5062 UV utf8_fold_flags;
8368298a 5063
d7ef4b73
KW
5064 folder = foldEQ_locale;
5065 fold_array = PL_fold_locale;
5066 type = REFFL;
cea315b6 5067 utf8_fold_flags = FOLDEQ_LOCALE;
d7ef4b73
KW
5068 goto do_nref;
5069
3c0563b9 5070 case NREFFA: /* /\g{name}/iaa */
2f7f8cb1
KW
5071 folder = foldEQ_latin1;
5072 fold_array = PL_fold_latin1;
5073 type = REFFA;
5074 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5075 goto do_nref;
5076
3c0563b9 5077 case NREFFU: /* /\g{name}/iu */
d7ef4b73
KW
5078 folder = foldEQ_latin1;
5079 fold_array = PL_fold_latin1;
5080 type = REFFU;
d513472c 5081 utf8_fold_flags = 0;
d7ef4b73
KW
5082 goto do_nref;
5083
3c0563b9 5084 case NREFF: /* /\g{name}/i */
d7ef4b73
KW
5085 folder = foldEQ;
5086 fold_array = PL_fold;
5087 type = REFF;
d513472c 5088 utf8_fold_flags = 0;
d7ef4b73
KW
5089 goto do_nref;
5090
3c0563b9 5091 case NREF: /* /\g{name}/ */
d7ef4b73 5092 type = REF;
83d7b90b
KW
5093 folder = NULL;
5094 fold_array = NULL;
d513472c 5095 utf8_fold_flags = 0;
d7ef4b73
KW
5096 do_nref:
5097
5098 /* For the named back references, find the corresponding buffer
5099 * number */
0a4db386
YO
5100 n = reg_check_named_buff_matched(rex,scan);
5101
d7ef4b73 5102 if ( ! n ) {
81714fb9 5103 sayNO;
d7ef4b73
KW
5104 }
5105 goto do_nref_ref_common;
5106
3c0563b9 5107 case REFFL: /* /\1/il */
d7ef4b73
KW
5108 folder = foldEQ_locale;
5109 fold_array = PL_fold_locale;
cea315b6 5110 utf8_fold_flags = FOLDEQ_LOCALE;
d7ef4b73
KW
5111 goto do_ref;
5112
3c0563b9 5113 case REFFA: /* /\1/iaa */
2f7f8cb1
KW
5114 folder = foldEQ_latin1;
5115 fold_array = PL_fold_latin1;
5116 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5117 goto do_ref;
5118
3c0563b9 5119 case REFFU: /* /\1/iu */
d7ef4b73
KW
5120 folder = foldEQ_latin1;
5121 fold_array = PL_fold_latin1;
d513472c 5122 utf8_fold_flags = 0;
d7ef4b73
KW
5123 goto do_ref;
5124
3c0563b9 5125 case REFF: /* /\1/i */
d7ef4b73
KW
5126 folder = foldEQ;
5127 fold_array = PL_fold;
d513472c 5128 utf8_fold_flags = 0;
83d7b90b 5129 goto do_ref;
d7ef4b73 5130
3c0563b9 5131 case REF: /* /\1/ */
83d7b90b
KW
5132 folder = NULL;
5133 fold_array = NULL;
d513472c 5134 utf8_fold_flags = 0;
83d7b90b 5135
d7ef4b73 5136 do_ref:
81714fb9 5137 type = OP(scan);
d7ef4b73
KW
5138 n = ARG(scan); /* which paren pair */
5139
5140 do_nref_ref_common:
b93070ed 5141 ln = rex->offs[n].start;
1cb48e53 5142 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
b93070ed 5143 if (rex->lastparen < n || ln == -1)
af3f8c16 5144 sayNO; /* Do not match unless seen CLOSEn. */
b93070ed 5145 if (ln == rex->offs[n].end)
a0d0e21e 5146 break;
a0ed51b3 5147
9d9163fb 5148 s = reginfo->strbeg + ln;
d7ef4b73 5149 if (type != REF /* REF can do byte comparison */
31f05a37
KW
5150 && (utf8_target || type == REFFU || type == REFFL))
5151 {
220db18a 5152 char * limit = reginfo->strend;
d7ef4b73
KW
5153
5154 /* This call case insensitively compares the entire buffer
5155 * at s, with the current input starting at locinput, but
220db18a
DM
5156 * not going off the end given by reginfo->strend, and
5157 * returns in <limit> upon success, how much of the
5158 * current input was matched */
b93070ed 5159 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
d513472c 5160 locinput, &limit, 0, utf8_target, utf8_fold_flags))
d7ef4b73
KW
5161 {
5162 sayNO;
a0ed51b3 5163 }
d7ef4b73 5164 locinput = limit;
a0ed51b3
LW
5165 break;
5166 }
5167
d7ef4b73 5168 /* Not utf8: Inline the first character, for speed. */
7016d6eb
DM
5169 if (!NEXTCHR_IS_EOS &&
5170 UCHARAT(s) != nextchr &&
81714fb9 5171 (type == REF ||
d7ef4b73 5172 UCHARAT(s) != fold_array[nextchr]))
4633a7c4 5173 sayNO;
b93070ed 5174 ln = rex->offs[n].end - ln;
220db18a 5175 if (locinput + ln > reginfo->strend)
4633a7c4 5176 sayNO;
81714fb9 5177 if (ln > 1 && (type == REF
24d3c4a9 5178 ? memNE(s, locinput, ln)
d7ef4b73 5179 : ! folder(s, locinput, ln)))
4633a7c4 5180 sayNO;
24d3c4a9 5181 locinput += ln;
a0d0e21e 5182 break;
81714fb9 5183 }
3c0563b9
DM
5184
5185 case NOTHING: /* null op; e.g. the 'nothing' following
5186 * the '*' in m{(a+|b)*}' */
5187 break;
5188 case TAIL: /* placeholder while compiling (A|B|C) */
a0d0e21e 5189 break;
3c0563b9 5190
40a82448
DM
5191#undef ST
5192#define ST st->u.eval
c277df42 5193 {
c277df42 5194 SV *ret;
d2f13c59 5195 REGEXP *re_sv;
6bda09f9 5196 regexp *re;
f8fc2ecf 5197 regexp_internal *rei;
1a147d38
YO
5198 regnode *startpoint;
5199
3c0563b9 5200 case GOSTART: /* (?R) */
e7707071
YO
5201 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
5202 if (cur_eval && cur_eval->locinput==locinput) {
24b23f37 5203 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
1a147d38 5204 Perl_croak(aTHX_ "Infinite recursion in regex");
4b196cd4 5205 if ( ++nochange_depth > max_nochange_depth )
1a147d38
YO
5206 Perl_croak(aTHX_
5207 "Pattern subroutine nesting without pos change"
5208 " exceeded limit in regex");
6bda09f9
YO
5209 } else {
5210 nochange_depth = 0;
1a147d38 5211 }
288b8c02 5212 re_sv = rex_sv;
6bda09f9 5213 re = rex;
f8fc2ecf 5214 rei = rexi;
1a147d38 5215 if (OP(scan)==GOSUB) {
6bda09f9
YO
5216 startpoint = scan + ARG2L(scan);
5217 ST.close_paren = ARG(scan);
5218 } else {
f8fc2ecf 5219 startpoint = rei->program+1;
6bda09f9
YO
5220 ST.close_paren = 0;
5221 }
d1b2014a
YO
5222
5223 /* Save all the positions seen so far. */
5224 ST.cp = regcppush(rex, 0, maxopenparen);
5225 REGCP_SET(ST.lastcp);
5226
5227 /* and then jump to the code we share with EVAL */
6bda09f9 5228 goto eval_recurse_doit;
a74ff37d 5229 /* NOTREACHED */
3c0563b9 5230
6bda09f9
YO
5231 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
5232 if (cur_eval && cur_eval->locinput==locinput) {
4b196cd4 5233 if ( ++nochange_depth > max_nochange_depth )
1a147d38 5234 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6bda09f9
YO
5235 } else {
5236 nochange_depth = 0;
5237 }
8e5e9ebe 5238 {
4aabdb9b 5239 /* execute the code in the {...} */
81ed78b2 5240
4aabdb9b 5241 dSP;
a6dc34f1 5242 IV before;
1f4d1a1e 5243 OP * const oop = PL_op;
4aabdb9b 5244 COP * const ocurcop = PL_curcop;
81ed78b2 5245 OP *nop;
81ed78b2 5246 CV *newcv;
91332126 5247
74088413 5248 /* save *all* paren positions */
92da3157 5249 regcppush(rex, 0, maxopenparen);
74088413
DM
5250 REGCP_SET(runops_cp);
5251
81ed78b2
DM
5252 if (!caller_cv)
5253 caller_cv = find_runcv(NULL);
5254
4aabdb9b 5255 n = ARG(scan);
81ed78b2 5256
b30fcab9 5257 if (rexi->data->what[n] == 'r') { /* code from an external qr */
8d919b0a 5258 newcv = (ReANY(
b30fcab9
DM
5259 (REGEXP*)(rexi->data->data[n])
5260 ))->qr_anoncv
81ed78b2
DM
5261 ;
5262 nop = (OP*)rexi->data->data[n+1];
b30fcab9
DM
5263 }
5264 else if (rexi->data->what[n] == 'l') { /* literal code */
81ed78b2
DM
5265 newcv = caller_cv;
5266 nop = (OP*)rexi->data->data[n];
5267 assert(CvDEPTH(newcv));
68e2671b
DM
5268 }
5269 else {
d24ca0c5
DM
5270 /* literal with own CV */
5271 assert(rexi->data->what[n] == 'L');
81ed78b2
DM
5272 newcv = rex->qr_anoncv;
5273 nop = (OP*)rexi->data->data[n];
68e2671b 5274 }
81ed78b2 5275
0e458318
DM
5276 /* normally if we're about to execute code from the same
5277 * CV that we used previously, we just use the existing
5278 * CX stack entry. However, its possible that in the
5279 * meantime we may have backtracked, popped from the save
5280 * stack, and undone the SAVECOMPPAD(s) associated with
5281 * PUSH_MULTICALL; in which case PL_comppad no longer
5282 * points to newcv's pad. */
5283 if (newcv != last_pushed_cv || PL_comppad != last_pad)
5284 {
b0065247
DM
5285 U8 flags = (CXp_SUB_RE |
5286 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
0e458318 5287 if (last_pushed_cv) {
b0065247 5288 CHANGE_MULTICALL_FLAGS(newcv, flags);
0e458318
DM
5289 }
5290 else {
b0065247 5291 PUSH_MULTICALL_FLAGS(newcv, flags);
0e458318
DM
5292 }
5293 last_pushed_cv = newcv;
5294 }
c31ee3bb
DM
5295 else {
5296 /* these assignments are just to silence compiler
5297 * warnings */
5298 multicall_cop = NULL;
5299 newsp = NULL;
5300 }
0e458318
DM
5301 last_pad = PL_comppad;
5302
2e2e3f36
DM
5303 /* the initial nextstate you would normally execute
5304 * at the start of an eval (which would cause error
5305 * messages to come from the eval), may be optimised
5306 * away from the execution path in the regex code blocks;
5307 * so manually set PL_curcop to it initially */
5308 {
81ed78b2 5309 OP *o = cUNOPx(nop)->op_first;
2e2e3f36
DM
5310 assert(o->op_type == OP_NULL);
5311 if (o->op_targ == OP_SCOPE) {
5312 o = cUNOPo->op_first;
5313 }
5314 else {
5315 assert(o->op_targ == OP_LEAVE);
5316 o = cUNOPo->op_first;
5317 assert(o->op_type == OP_ENTER);
1ed44841 5318 o = OP_SIBLING(o);
2e2e3f36
DM
5319 }
5320
5321 if (o->op_type != OP_STUB) {
5322 assert( o->op_type == OP_NEXTSTATE
5323 || o->op_type == OP_DBSTATE
5324 || (o->op_type == OP_NULL
5325 && ( o->op_targ == OP_NEXTSTATE
5326 || o->op_targ == OP_DBSTATE
5327 )
5328 )
5329 );
5330 PL_curcop = (COP*)o;
5331 }
5332 }
81ed78b2 5333 nop = nop->op_next;
2e2e3f36 5334
24b23f37 5335 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
81ed78b2
DM
5336 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
5337
8adc0f72 5338 rex->offs[0].end = locinput - reginfo->strbeg;
bf2039a9 5339 if (reginfo->info_aux_eval->pos_magic)
25fdce4a
FC
5340 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
5341 reginfo->sv, reginfo->strbeg,
5342 locinput - reginfo->strbeg);
4aabdb9b 5343
2bf803e2
YO
5344 if (sv_yes_mark) {
5345 SV *sv_mrk = get_sv("REGMARK", 1);
5346 sv_setsv(sv_mrk, sv_yes_mark);
5347 }
5348
81ed78b2
DM
5349 /* we don't use MULTICALL here as we want to call the
5350 * first op of the block of interest, rather than the
5351 * first op of the sub */
a6dc34f1 5352 before = (IV)(SP-PL_stack_base);
81ed78b2 5353 PL_op = nop;
8e5e9ebe
RGS
5354 CALLRUNOPS(aTHX); /* Scalar context. */
5355 SPAGAIN;
a6dc34f1 5356 if ((IV)(SP-PL_stack_base) == before)
075aa684 5357 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
8e5e9ebe
RGS
5358 else {
5359 ret = POPs;
5360 PUTBACK;
5361 }
4aabdb9b 5362
e4bfbed3
DM
5363 /* before restoring everything, evaluate the returned
5364 * value, so that 'uninit' warnings don't use the wrong
497d0a96
DM
5365 * PL_op or pad. Also need to process any magic vars
5366 * (e.g. $1) *before* parentheses are restored */
e4bfbed3
DM
5367
5368 PL_op = NULL;
5369
5e98dac2 5370 re_sv = NULL;
e4bfbed3
DM
5371 if (logical == 0) /* (?{})/ */
5372 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
5373 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
5374 sw = cBOOL(SvTRUE(ret));
5375 logical = 0;
5376 }
5377 else { /* /(??{}) */
497d0a96
DM
5378 /* if its overloaded, let the regex compiler handle
5379 * it; otherwise extract regex, or stringify */
237da807 5380 if (SvGMAGICAL(ret))
2685dc2d 5381 ret = sv_mortalcopy(ret);
497d0a96
DM
5382 if (!SvAMAGIC(ret)) {
5383 SV *sv = ret;
5384 if (SvROK(sv))
5385 sv = SvRV(sv);
5386 if (SvTYPE(sv) == SVt_REGEXP)
5387 re_sv = (REGEXP*) sv;
63620942
FC
5388 else if (SvSMAGICAL(ret)) {
5389 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
497d0a96
DM
5390 if (mg)
5391 re_sv = (REGEXP *) mg->mg_obj;
5392 }
e4bfbed3 5393
2685dc2d 5394 /* force any undef warnings here */
237da807
FC
5395 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
5396 ret = sv_mortalcopy(ret);
497d0a96
DM
5397 (void) SvPV_force_nolen(ret);
5398 }
e4bfbed3
DM
5399 }
5400
5401 }
5402
81ed78b2
DM
5403 /* *** Note that at this point we don't restore
5404 * PL_comppad, (or pop the CxSUB) on the assumption it may
5405 * be used again soon. This is safe as long as nothing
5406 * in the regexp code uses the pad ! */
4aabdb9b 5407 PL_op = oop;
4aabdb9b 5408 PL_curcop = ocurcop;
92da3157 5409 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
f5df269c 5410 PL_curpm = PL_reg_curpm;
e4bfbed3
DM
5411
5412 if (logical != 2)
4aabdb9b 5413 break;
8e5e9ebe 5414 }
e4bfbed3
DM
5415
5416 /* only /(??{})/ from now on */
24d3c4a9 5417 logical = 0;
4aabdb9b 5418 {
4f639d21
DM
5419 /* extract RE object from returned value; compiling if
5420 * necessary */
5c35adbb 5421
575c37f6
DM
5422 if (re_sv) {
5423 re_sv = reg_temp_copy(NULL, re_sv);
288b8c02 5424 }
0f5d15d6 5425 else {
c737faaf 5426 U32 pm_flags = 0;
0f5d15d6 5427
9753d940
DM
5428 if (SvUTF8(ret) && IN_BYTES) {
5429 /* In use 'bytes': make a copy of the octet
5430 * sequence, but without the flag on */
b9ad30b4
NC
5431 STRLEN len;
5432 const char *const p = SvPV(ret, len);
5433 ret = newSVpvn_flags(p, len, SVs_TEMP);
5434 }
732caac7
DM
5435 if (rex->intflags & PREGf_USE_RE_EVAL)
5436 pm_flags |= PMf_USE_RE_EVAL;
5437
5438 /* if we got here, it should be an engine which
5439 * supports compiling code blocks and stuff */
5440 assert(rex->engine && rex->engine->op_comp);
ec841a27 5441 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
575c37f6 5442 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
ec841a27
DM
5443 rex->engine, NULL, NULL,
5444 /* copy /msix etc to inner pattern */
13f27704 5445 ARG2L(scan),
ec841a27 5446 pm_flags);
732caac7 5447
9041c2e3 5448 if (!(SvFLAGS(ret)
237da807
FC
5449 & (SVs_TEMP | SVs_GMG | SVf_ROK))
5450 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
a2794585
NC
5451 /* This isn't a first class regexp. Instead, it's
5452 caching a regexp onto an existing, Perl visible
5453 scalar. */
575c37f6 5454 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
3ce3ed55 5455 }
0f5d15d6 5456 }
e1ff3a88 5457 SAVEFREESV(re_sv);
8d919b0a 5458 re = ReANY(re_sv);
4aabdb9b 5459 }
07bc277f 5460 RXp_MATCH_COPIED_off(re);
28d8d7f4
YO
5461 re->subbeg = rex->subbeg;
5462 re->sublen = rex->sublen;
6502e081
DM
5463 re->suboffset = rex->suboffset;
5464 re->subcoffset = rex->subcoffset;
d1b2014a
YO
5465 re->lastparen = 0;
5466 re->lastcloseparen = 0;
f8fc2ecf 5467 rei = RXi_GET(re);
6bda09f9 5468 DEBUG_EXECUTE_r(
220db18a
DM
5469 debug_start_match(re_sv, utf8_target, locinput,
5470 reginfo->strend, "Matching embedded");
6bda09f9 5471 );
f8fc2ecf 5472 startpoint = rei->program + 1;
1a147d38 5473 ST.close_paren = 0; /* only used for GOSUB */
d1b2014a
YO
5474 /* Save all the seen positions so far. */
5475 ST.cp = regcppush(rex, 0, maxopenparen);
5476 REGCP_SET(ST.lastcp);
5477 /* and set maxopenparen to 0, since we are starting a "fresh" match */
5478 maxopenparen = 0;
5479 /* run the pattern returned from (??{...}) */
aa283a38 5480
d1b2014a
YO
5481 eval_recurse_doit: /* Share code with GOSUB below this line
5482 * At this point we expect the stack context to be
5483 * set up correctly */
4aabdb9b 5484
1cb95af7
DM
5485 /* invalidate the S-L poscache. We're now executing a
5486 * different set of WHILEM ops (and their associated
5487 * indexes) against the same string, so the bits in the
5488 * cache are meaningless. Setting maxiter to zero forces
5489 * the cache to be invalidated and zeroed before reuse.
5490 * XXX This is too dramatic a measure. Ideally we should
5491 * save the old cache and restore when running the outer
5492 * pattern again */
1cb48e53 5493 reginfo->poscache_maxiter = 0;
4aabdb9b 5494
d1b2014a 5495 /* the new regexp might have a different is_utf8_pat than we do */
aed7b151 5496 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
faec1544 5497
288b8c02 5498 ST.prev_rex = rex_sv;
faec1544 5499 ST.prev_curlyx = cur_curlyx;
ec43f78b
DM
5500 rex_sv = re_sv;
5501 SET_reg_curpm(rex_sv);
288b8c02 5502 rex = re;
f8fc2ecf 5503 rexi = rei;
faec1544 5504 cur_curlyx = NULL;
40a82448 5505 ST.B = next;
faec1544
DM
5506 ST.prev_eval = cur_eval;
5507 cur_eval = st;
faec1544 5508 /* now continue from first node in postoned RE */
4d5016e5 5509 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
a74ff37d 5510 /* NOTREACHED */
e5964223 5511 NOT_REACHED;
c277df42 5512 }
40a82448 5513
faec1544
DM
5514 case EVAL_AB: /* cleanup after a successful (??{A})B */
5515 /* note: this is called twice; first after popping B, then A */
ec43f78b 5516 rex_sv = ST.prev_rex;
aed7b151 5517 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
ec43f78b 5518 SET_reg_curpm(rex_sv);
8d919b0a 5519 rex = ReANY(rex_sv);
f8fc2ecf 5520 rexi = RXi_GET(rex);
4b22688e
YO
5521 {
5522 /* preserve $^R across LEAVE's. See Bug 121070. */
5523 SV *save_sv= GvSV(PL_replgv);
5524 SvREFCNT_inc(save_sv);
5525 regcpblow(ST.cp); /* LEAVE in disguise */
5526 sv_setsv(GvSV(PL_replgv), save_sv);
5527 SvREFCNT_dec(save_sv);
5528 }
faec1544
DM
5529 cur_eval = ST.prev_eval;
5530 cur_curlyx = ST.prev_curlyx;
34a81e2b 5531
1cb95af7 5532 /* Invalidate cache. See "invalidate" comment above. */
1cb48e53 5533 reginfo->poscache_maxiter = 0;
e7707071 5534 if ( nochange_depth )
4b196cd4 5535 nochange_depth--;
262b90c4 5536 sayYES;
40a82448 5537
40a82448 5538
faec1544
DM
5539 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
5540 /* note: this is called twice; first after popping B, then A */
ec43f78b 5541 rex_sv = ST.prev_rex;
aed7b151 5542 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
ec43f78b 5543 SET_reg_curpm(rex_sv);
8d919b0a 5544 rex = ReANY(rex_sv);
f8fc2ecf 5545 rexi = RXi_GET(rex);
0357f1fd 5546
40a82448 5547 REGCP_UNWIND(ST.lastcp);
92da3157 5548 regcppop(rex, &maxopenparen);
faec1544
DM
5549 cur_eval = ST.prev_eval;
5550 cur_curlyx = ST.prev_curlyx;
1cb95af7 5551 /* Invalidate cache. See "invalidate" comment above. */
1cb48e53 5552 reginfo->poscache_maxiter = 0;
e7707071 5553 if ( nochange_depth )
4b196cd4 5554 nochange_depth--;
40a82448 5555 sayNO_SILENT;
40a82448
DM
5556#undef ST
5557
3c0563b9 5558 case OPEN: /* ( */
c277df42 5559 n = ARG(scan); /* which paren pair */
9d9163fb 5560 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
92da3157
DM
5561 if (n > maxopenparen)
5562 maxopenparen = n;
495f47a5 5563 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
92da3157 5564 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
495f47a5
DM
5565 PTR2UV(rex),
5566 PTR2UV(rex->offs),
5567 (UV)n,
5568 (IV)rex->offs[n].start_tmp,
92da3157 5569 (UV)maxopenparen
495f47a5 5570 ));
e2e6a0f1 5571 lastopen = n;
a0d0e21e 5572 break;
495f47a5
DM
5573
5574/* XXX really need to log other places start/end are set too */
5575#define CLOSE_CAPTURE \
5576 rex->offs[n].start = rex->offs[n].start_tmp; \
9d9163fb 5577 rex->offs[n].end = locinput - reginfo->strbeg; \
495f47a5
DM
5578 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
5579 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
5580 PTR2UV(rex), \
5581 PTR2UV(rex->offs), \
5582 (UV)n, \
5583 (IV)rex->offs[n].start, \
5584 (IV)rex->offs[n].end \
5585 ))
5586
3c0563b9 5587 case CLOSE: /* ) */
c277df42 5588 n = ARG(scan); /* which paren pair */
495f47a5 5589 CLOSE_CAPTURE;
b93070ed
DM
5590 if (n > rex->lastparen)
5591 rex->lastparen = n;
5592 rex->lastcloseparen = n;
3b6647e0 5593 if (cur_eval && cur_eval->u.eval.close_paren == n) {
6bda09f9
YO
5594 goto fake_end;
5595 }
a0d0e21e 5596 break;
3c0563b9
DM
5597
5598 case ACCEPT: /* (*ACCEPT) */
e2e6a0f1
YO
5599 if (ARG(scan)){
5600 regnode *cursor;
5601 for (cursor=scan;
5602 cursor && OP(cursor)!=END;
5603 cursor=regnext(cursor))
5604 {
5605 if ( OP(cursor)==CLOSE ){
5606 n = ARG(cursor);
5607 if ( n <= lastopen ) {
495f47a5 5608 CLOSE_CAPTURE;
b93070ed
DM
5609 if (n > rex->lastparen)
5610 rex->lastparen = n;
5611 rex->lastcloseparen = n;
3b6647e0
RB
5612 if ( n == ARG(scan) || (cur_eval &&
5613 cur_eval->u.eval.close_paren == n))
e2e6a0f1
YO
5614 break;
5615 }
5616 }
5617 }
5618 }
5619 goto fake_end;
a74ff37d 5620 /* NOTREACHED */
3c0563b9
DM
5621
5622 case GROUPP: /* (?(1)) */
c277df42 5623 n = ARG(scan); /* which paren pair */
b93070ed 5624 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
c277df42 5625 break;
3c0563b9
DM
5626
5627 case NGROUPP: /* (?(<name>)) */
0a4db386 5628 /* reg_check_named_buff_matched returns 0 for no match */
f2338a2e 5629 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
0a4db386 5630 break;
3c0563b9
DM
5631
5632 case INSUBP: /* (?(R)) */
0a4db386 5633 n = ARG(scan);
3b6647e0 5634 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
0a4db386 5635 break;
3c0563b9
DM
5636
5637 case DEFINEP: /* (?(DEFINE)) */
0a4db386
YO
5638 sw = 0;
5639 break;
3c0563b9
DM
5640
5641 case IFTHEN: /* (?(cond)A|B) */
1cb48e53 5642 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
24d3c4a9 5643 if (sw)
c277df42
IZ
5644 next = NEXTOPER(NEXTOPER(scan));
5645 else {
5646 next = scan + ARG(scan);
5647 if (OP(next) == IFTHEN) /* Fake one. */
5648 next = NEXTOPER(NEXTOPER(next));
5649 }
5650 break;
3c0563b9
DM
5651
5652 case LOGICAL: /* modifier for EVAL and IFMATCH */
24d3c4a9 5653 logical = scan->flags;
c277df42 5654 break;
c476f425 5655
2ab05381 5656/*******************************************************************
2ab05381 5657
c476f425
DM
5658The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
5659pattern, where A and B are subpatterns. (For simple A, CURLYM or
5660STAR/PLUS/CURLY/CURLYN are used instead.)
2ab05381 5661
c476f425 5662A*B is compiled as <CURLYX><A><WHILEM><B>
2ab05381 5663
c476f425
DM
5664On entry to the subpattern, CURLYX is called. This pushes a CURLYX
5665state, which contains the current count, initialised to -1. It also sets
5666cur_curlyx to point to this state, with any previous value saved in the
5667state block.
2ab05381 5668
c476f425
DM
5669CURLYX then jumps straight to the WHILEM op, rather than executing A,
5670since the pattern may possibly match zero times (i.e. it's a while {} loop
5671rather than a do {} while loop).
2ab05381 5672
c476f425
DM
5673Each entry to WHILEM represents a successful match of A. The count in the
5674CURLYX block is incremented, another WHILEM state is pushed, and execution
5675passes to A or B depending on greediness and the current count.
2ab05381 5676
c476f425
DM
5677For example, if matching against the string a1a2a3b (where the aN are
5678substrings that match /A/), then the match progresses as follows: (the
5679pushed states are interspersed with the bits of strings matched so far):
2ab05381 5680
c476f425
DM
5681 <CURLYX cnt=-1>
5682 <CURLYX cnt=0><WHILEM>
5683 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
5684 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
5685 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
5686 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
2ab05381 5687
c476f425
DM
5688(Contrast this with something like CURLYM, which maintains only a single
5689backtrack state:
2ab05381 5690
c476f425
DM
5691 <CURLYM cnt=0> a1
5692 a1 <CURLYM cnt=1> a2
5693 a1 a2 <CURLYM cnt=2> a3
5694 a1 a2 a3 <CURLYM cnt=3> b
5695)
2ab05381 5696
c476f425
DM
5697Each WHILEM state block marks a point to backtrack to upon partial failure
5698of A or B, and also contains some minor state data related to that
5699iteration. The CURLYX block, pointed to by cur_curlyx, contains the
5700overall state, such as the count, and pointers to the A and B ops.
2ab05381 5701
c476f425
DM
5702This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
5703must always point to the *current* CURLYX block, the rules are:
2ab05381 5704
c476f425
DM
5705When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
5706and set cur_curlyx to point the new block.
2ab05381 5707
c476f425
DM
5708When popping the CURLYX block after a successful or unsuccessful match,
5709restore the previous cur_curlyx.
2ab05381 5710
c476f425
DM
5711When WHILEM is about to execute B, save the current cur_curlyx, and set it
5712to the outer one saved in the CURLYX block.
2ab05381 5713
c476f425
DM
5714When popping the WHILEM block after a successful or unsuccessful B match,
5715restore the previous cur_curlyx.
2ab05381 5716
c476f425
DM
5717Here's an example for the pattern (AI* BI)*BO
5718I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
2ab05381 5719
c476f425
DM
5720cur_
5721curlyx backtrack stack
5722------ ---------------
5723NULL
5724CO <CO prev=NULL> <WO>
5725CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5726CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5727NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
2ab05381 5728
c476f425
DM
5729At this point the pattern succeeds, and we work back down the stack to
5730clean up, restoring as we go:
95b24440 5731
c476f425
DM
5732CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
5733CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
5734CO <CO prev=NULL> <WO>
5735NULL
a0374537 5736
c476f425
DM
5737*******************************************************************/
5738
5739#define ST st->u.curlyx
5740
5741 case CURLYX: /* start of /A*B/ (for complex A) */
5742 {
5743 /* No need to save/restore up to this paren */
5744 I32 parenfloor = scan->flags;
5745
5746 assert(next); /* keep Coverity happy */
5747 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
5748 next += ARG(next);
5749
5750 /* XXXX Probably it is better to teach regpush to support
92da3157 5751 parenfloor > maxopenparen ... */
b93070ed
DM
5752 if (parenfloor > (I32)rex->lastparen)
5753 parenfloor = rex->lastparen; /* Pessimization... */
c476f425
DM
5754
5755 ST.prev_curlyx= cur_curlyx;
5756 cur_curlyx = st;
5757 ST.cp = PL_savestack_ix;
5758
5759 /* these fields contain the state of the current curly.
5760 * they are accessed by subsequent WHILEMs */
5761 ST.parenfloor = parenfloor;
d02d6d97 5762 ST.me = scan;
c476f425 5763 ST.B = next;
24d3c4a9
DM
5764 ST.minmod = minmod;
5765 minmod = 0;
c476f425
DM
5766 ST.count = -1; /* this will be updated by WHILEM */
5767 ST.lastloc = NULL; /* this will be updated by WHILEM */
5768
4d5016e5 5769 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
a74ff37d 5770 /* NOTREACHED */
e5964223 5771 NOT_REACHED;
c476f425 5772 }
a0d0e21e 5773
c476f425 5774 case CURLYX_end: /* just finished matching all of A*B */
c476f425
DM
5775 cur_curlyx = ST.prev_curlyx;
5776 sayYES;
a74ff37d 5777 /* NOTREACHED */
e5964223 5778 NOT_REACHED;
a0d0e21e 5779
c476f425
DM
5780 case CURLYX_end_fail: /* just failed to match all of A*B */
5781 regcpblow(ST.cp);
5782 cur_curlyx = ST.prev_curlyx;
5783 sayNO;
a74ff37d 5784 /* NOTREACHED */
e5964223 5785 NOT_REACHED;
4633a7c4 5786
a0d0e21e 5787
c476f425
DM
5788#undef ST
5789#define ST st->u.whilem
5790
5791 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
5792 {
5793 /* see the discussion above about CURLYX/WHILEM */
c476f425 5794 I32 n;
1a522d5d
JH
5795 int min, max;
5796 regnode *A;
d02d6d97 5797
c476f425 5798 assert(cur_curlyx); /* keep Coverity happy */
1a522d5d
JH
5799
5800 min = ARG1(cur_curlyx->u.curlyx.me);
5801 max = ARG2(cur_curlyx->u.curlyx.me);
5802 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
c476f425
DM
5803 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
5804 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
5805 ST.cache_offset = 0;
5806 ST.cache_mask = 0;
5807
c476f425
DM
5808
5809 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
d02d6d97
DM
5810 "%*s whilem: matched %ld out of %d..%d\n",
5811 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
c476f425 5812 );
a0d0e21e 5813
c476f425 5814 /* First just match a string of min A's. */
a0d0e21e 5815
d02d6d97 5816 if (n < min) {
92da3157
DM
5817 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5818 maxopenparen);
c476f425 5819 cur_curlyx->u.curlyx.lastloc = locinput;
92e82afa
YO
5820 REGCP_SET(ST.lastcp);
5821
4d5016e5 5822 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
a74ff37d 5823 /* NOTREACHED */
e5964223 5824 NOT_REACHED;
c476f425
DM
5825 }
5826
5827 /* If degenerate A matches "", assume A done. */
5828
5829 if (locinput == cur_curlyx->u.curlyx.lastloc) {
5830 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5831 "%*s whilem: empty match detected, trying continuation...\n",
5832 REPORT_CODE_OFF+depth*2, "")
5833 );
5834 goto do_whilem_B_max;
5835 }
5836
1cb95af7
DM
5837 /* super-linear cache processing.
5838 *
5839 * The idea here is that for certain types of CURLYX/WHILEM -
5840 * principally those whose upper bound is infinity (and
5841 * excluding regexes that have things like \1 and other very
5842 * non-regular expresssiony things), then if a pattern like
5843 * /....A*.../ fails and we backtrack to the WHILEM, then we
5844 * make a note that this particular WHILEM op was at string
5845 * position 47 (say) when the rest of pattern failed. Then, if
5846 * we ever find ourselves back at that WHILEM, and at string
5847 * position 47 again, we can just fail immediately rather than
5848 * running the rest of the pattern again.
5849 *
5850 * This is very handy when patterns start to go
5851 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
5852 * with a combinatorial explosion of backtracking.
5853 *
5854 * The cache is implemented as a bit array, with one bit per
5855 * string byte position per WHILEM op (up to 16) - so its
5856 * between 0.25 and 2x the string size.
5857 *
5858 * To avoid allocating a poscache buffer every time, we do an
5859 * initially countdown; only after we have executed a WHILEM
5860 * op (string-length x #WHILEMs) times do we allocate the
5861 * cache.
5862 *
5863 * The top 4 bits of scan->flags byte say how many different
5864 * relevant CURLLYX/WHILEM op pairs there are, while the
5865 * bottom 4-bits is the identifying index number of this
5866 * WHILEM.
5867 */
c476f425
DM
5868
5869 if (scan->flags) {
a0d0e21e 5870
1cb48e53 5871 if (!reginfo->poscache_maxiter) {
c476f425
DM
5872 /* start the countdown: Postpone detection until we
5873 * know the match is not *that* much linear. */
1cb48e53 5874 reginfo->poscache_maxiter
9d9163fb
DM
5875 = (reginfo->strend - reginfo->strbeg + 1)
5876 * (scan->flags>>4);
66bf836d 5877 /* possible overflow for long strings and many CURLYX's */
1cb48e53
DM
5878 if (reginfo->poscache_maxiter < 0)
5879 reginfo->poscache_maxiter = I32_MAX;
5880 reginfo->poscache_iter = reginfo->poscache_maxiter;
2c2d71f5 5881 }
c476f425 5882
1cb48e53 5883 if (reginfo->poscache_iter-- == 0) {
c476f425 5884 /* initialise cache */
ea3daa5d 5885 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
2ac8ff4b
DM
5886 regmatch_info_aux *const aux = reginfo->info_aux;
5887 if (aux->poscache) {
ea3daa5d 5888 if ((SSize_t)reginfo->poscache_size < size) {
2ac8ff4b
DM
5889 Renew(aux->poscache, size, char);
5890 reginfo->poscache_size = size;
2c2d71f5 5891 }
2ac8ff4b 5892 Zero(aux->poscache, size, char);
2c2d71f5
JH
5893 }
5894 else {
2ac8ff4b
DM
5895 reginfo->poscache_size = size;
5896 Newxz(aux->poscache, size, char);
2c2d71f5 5897 }
c476f425
DM
5898 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5899 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
5900 PL_colors[4], PL_colors[5])
5901 );
2c2d71f5 5902 }
c476f425 5903
1cb48e53 5904 if (reginfo->poscache_iter < 0) {
c476f425 5905 /* have we already failed at this position? */
ea3daa5d 5906 SSize_t offset, mask;
338e600a
DM
5907
5908 reginfo->poscache_iter = -1; /* stop eventual underflow */
c476f425 5909 offset = (scan->flags & 0xf) - 1
9d9163fb
DM
5910 + (locinput - reginfo->strbeg)
5911 * (scan->flags>>4);
c476f425
DM
5912 mask = 1 << (offset % 8);
5913 offset /= 8;
2ac8ff4b 5914 if (reginfo->info_aux->poscache[offset] & mask) {
c476f425
DM
5915 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
5916 "%*s whilem: (cache) already tried at this position...\n",
5917 REPORT_CODE_OFF+depth*2, "")
2c2d71f5 5918 );
3298f257 5919 sayNO; /* cache records failure */
2c2d71f5 5920 }
c476f425
DM
5921 ST.cache_offset = offset;
5922 ST.cache_mask = mask;
2c2d71f5 5923 }
c476f425 5924 }
2c2d71f5 5925
c476f425 5926 /* Prefer B over A for minimal matching. */
a687059c 5927
c476f425
DM
5928 if (cur_curlyx->u.curlyx.minmod) {
5929 ST.save_curlyx = cur_curlyx;
5930 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
92da3157
DM
5931 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
5932 maxopenparen);
c476f425 5933 REGCP_SET(ST.lastcp);
4d5016e5
DM
5934 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
5935 locinput);
a74ff37d 5936 /* NOTREACHED */
e5964223 5937 NOT_REACHED;
c476f425 5938 }
a0d0e21e 5939
c476f425
DM
5940 /* Prefer A over B for maximal matching. */
5941
d02d6d97 5942 if (n < max) { /* More greed allowed? */
92da3157
DM
5943 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
5944 maxopenparen);
c476f425
DM
5945 cur_curlyx->u.curlyx.lastloc = locinput;
5946 REGCP_SET(ST.lastcp);
4d5016e5 5947 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
a74ff37d 5948 /* NOTREACHED */
e5964223 5949 NOT_REACHED;
c476f425
DM
5950 }
5951 goto do_whilem_B_max;
5952 }
a74ff37d 5953 /* NOTREACHED */
e5964223 5954 NOT_REACHED;
c476f425
DM
5955
5956 case WHILEM_B_min: /* just matched B in a minimal match */
5957 case WHILEM_B_max: /* just matched B in a maximal match */
5958 cur_curlyx = ST.save_curlyx;
5959 sayYES;
a74ff37d 5960 /* NOTREACHED */
e5964223 5961 NOT_REACHED;
c476f425
DM
5962
5963 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
5964 cur_curlyx = ST.save_curlyx;
5965 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5966 cur_curlyx->u.curlyx.count--;
5967 CACHEsayNO;
a74ff37d 5968 /* NOTREACHED */
e5964223 5969 NOT_REACHED;
c476f425
DM
5970
5971 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
924ba076 5972 /* FALLTHROUGH */
c476f425 5973 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
92e82afa 5974 REGCP_UNWIND(ST.lastcp);
92da3157 5975 regcppop(rex, &maxopenparen);
c476f425
DM
5976 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5977 cur_curlyx->u.curlyx.count--;
5978 CACHEsayNO;
a74ff37d 5979 /* NOTREACHED */
e5964223 5980 NOT_REACHED;
c476f425
DM
5981
5982 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5983 REGCP_UNWIND(ST.lastcp);
92da3157 5984 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
c476f425
DM
5985 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5986 "%*s whilem: failed, trying continuation...\n",
5987 REPORT_CODE_OFF+depth*2, "")
5988 );
5989 do_whilem_B_max:
5990 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5991 && ckWARN(WARN_REGEXP)
39819bd9 5992 && !reginfo->warned)
c476f425 5993 {
39819bd9 5994 reginfo->warned = TRUE;
dcbac5bb
FC
5995 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5996 "Complex regular subexpression recursion limit (%d) "
5997 "exceeded",
c476f425
DM
5998 REG_INFTY - 1);
5999 }
6000
6001 /* now try B */
6002 ST.save_curlyx = cur_curlyx;
6003 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4d5016e5
DM
6004 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
6005 locinput);
a74ff37d 6006 /* NOTREACHED */
e5964223 6007 NOT_REACHED;
c476f425
DM
6008
6009 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
6010 cur_curlyx = ST.save_curlyx;
6011 REGCP_UNWIND(ST.lastcp);
92da3157 6012 regcppop(rex, &maxopenparen);
c476f425 6013
d02d6d97 6014 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
c476f425
DM
6015 /* Maximum greed exceeded */
6016 if (cur_curlyx->u.curlyx.count >= REG_INFTY
6017 && ckWARN(WARN_REGEXP)
39819bd9 6018 && !reginfo->warned)
c476f425 6019 {
39819bd9 6020 reginfo->warned = TRUE;
c476f425 6021 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
dcbac5bb
FC
6022 "Complex regular subexpression recursion "
6023 "limit (%d) exceeded",
c476f425 6024 REG_INFTY - 1);
a0d0e21e 6025 }
c476f425 6026 cur_curlyx->u.curlyx.count--;
3ab3c9b4 6027 CACHEsayNO;
a0d0e21e 6028 }
c476f425
DM
6029
6030 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
6031 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
6032 );
6033 /* Try grabbing another A and see if it helps. */
c476f425 6034 cur_curlyx->u.curlyx.lastloc = locinput;
92da3157
DM
6035 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
6036 maxopenparen);
c476f425 6037 REGCP_SET(ST.lastcp);
d02d6d97 6038 PUSH_STATE_GOTO(WHILEM_A_min,
4d5016e5
DM
6039 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
6040 locinput);
a74ff37d 6041 /* NOTREACHED */
e5964223 6042 NOT_REACHED;
40a82448
DM
6043
6044#undef ST
6045#define ST st->u.branch
6046
6047 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
c277df42
IZ
6048 next = scan + ARG(scan);
6049 if (next == scan)
6050 next = NULL;
40a82448 6051 scan = NEXTOPER(scan);
924ba076 6052 /* FALLTHROUGH */
c277df42 6053
40a82448
DM
6054 case BRANCH: /* /(...|A|...)/ */
6055 scan = NEXTOPER(scan); /* scan now points to inner node */
b93070ed 6056 ST.lastparen = rex->lastparen;
f6033a9d 6057 ST.lastcloseparen = rex->lastcloseparen;
40a82448
DM
6058 ST.next_branch = next;
6059 REGCP_SET(ST.cp);
02db2b7b 6060
40a82448 6061 /* Now go into the branch */
5d458dd8 6062 if (has_cutgroup) {
4d5016e5 6063 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
5d458dd8 6064 } else {
4d5016e5 6065 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
5d458dd8 6066 }
a74ff37d 6067 /* NOTREACHED */
e5964223 6068 NOT_REACHED;
3c0563b9
DM
6069
6070 case CUTGROUP: /* /(*THEN)/ */
5d458dd8 6071 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
ad64d0ec 6072 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4d5016e5 6073 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
a74ff37d 6074 /* NOTREACHED */
e5964223 6075 NOT_REACHED;
3c0563b9 6076
5d458dd8
YO
6077 case CUTGROUP_next_fail:
6078 do_cutgroup = 1;
6079 no_final = 1;
6080 if (st->u.mark.mark_name)
6081 sv_commit = st->u.mark.mark_name;
6082 sayNO;
a74ff37d 6083 /* NOTREACHED */
e5964223 6084 NOT_REACHED;
3c0563b9 6085
5d458dd8
YO
6086 case BRANCH_next:
6087 sayYES;
a74ff37d 6088 /* NOTREACHED */
e5964223 6089 NOT_REACHED;
3c0563b9 6090
40a82448 6091 case BRANCH_next_fail: /* that branch failed; try the next, if any */
5d458dd8
YO
6092 if (do_cutgroup) {
6093 do_cutgroup = 0;
6094 no_final = 0;
6095 }
40a82448 6096 REGCP_UNWIND(ST.cp);
a8d1f4b4 6097 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
40a82448
DM
6098 scan = ST.next_branch;
6099 /* no more branches? */
5d458dd8
YO
6100 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
6101 DEBUG_EXECUTE_r({
6102 PerlIO_printf( Perl_debug_log,
6103 "%*s %sBRANCH failed...%s\n",
6104 REPORT_CODE_OFF+depth*2, "",
6105 PL_colors[4],
6106 PL_colors[5] );
6107 });
6108 sayNO_SILENT;
6109 }
40a82448 6110 continue; /* execute next BRANCH[J] op */
a74ff37d 6111 /* NOTREACHED */
40a82448 6112
3c0563b9 6113 case MINMOD: /* next op will be non-greedy, e.g. A*? */
24d3c4a9 6114 minmod = 1;
a0d0e21e 6115 break;
40a82448
DM
6116
6117#undef ST
6118#define ST st->u.curlym
6119
6120 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
6121
6122 /* This is an optimisation of CURLYX that enables us to push
84d2fa14 6123 * only a single backtracking state, no matter how many matches
40a82448
DM
6124 * there are in {m,n}. It relies on the pattern being constant
6125 * length, with no parens to influence future backrefs
6126 */
6127
6128 ST.me = scan;
dc45a647 6129 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
40a82448 6130
f6033a9d
DM
6131 ST.lastparen = rex->lastparen;
6132 ST.lastcloseparen = rex->lastcloseparen;
6133
40a82448
DM
6134 /* if paren positive, emulate an OPEN/CLOSE around A */
6135 if (ST.me->flags) {
3b6647e0 6136 U32 paren = ST.me->flags;
92da3157
DM
6137 if (paren > maxopenparen)
6138 maxopenparen = paren;
c277df42 6139 scan += NEXT_OFF(scan); /* Skip former OPEN. */
6407bf3b 6140 }
40a82448
DM
6141 ST.A = scan;
6142 ST.B = next;
6143 ST.alen = 0;
6144 ST.count = 0;
24d3c4a9
DM
6145 ST.minmod = minmod;
6146 minmod = 0;
40a82448
DM
6147 ST.c1 = CHRTEST_UNINIT;
6148 REGCP_SET(ST.cp);
6407bf3b 6149
40a82448
DM
6150 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
6151 goto curlym_do_B;
6152
6153 curlym_do_A: /* execute the A in /A{m,n}B/ */
4d5016e5 6154 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
a74ff37d 6155 /* NOTREACHED */
e5964223 6156 NOT_REACHED;
5f80c4cf 6157
40a82448 6158 case CURLYM_A: /* we've just matched an A */
40a82448
DM
6159 ST.count++;
6160 /* after first match, determine A's length: u.curlym.alen */
6161 if (ST.count == 1) {
ba44c216 6162 if (reginfo->is_utf8_target) {
c07e9d7b
DM
6163 char *s = st->locinput;
6164 while (s < locinput) {
40a82448
DM
6165 ST.alen++;
6166 s += UTF8SKIP(s);
6167 }
6168 }
6169 else {
c07e9d7b 6170 ST.alen = locinput - st->locinput;
40a82448
DM
6171 }
6172 if (ST.alen == 0)
6173 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
6174 }
0cadcf80
DM
6175 DEBUG_EXECUTE_r(
6176 PerlIO_printf(Perl_debug_log,
40a82448 6177 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
5bc10b2c 6178 (int)(REPORT_CODE_OFF+(depth*2)), "",
40a82448 6179 (IV) ST.count, (IV)ST.alen)
0cadcf80
DM
6180 );
6181
0a4db386 6182 if (cur_eval && cur_eval->u.eval.close_paren &&
24b23f37 6183 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
0a4db386
YO
6184 goto fake_end;
6185
c966426a
DM
6186 {
6187 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
6188 if ( max == REG_INFTY || ST.count < max )
6189 goto curlym_do_A; /* try to match another A */
6190 }
40a82448 6191 goto curlym_do_B; /* try to match B */
5f80c4cf 6192
40a82448
DM
6193 case CURLYM_A_fail: /* just failed to match an A */
6194 REGCP_UNWIND(ST.cp);
0a4db386
YO
6195
6196 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
6197 || (cur_eval && cur_eval->u.eval.close_paren &&
24b23f37 6198 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
40a82448 6199 sayNO;
0cadcf80 6200
40a82448 6201 curlym_do_B: /* execute the B in /A{m,n}B/ */
40a82448
DM
6202 if (ST.c1 == CHRTEST_UNINIT) {
6203 /* calculate c1 and c2 for possible match of 1st char
6204 * following curly */
6205 ST.c1 = ST.c2 = CHRTEST_VOID;
d20a21f4 6206 assert(ST.B);
40a82448
DM
6207 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
6208 regnode *text_node = ST.B;
6209 if (! HAS_TEXT(text_node))
6210 FIND_NEXT_IMPT(text_node);
ee9b8eae
YO
6211 /* this used to be
6212
6213 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
6214
6215 But the former is redundant in light of the latter.
6216
6217 if this changes back then the macro for
6218 IS_TEXT and friends need to change.
6219 */
c74f6de9 6220 if (PL_regkind[OP(text_node)] == EXACT) {
79a2a0e8 6221 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
984e6dd1 6222 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
aed7b151 6223 reginfo))
c74f6de9
KW
6224 {
6225 sayNO;
6226 }
c277df42 6227 }
c277df42 6228 }
40a82448
DM
6229 }
6230
6231 DEBUG_EXECUTE_r(
6232 PerlIO_printf(Perl_debug_log,
6233 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
5bc10b2c 6234 (int)(REPORT_CODE_OFF+(depth*2)),
40a82448
DM
6235 "", (IV)ST.count)
6236 );
c74f6de9 6237 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
79a2a0e8
KW
6238 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
6239 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6240 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6241 {
6242 /* simulate B failing */
6243 DEBUG_OPTIMISE_r(
6244 PerlIO_printf(Perl_debug_log,
33daa3a5 6245 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
79a2a0e8
KW
6246 (int)(REPORT_CODE_OFF+(depth*2)),"",
6247 valid_utf8_to_uvchr((U8 *) locinput, NULL),
6248 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
6249 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
6250 );
6251 state_num = CURLYM_B_fail;
6252 goto reenter_switch;
6253 }
6254 }
6255 else if (nextchr != ST.c1 && nextchr != ST.c2) {
5400f398
KW
6256 /* simulate B failing */
6257 DEBUG_OPTIMISE_r(
6258 PerlIO_printf(Perl_debug_log,
33daa3a5 6259 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
5400f398 6260 (int)(REPORT_CODE_OFF+(depth*2)),"",
79a2a0e8
KW
6261 (int) nextchr, ST.c1, ST.c2)
6262 );
5400f398
KW
6263 state_num = CURLYM_B_fail;
6264 goto reenter_switch;
6265 }
c74f6de9 6266 }
40a82448
DM
6267
6268 if (ST.me->flags) {
f6033a9d 6269 /* emulate CLOSE: mark current A as captured */
40a82448
DM
6270 I32 paren = ST.me->flags;
6271 if (ST.count) {
b93070ed 6272 rex->offs[paren].start
9d9163fb
DM
6273 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
6274 rex->offs[paren].end = locinput - reginfo->strbeg;
f6033a9d
DM
6275 if ((U32)paren > rex->lastparen)
6276 rex->lastparen = paren;
6277 rex->lastcloseparen = paren;
c277df42 6278 }
40a82448 6279 else
b93070ed 6280 rex->offs[paren].end = -1;
0a4db386 6281 if (cur_eval && cur_eval->u.eval.close_paren &&
24b23f37 6282 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
0a4db386
YO
6283 {
6284 if (ST.count)
6285 goto fake_end;
6286 else
6287 sayNO;
6288 }
c277df42 6289 }
0a4db386 6290
4d5016e5 6291 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
a74ff37d 6292 /* NOTREACHED */
e5964223 6293 NOT_REACHED;
40a82448
DM
6294
6295 case CURLYM_B_fail: /* just failed to match a B */
6296 REGCP_UNWIND(ST.cp);
a8d1f4b4 6297 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
40a82448 6298 if (ST.minmod) {
84d2fa14
HS
6299 I32 max = ARG2(ST.me);
6300 if (max != REG_INFTY && ST.count == max)
40a82448
DM
6301 sayNO;
6302 goto curlym_do_A; /* try to match a further A */
6303 }
6304 /* backtrack one A */
6305 if (ST.count == ARG1(ST.me) /* min */)
6306 sayNO;
6307 ST.count--;
7016d6eb 6308 SET_locinput(HOPc(locinput, -ST.alen));
40a82448
DM
6309 goto curlym_do_B; /* try to match B */
6310
c255a977
DM
6311#undef ST
6312#define ST st->u.curly
40a82448 6313
c255a977
DM
6314#define CURLY_SETPAREN(paren, success) \
6315 if (paren) { \
6316 if (success) { \
9d9163fb
DM
6317 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
6318 rex->offs[paren].end = locinput - reginfo->strbeg; \
f6033a9d
DM
6319 if (paren > rex->lastparen) \
6320 rex->lastparen = paren; \
b93070ed 6321 rex->lastcloseparen = paren; \
c255a977 6322 } \
f6033a9d 6323 else { \
b93070ed 6324 rex->offs[paren].end = -1; \
f6033a9d
DM
6325 rex->lastparen = ST.lastparen; \
6326 rex->lastcloseparen = ST.lastcloseparen; \
6327 } \
c255a977
DM
6328 }
6329
b40a2c17 6330 case STAR: /* /A*B/ where A is width 1 char */
c255a977
DM
6331 ST.paren = 0;
6332 ST.min = 0;
6333 ST.max = REG_INFTY;
a0d0e21e
LW
6334 scan = NEXTOPER(scan);
6335 goto repeat;
3c0563b9 6336
b40a2c17 6337 case PLUS: /* /A+B/ where A is width 1 char */
c255a977
DM
6338 ST.paren = 0;
6339 ST.min = 1;
6340 ST.max = REG_INFTY;
c277df42 6341 scan = NEXTOPER(scan);
c255a977 6342 goto repeat;
3c0563b9 6343
b40a2c17 6344 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
5400f398
KW
6345 ST.paren = scan->flags; /* Which paren to set */
6346 ST.lastparen = rex->lastparen;
f6033a9d 6347 ST.lastcloseparen = rex->lastcloseparen;
92da3157
DM
6348 if (ST.paren > maxopenparen)
6349 maxopenparen = ST.paren;
c255a977
DM
6350 ST.min = ARG1(scan); /* min to match */
6351 ST.max = ARG2(scan); /* max to match */
0a4db386 6352 if (cur_eval && cur_eval->u.eval.close_paren &&
86413ec0 6353 cur_eval->u.eval.close_paren == (U32)ST.paren) {
0a4db386
YO
6354 ST.min=1;
6355 ST.max=1;
6356 }
c255a977
DM
6357 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
6358 goto repeat;
3c0563b9 6359
b40a2c17 6360 case CURLY: /* /A{m,n}B/ where A is width 1 char */
c255a977
DM
6361 ST.paren = 0;
6362 ST.min = ARG1(scan); /* min to match */
6363 ST.max = ARG2(scan); /* max to match */
6364 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
c277df42 6365 repeat:
a0d0e21e
LW
6366 /*
6367 * Lookahead to avoid useless match attempts
6368 * when we know what character comes next.
c255a977 6369 *
5f80c4cf
JP
6370 * Used to only do .*x and .*?x, but now it allows
6371 * for )'s, ('s and (?{ ... })'s to be in the way
6372 * of the quantifier and the EXACT-like node. -- japhy
6373 */
6374
eb5c1be8 6375 assert(ST.min <= ST.max);
3337dfe3
KW
6376 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
6377 ST.c1 = ST.c2 = CHRTEST_VOID;
6378 }
6379 else {
5f80c4cf
JP
6380 regnode *text_node = next;
6381
3dab1dad
YO
6382 if (! HAS_TEXT(text_node))
6383 FIND_NEXT_IMPT(text_node);
5f80c4cf 6384
9e137952 6385 if (! HAS_TEXT(text_node))
c255a977 6386 ST.c1 = ST.c2 = CHRTEST_VOID;
5f80c4cf 6387 else {
ee9b8eae 6388 if ( PL_regkind[OP(text_node)] != EXACT ) {
c255a977 6389 ST.c1 = ST.c2 = CHRTEST_VOID;
cca55fe3 6390 }
c74f6de9 6391 else {
ee9b8eae
YO
6392
6393 /* Currently we only get here when
6394
6395 PL_rekind[OP(text_node)] == EXACT
6396
6397 if this changes back then the macro for IS_TEXT and
6398 friends need to change. */
79a2a0e8 6399 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
984e6dd1 6400 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
aed7b151 6401 reginfo))
c74f6de9
KW
6402 {
6403 sayNO;
6404 }
6405 }
1aa99e6b 6406 }
bbce6d69 6407 }
c255a977
DM
6408
6409 ST.A = scan;
6410 ST.B = next;
24d3c4a9 6411 if (minmod) {
eb72505d 6412 char *li = locinput;
24d3c4a9 6413 minmod = 0;
984e6dd1 6414 if (ST.min &&
f9176b44 6415 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
984e6dd1 6416 < ST.min)
4633a7c4 6417 sayNO;
7016d6eb 6418 SET_locinput(li);
c255a977 6419 ST.count = ST.min;
c255a977
DM
6420 REGCP_SET(ST.cp);
6421 if (ST.c1 == CHRTEST_VOID)
6422 goto curly_try_B_min;
6423
6424 ST.oldloc = locinput;
6425
6426 /* set ST.maxpos to the furthest point along the
6427 * string that could possibly match */
6428 if (ST.max == REG_INFTY) {
220db18a 6429 ST.maxpos = reginfo->strend - 1;
f2ed9b32 6430 if (utf8_target)
c255a977
DM
6431 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
6432 ST.maxpos--;
6433 }
f2ed9b32 6434 else if (utf8_target) {
c255a977
DM
6435 int m = ST.max - ST.min;
6436 for (ST.maxpos = locinput;
220db18a 6437 m >0 && ST.maxpos < reginfo->strend; m--)
c255a977
DM
6438 ST.maxpos += UTF8SKIP(ST.maxpos);
6439 }
6440 else {
6441 ST.maxpos = locinput + ST.max - ST.min;
220db18a
DM
6442 if (ST.maxpos >= reginfo->strend)
6443 ST.maxpos = reginfo->strend - 1;
c255a977
DM
6444 }
6445 goto curly_try_B_min_known;
6446
6447 }
6448 else {
eb72505d
DM
6449 /* avoid taking address of locinput, so it can remain
6450 * a register var */
6451 char *li = locinput;
f9176b44 6452 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
c255a977
DM
6453 if (ST.count < ST.min)
6454 sayNO;
7016d6eb 6455 SET_locinput(li);
c255a977
DM
6456 if ((ST.count > ST.min)
6457 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
6458 {
6459 /* A{m,n} must come at the end of the string, there's
6460 * no point in backing off ... */
6461 ST.min = ST.count;
6462 /* ...except that $ and \Z can match before *and* after
6463 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
6464 We may back off by one in this case. */
eb72505d 6465 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
c255a977
DM
6466 ST.min--;
6467 }
6468 REGCP_SET(ST.cp);
6469 goto curly_try_B_max;
6470 }
a74ff37d 6471 /* NOTREACHED */
e5964223 6472 NOT_REACHED;
c255a977
DM
6473
6474 case CURLY_B_min_known_fail:
6475 /* failed to find B in a non-greedy match where c1,c2 valid */
c255a977 6476
c255a977 6477 REGCP_UNWIND(ST.cp);
a8d1f4b4
DM
6478 if (ST.paren) {
6479 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6480 }
c255a977
DM
6481 /* Couldn't or didn't -- move forward. */
6482 ST.oldloc = locinput;
f2ed9b32 6483 if (utf8_target)
c255a977
DM
6484 locinput += UTF8SKIP(locinput);
6485 else
6486 locinput++;
6487 ST.count++;
6488 curly_try_B_min_known:
6489 /* find the next place where 'B' could work, then call B */
6490 {
6491 int n;
f2ed9b32 6492 if (utf8_target) {
c255a977
DM
6493 n = (ST.oldloc == locinput) ? 0 : 1;
6494 if (ST.c1 == ST.c2) {
c255a977 6495 /* set n to utf8_distance(oldloc, locinput) */
79a2a0e8
KW
6496 while (locinput <= ST.maxpos
6497 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
6498 {
6499 locinput += UTF8SKIP(locinput);
c255a977
DM
6500 n++;
6501 }
1aa99e6b
IH
6502 }
6503 else {
c255a977 6504 /* set n to utf8_distance(oldloc, locinput) */
79a2a0e8
KW
6505 while (locinput <= ST.maxpos
6506 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
6507 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
6508 {
6509 locinput += UTF8SKIP(locinput);
c255a977 6510 n++;
1aa99e6b 6511 }
0fe9bf95
IZ
6512 }
6513 }
5400f398 6514 else { /* Not utf8_target */
c255a977
DM
6515 if (ST.c1 == ST.c2) {
6516 while (locinput <= ST.maxpos &&
6517 UCHARAT(locinput) != ST.c1)
6518 locinput++;
bbce6d69 6519 }
c255a977
DM
6520 else {
6521 while (locinput <= ST.maxpos
6522 && UCHARAT(locinput) != ST.c1
6523 && UCHARAT(locinput) != ST.c2)
6524 locinput++;
a0ed51b3 6525 }
c255a977
DM
6526 n = locinput - ST.oldloc;
6527 }
6528 if (locinput > ST.maxpos)
6529 sayNO;
c255a977 6530 if (n) {
eb72505d
DM
6531 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
6532 * at b; check that everything between oldloc and
6533 * locinput matches */
6534 char *li = ST.oldloc;
c255a977 6535 ST.count += n;
f9176b44 6536 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
4633a7c4 6537 sayNO;
eb72505d 6538 assert(n == REG_INFTY || locinput == li);
a0d0e21e 6539 }
c255a977 6540 CURLY_SETPAREN(ST.paren, ST.count);
0a4db386 6541 if (cur_eval && cur_eval->u.eval.close_paren &&
86413ec0 6542 cur_eval->u.eval.close_paren == (U32)ST.paren) {
0a4db386
YO
6543 goto fake_end;
6544 }
4d5016e5 6545 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
a0d0e21e 6546 }
a74ff37d 6547 /* NOTREACHED */
e5964223 6548 NOT_REACHED;
c255a977
DM
6549
6550 case CURLY_B_min_fail:
6551 /* failed to find B in a non-greedy match where c1,c2 invalid */
c255a977
DM
6552
6553 REGCP_UNWIND(ST.cp);
a8d1f4b4
DM
6554 if (ST.paren) {
6555 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6556 }
c255a977 6557 /* failed -- move forward one */
f73aaa43 6558 {
eb72505d 6559 char *li = locinput;
f9176b44 6560 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
f73aaa43
DM
6561 sayNO;
6562 }
eb72505d 6563 locinput = li;
f73aaa43
DM
6564 }
6565 {
c255a977 6566 ST.count++;
c255a977
DM
6567 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
6568 ST.count > 0)) /* count overflow ? */
15272685 6569 {
c255a977
DM
6570 curly_try_B_min:
6571 CURLY_SETPAREN(ST.paren, ST.count);
0a4db386 6572 if (cur_eval && cur_eval->u.eval.close_paren &&
86413ec0 6573 cur_eval->u.eval.close_paren == (U32)ST.paren) {
0a4db386
YO
6574 goto fake_end;
6575 }
4d5016e5 6576 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
a0d0e21e
LW
6577 }
6578 }
c74f6de9 6579 sayNO;
a74ff37d 6580 /* NOTREACHED */
e5964223 6581 NOT_REACHED;
c255a977
DM
6582
6583 curly_try_B_max:
6584 /* a successful greedy match: now try to match B */
40d049e4 6585 if (cur_eval && cur_eval->u.eval.close_paren &&
86413ec0 6586 cur_eval->u.eval.close_paren == (U32)ST.paren) {
40d049e4
YO
6587 goto fake_end;
6588 }
c255a977 6589 {
220db18a 6590 bool could_match = locinput < reginfo->strend;
79a2a0e8 6591
c255a977 6592 /* If it could work, try it. */
79a2a0e8
KW
6593 if (ST.c1 != CHRTEST_VOID && could_match) {
6594 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
6595 {
6596 could_match = memEQ(locinput,
6597 ST.c1_utf8,
6598 UTF8SKIP(locinput))
6599 || memEQ(locinput,
6600 ST.c2_utf8,
6601 UTF8SKIP(locinput));
6602 }
6603 else {
6604 could_match = UCHARAT(locinput) == ST.c1
6605 || UCHARAT(locinput) == ST.c2;
6606 }
6607 }
6608 if (ST.c1 == CHRTEST_VOID || could_match) {
c255a977 6609 CURLY_SETPAREN(ST.paren, ST.count);
4d5016e5 6610 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
a74ff37d 6611 /* NOTREACHED */
e5964223 6612 NOT_REACHED;
c255a977
DM
6613 }
6614 }
924ba076 6615 /* FALLTHROUGH */
3c0563b9 6616
c255a977
DM
6617 case CURLY_B_max_fail:
6618 /* failed to find B in a greedy match */
c255a977
DM
6619
6620 REGCP_UNWIND(ST.cp);
a8d1f4b4
DM
6621 if (ST.paren) {
6622 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6623 }
c255a977
DM
6624 /* back up. */
6625 if (--ST.count < ST.min)
6626 sayNO;
eb72505d 6627 locinput = HOPc(locinput, -1);
c255a977
DM
6628 goto curly_try_B_max;
6629
6630#undef ST
6631
3c0563b9 6632 case END: /* last op of main pattern */
6bda09f9 6633 fake_end:
faec1544
DM
6634 if (cur_eval) {
6635 /* we've just finished A in /(??{A})B/; now continue with B */
faec1544 6636
288b8c02 6637 st->u.eval.prev_rex = rex_sv; /* inner */
92da3157
DM
6638
6639 /* Save *all* the positions. */
6640 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
ec43f78b 6641 rex_sv = cur_eval->u.eval.prev_rex;
aed7b151 6642 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
ec43f78b 6643 SET_reg_curpm(rex_sv);
8d919b0a 6644 rex = ReANY(rex_sv);
f8fc2ecf 6645 rexi = RXi_GET(rex);
faec1544 6646 cur_curlyx = cur_eval->u.eval.prev_curlyx;
34a81e2b 6647
faec1544 6648 REGCP_SET(st->u.eval.lastcp);
faec1544
DM
6649
6650 /* Restore parens of the outer rex without popping the
6651 * savestack */
92da3157
DM
6652 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
6653 &maxopenparen);
faec1544
DM
6654
6655 st->u.eval.prev_eval = cur_eval;
6656 cur_eval = cur_eval->u.eval.prev_eval;
6657 DEBUG_EXECUTE_r(
2a49f0f5
JH
6658 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
6659 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
e7707071
YO
6660 if ( nochange_depth )
6661 nochange_depth--;
6662
4d5016e5
DM
6663 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
6664 locinput); /* match B */
faec1544
DM
6665 }
6666
3b0527fe 6667 if (locinput < reginfo->till) {
a3621e74 6668 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7821416a
IZ
6669 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
6670 PL_colors[4],
6d59b646
DM
6671 (long)(locinput - startpos),
6672 (long)(reginfo->till - startpos),
7821416a 6673 PL_colors[5]));
58e23c8d 6674
262b90c4 6675 sayNO_SILENT; /* Cannot match: too short. */
7821416a 6676 }
262b90c4 6677 sayYES; /* Success! */
dad79028
DM
6678
6679 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
6680 DEBUG_EXECUTE_r(
6681 PerlIO_printf(Perl_debug_log,
6682 "%*s %ssubpattern success...%s\n",
5bc10b2c 6683 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
262b90c4 6684 sayYES; /* Success! */
dad79028 6685
40a82448
DM
6686#undef ST
6687#define ST st->u.ifmatch
6688
37f53970
DM
6689 {
6690 char *newstart;
6691
40a82448
DM
6692 case SUSPEND: /* (?>A) */
6693 ST.wanted = 1;
37f53970 6694 newstart = locinput;
9041c2e3 6695 goto do_ifmatch;
dad79028 6696
40a82448
DM
6697 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
6698 ST.wanted = 0;
dad79028
DM
6699 goto ifmatch_trivial_fail_test;
6700
40a82448
DM
6701 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
6702 ST.wanted = 1;
dad79028 6703 ifmatch_trivial_fail_test:
a0ed51b3 6704 if (scan->flags) {
52657f30 6705 char * const s = HOPBACKc(locinput, scan->flags);
dad79028
DM
6706 if (!s) {
6707 /* trivial fail */
24d3c4a9
DM
6708 if (logical) {
6709 logical = 0;
f2338a2e 6710 sw = 1 - cBOOL(ST.wanted);
dad79028 6711 }
40a82448 6712 else if (ST.wanted)
dad79028
DM
6713 sayNO;
6714 next = scan + ARG(scan);
6715 if (next == scan)
6716 next = NULL;
6717 break;
6718 }
37f53970 6719 newstart = s;
a0ed51b3
LW
6720 }
6721 else
37f53970 6722 newstart = locinput;
a0ed51b3 6723
c277df42 6724 do_ifmatch:
40a82448 6725 ST.me = scan;
24d3c4a9 6726 ST.logical = logical;
24d786f4
YO
6727 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
6728
40a82448 6729 /* execute body of (?...A) */
37f53970 6730 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
a74ff37d 6731 /* NOTREACHED */
e5964223 6732 NOT_REACHED;
37f53970 6733 }
40a82448
DM
6734
6735 case IFMATCH_A_fail: /* body of (?...A) failed */
6736 ST.wanted = !ST.wanted;
924ba076 6737 /* FALLTHROUGH */
40a82448
DM
6738
6739 case IFMATCH_A: /* body of (?...A) succeeded */
24d3c4a9 6740 if (ST.logical) {
f2338a2e 6741 sw = cBOOL(ST.wanted);
40a82448
DM
6742 }
6743 else if (!ST.wanted)
6744 sayNO;
6745
37f53970
DM
6746 if (OP(ST.me) != SUSPEND) {
6747 /* restore old position except for (?>...) */
6748 locinput = st->locinput;
40a82448
DM
6749 }
6750 scan = ST.me + ARG(ST.me);
6751 if (scan == ST.me)
6752 scan = NULL;
6753 continue; /* execute B */
6754
6755#undef ST
dad79028 6756
3c0563b9
DM
6757 case LONGJMP: /* alternative with many branches compiles to
6758 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
c277df42
IZ
6759 next = scan + ARG(scan);
6760 if (next == scan)
6761 next = NULL;
a0d0e21e 6762 break;
3c0563b9
DM
6763
6764 case COMMIT: /* (*COMMIT) */
220db18a 6765 reginfo->cutpoint = reginfo->strend;
e2e6a0f1 6766 /* FALLTHROUGH */
3c0563b9
DM
6767
6768 case PRUNE: /* (*PRUNE) */
e2e6a0f1 6769 if (!scan->flags)
ad64d0ec 6770 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4d5016e5 6771 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
a74ff37d 6772 /* NOTREACHED */
e5964223 6773 NOT_REACHED;
3c0563b9 6774
54612592
YO
6775 case COMMIT_next_fail:
6776 no_final = 1;
6777 /* FALLTHROUGH */
3c0563b9
DM
6778
6779 case OPFAIL: /* (*FAIL) */
7f69552c 6780 sayNO;
a74ff37d 6781 /* NOTREACHED */
e5964223 6782 NOT_REACHED;
e2e6a0f1
YO
6783
6784#define ST st->u.mark
3c0563b9 6785 case MARKPOINT: /* (*MARK:foo) */
e2e6a0f1 6786 ST.prev_mark = mark_state;
5d458dd8 6787 ST.mark_name = sv_commit = sv_yes_mark
ad64d0ec 6788 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
e2e6a0f1 6789 mark_state = st;
4d5016e5
DM
6790 ST.mark_loc = locinput;
6791 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
a74ff37d 6792 /* NOTREACHED */
e5964223 6793 NOT_REACHED;
3c0563b9 6794
e2e6a0f1
YO
6795 case MARKPOINT_next:
6796 mark_state = ST.prev_mark;
6797 sayYES;
a74ff37d 6798 /* NOTREACHED */
e5964223 6799 NOT_REACHED;
3c0563b9 6800
e2e6a0f1 6801 case MARKPOINT_next_fail:
5d458dd8 6802 if (popmark && sv_eq(ST.mark_name,popmark))
e2e6a0f1
YO
6803 {
6804 if (ST.mark_loc > startpoint)
6805 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
6806 popmark = NULL; /* we found our mark */
6807 sv_commit = ST.mark_name;
6808
6809 DEBUG_EXECUTE_r({
5d458dd8 6810 PerlIO_printf(Perl_debug_log,
e2e6a0f1
YO
6811 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
6812 REPORT_CODE_OFF+depth*2, "",
be2597df 6813 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
e2e6a0f1
YO
6814 });
6815 }
6816 mark_state = ST.prev_mark;
5d458dd8
YO
6817 sv_yes_mark = mark_state ?
6818 mark_state->u.mark.mark_name : NULL;
e2e6a0f1 6819 sayNO;
a74ff37d 6820 /* NOTREACHED */
e5964223 6821 NOT_REACHED;
3c0563b9
DM
6822
6823 case SKIP: /* (*SKIP) */
5d458dd8 6824 if (scan->flags) {
2bf803e2 6825 /* (*SKIP) : if we fail we cut here*/
5d458dd8 6826 ST.mark_name = NULL;
e2e6a0f1 6827 ST.mark_loc = locinput;
4d5016e5 6828 PUSH_STATE_GOTO(SKIP_next,next, locinput);
5d458dd8 6829 } else {
2bf803e2 6830 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5d458dd8
YO
6831 otherwise do nothing. Meaning we need to scan
6832 */
6833 regmatch_state *cur = mark_state;
ad64d0ec 6834 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5d458dd8
YO
6835
6836 while (cur) {
6837 if ( sv_eq( cur->u.mark.mark_name,
6838 find ) )
6839 {
6840 ST.mark_name = find;
4d5016e5 6841 PUSH_STATE_GOTO( SKIP_next, next, locinput);
5d458dd8
YO
6842 }
6843 cur = cur->u.mark.prev_mark;
6844 }
e2e6a0f1 6845 }
2bf803e2 6846 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5d458dd8 6847 break;
3c0563b9 6848
5d458dd8
YO
6849 case SKIP_next_fail:
6850 if (ST.mark_name) {
6851 /* (*CUT:NAME) - Set up to search for the name as we
6852 collapse the stack*/
6853 popmark = ST.mark_name;
6854 } else {
6855 /* (*CUT) - No name, we cut here.*/
e2e6a0f1
YO
6856 if (ST.mark_loc > startpoint)
6857 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5d458dd8
YO
6858 /* but we set sv_commit to latest mark_name if there
6859 is one so they can test to see how things lead to this
6860 cut */
6861 if (mark_state)
6862 sv_commit=mark_state->u.mark.mark_name;
6863 }
e2e6a0f1
YO
6864 no_final = 1;
6865 sayNO;
a74ff37d 6866 /* NOTREACHED */
e5964223 6867 NOT_REACHED;
e2e6a0f1 6868#undef ST
3c0563b9
DM
6869
6870 case LNBREAK: /* \R */
220db18a 6871 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
e1d1eefb 6872 locinput += n;
e1d1eefb
YO
6873 } else
6874 sayNO;
6875 break;
6876
a0d0e21e 6877 default:
b900a521 6878 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
d7d93a81 6879 PTR2UV(scan), OP(scan));
cea2e8a9 6880 Perl_croak(aTHX_ "regexp memory corruption");
28b98f76
DM
6881
6882 /* this is a point to jump to in order to increment
6883 * locinput by one character */
6884 increment_locinput:
e6ca698c 6885 assert(!NEXTCHR_IS_EOS);
28b98f76
DM
6886 if (utf8_target) {
6887 locinput += PL_utf8skip[nextchr];
7016d6eb 6888 /* locinput is allowed to go 1 char off the end, but not 2+ */
220db18a 6889 if (locinput > reginfo->strend)
28b98f76 6890 sayNO;
28b98f76
DM
6891 }
6892 else
3640db6b 6893 locinput++;
28b98f76 6894 break;
5d458dd8
YO
6895
6896 } /* end switch */
95b24440 6897
5d458dd8
YO
6898 /* switch break jumps here */
6899 scan = next; /* prepare to execute the next op and ... */
6900 continue; /* ... jump back to the top, reusing st */
a74ff37d 6901 /* NOTREACHED */
95b24440 6902
40a82448
DM
6903 push_yes_state:
6904 /* push a state that backtracks on success */
6905 st->u.yes.prev_yes_state = yes_state;
6906 yes_state = st;
924ba076 6907 /* FALLTHROUGH */
40a82448
DM
6908 push_state:
6909 /* push a new regex state, then continue at scan */
6910 {
6911 regmatch_state *newst;
6912
24b23f37
YO
6913 DEBUG_STACK_r({
6914 regmatch_state *cur = st;
6915 regmatch_state *curyes = yes_state;
6916 int curd = depth;
6917 regmatch_slab *slab = PL_regmatch_slab;
6918 for (;curd > -1;cur--,curd--) {
6919 if (cur < SLAB_FIRST(slab)) {
6920 slab = slab->prev;
6921 cur = SLAB_LAST(slab);
6922 }
6923 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
6924 REPORT_CODE_OFF + 2 + depth * 2,"",
13d6edb4 6925 curd, PL_reg_name[cur->resume_state],
24b23f37
YO
6926 (curyes == cur) ? "yes" : ""
6927 );
6928 if (curyes == cur)
6929 curyes = cur->u.yes.prev_yes_state;
6930 }
6931 } else
6932 DEBUG_STATE_pp("push")
6933 );
40a82448 6934 depth++;
40a82448
DM
6935 st->locinput = locinput;
6936 newst = st+1;
6937 if (newst > SLAB_LAST(PL_regmatch_slab))
6938 newst = S_push_slab(aTHX);
6939 PL_regmatch_state = newst;
786e8c11 6940
4d5016e5 6941 locinput = pushinput;
40a82448
DM
6942 st = newst;
6943 continue;
a74ff37d 6944 /* NOTREACHED */
40a82448 6945 }
a0d0e21e 6946 }
a687059c 6947
a0d0e21e
LW
6948 /*
6949 * We get here only if there's trouble -- normally "case END" is
6950 * the terminating point.
6951 */
cea2e8a9 6952 Perl_croak(aTHX_ "corrupted regexp pointers");
a74ff37d 6953 /* NOTREACHED */
4633a7c4 6954 sayNO;
e5964223 6955 NOT_REACHED;
4633a7c4 6956
262b90c4 6957yes:
77cb431f
DM
6958 if (yes_state) {
6959 /* we have successfully completed a subexpression, but we must now
6960 * pop to the state marked by yes_state and continue from there */
77cb431f 6961 assert(st != yes_state);
5bc10b2c
DM
6962#ifdef DEBUGGING
6963 while (st != yes_state) {
6964 st--;
6965 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6966 PL_regmatch_slab = PL_regmatch_slab->prev;
6967 st = SLAB_LAST(PL_regmatch_slab);
6968 }
e2e6a0f1 6969 DEBUG_STATE_r({
54612592
YO
6970 if (no_final) {
6971 DEBUG_STATE_pp("pop (no final)");
6972 } else {
6973 DEBUG_STATE_pp("pop (yes)");
6974 }
e2e6a0f1 6975 });
5bc10b2c
DM
6976 depth--;
6977 }
6978#else
77cb431f
DM
6979 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
6980 || yes_state > SLAB_LAST(PL_regmatch_slab))
6981 {
6982 /* not in this slab, pop slab */
6983 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
6984 PL_regmatch_slab = PL_regmatch_slab->prev;
6985 st = SLAB_LAST(PL_regmatch_slab);
6986 }
6987 depth -= (st - yes_state);
5bc10b2c 6988#endif
77cb431f
DM
6989 st = yes_state;
6990 yes_state = st->u.yes.prev_yes_state;
6991 PL_regmatch_state = st;
24b23f37 6992
3640db6b 6993 if (no_final)
5d458dd8 6994 locinput= st->locinput;
54612592 6995 state_num = st->resume_state + no_final;
24d3c4a9 6996 goto reenter_switch;
77cb431f
DM
6997 }
6998
a3621e74 6999 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
e4584336 7000 PL_colors[4], PL_colors[5]));
02db2b7b 7001
bf2039a9 7002 if (reginfo->info_aux_eval) {
19b95bf0
DM
7003 /* each successfully executed (?{...}) block does the equivalent of
7004 * local $^R = do {...}
7005 * When popping the save stack, all these locals would be undone;
7006 * bypass this by setting the outermost saved $^R to the latest
7007 * value */
4b22688e
YO
7008 /* I dont know if this is needed or works properly now.
7009 * see code related to PL_replgv elsewhere in this file.
7010 * Yves
7011 */
19b95bf0
DM
7012 if (oreplsv != GvSV(PL_replgv))
7013 sv_setsv(oreplsv, GvSV(PL_replgv));
7014 }
95b24440 7015 result = 1;
aa283a38 7016 goto final_exit;
4633a7c4
LW
7017
7018no:
a3621e74 7019 DEBUG_EXECUTE_r(
7821416a 7020 PerlIO_printf(Perl_debug_log,
786e8c11 7021 "%*s %sfailed...%s\n",
5bc10b2c 7022 REPORT_CODE_OFF+depth*2, "",
786e8c11 7023 PL_colors[4], PL_colors[5])
7821416a 7024 );
aa283a38 7025
262b90c4 7026no_silent:
54612592
YO
7027 if (no_final) {
7028 if (yes_state) {
7029 goto yes;
7030 } else {
7031 goto final_exit;
7032 }
7033 }
aa283a38
DM
7034 if (depth) {
7035 /* there's a previous state to backtrack to */
40a82448
DM
7036 st--;
7037 if (st < SLAB_FIRST(PL_regmatch_slab)) {
7038 PL_regmatch_slab = PL_regmatch_slab->prev;
7039 st = SLAB_LAST(PL_regmatch_slab);
7040 }
7041 PL_regmatch_state = st;
40a82448 7042 locinput= st->locinput;
40a82448 7043
5bc10b2c
DM
7044 DEBUG_STATE_pp("pop");
7045 depth--;
262b90c4
DM
7046 if (yes_state == st)
7047 yes_state = st->u.yes.prev_yes_state;
5bc10b2c 7048
24d3c4a9
DM
7049 state_num = st->resume_state + 1; /* failure = success + 1 */
7050 goto reenter_switch;
95b24440 7051 }
24d3c4a9 7052 result = 0;
aa283a38 7053
262b90c4 7054 final_exit:
bbe252da 7055 if (rex->intflags & PREGf_VERBARG_SEEN) {
5d458dd8
YO
7056 SV *sv_err = get_sv("REGERROR", 1);
7057 SV *sv_mrk = get_sv("REGMARK", 1);
7058 if (result) {
e2e6a0f1 7059 sv_commit = &PL_sv_no;
5d458dd8
YO
7060 if (!sv_yes_mark)
7061 sv_yes_mark = &PL_sv_yes;
7062 } else {
7063 if (!sv_commit)
7064 sv_commit = &PL_sv_yes;
7065 sv_yes_mark = &PL_sv_no;
7066 }
316ebaf2
JH
7067 assert(sv_err);
7068 assert(sv_mrk);
5d458dd8
YO
7069 sv_setsv(sv_err, sv_commit);
7070 sv_setsv(sv_mrk, sv_yes_mark);
e2e6a0f1 7071 }
19b95bf0 7072
81ed78b2
DM
7073
7074 if (last_pushed_cv) {
7075 dSP;
7076 POP_MULTICALL;
4f8dbb2d 7077 PERL_UNUSED_VAR(SP);
81ed78b2
DM
7078 }
7079
9d9163fb
DM
7080 assert(!result || locinput - reginfo->strbeg >= 0);
7081 return result ? locinput - reginfo->strbeg : -1;
a687059c
LW
7082}
7083
7084/*
7085 - regrepeat - repeatedly match something simple, report how many
d60de1d1 7086 *
e64f369d
KW
7087 * What 'simple' means is a node which can be the operand of a quantifier like
7088 * '+', or {1,3}
7089 *
d60de1d1
DM
7090 * startposp - pointer a pointer to the start position. This is updated
7091 * to point to the byte following the highest successful
7092 * match.
7093 * p - the regnode to be repeatedly matched against.
220db18a 7094 * reginfo - struct holding match state, such as strend
4063ade8 7095 * max - maximum number of things to match.
d60de1d1 7096 * depth - (for debugging) backtracking depth.
a687059c 7097 */
76e3520e 7098STATIC I32
272d35c9 7099S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
f9176b44 7100 regmatch_info *const reginfo, I32 max, int depth)
a687059c 7101{
4063ade8 7102 char *scan; /* Pointer to current position in target string */
eb578fdb 7103 I32 c;
220db18a 7104 char *loceol = reginfo->strend; /* local version */
4063ade8 7105 I32 hardcount = 0; /* How many matches so far */
ba44c216 7106 bool utf8_target = reginfo->is_utf8_target;
3018b823 7107 int to_complement = 0; /* Invert the result? */
d513472c 7108 UV utf8_flags;
3018b823 7109 _char_class_number classnum;
4f55667c
SP
7110#ifndef DEBUGGING
7111 PERL_UNUSED_ARG(depth);
7112#endif
a0d0e21e 7113
7918f24d
NC
7114 PERL_ARGS_ASSERT_REGREPEAT;
7115
f73aaa43 7116 scan = *startposp;
faf11cac
HS
7117 if (max == REG_INFTY)
7118 max = I32_MAX;
dfb8f192 7119 else if (! utf8_target && loceol - scan > max)
7f596f4c 7120 loceol = scan + max;
4063ade8
KW
7121
7122 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
7123 * to the maximum of how far we should go in it (leaving it set to the real
7124 * end, if the maximum permissible would take us beyond that). This allows
7125 * us to make the loop exit condition that we haven't gone past <loceol> to
7126 * also mean that we haven't exceeded the max permissible count, saving a
7127 * test each time through the loop. But it assumes that the OP matches a
7128 * single byte, which is true for most of the OPs below when applied to a
7129 * non-UTF-8 target. Those relatively few OPs that don't have this
7130 * characteristic will have to compensate.
7131 *
7132 * There is no adjustment for UTF-8 targets, as the number of bytes per
7133 * character varies. OPs will have to test both that the count is less
7134 * than the max permissible (using <hardcount> to keep track), and that we
7135 * are still within the bounds of the string (using <loceol>. A few OPs
7136 * match a single byte no matter what the encoding. They can omit the max
7137 * test if, for the UTF-8 case, they do the adjustment that was skipped
7138 * above.
7139 *
7140 * Thus, the code above sets things up for the common case; and exceptional
7141 * cases need extra work; the common case is to make sure <scan> doesn't
7142 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
7143 * count doesn't exceed the maximum permissible */
7144
a0d0e21e 7145 switch (OP(p)) {
22c35a8c 7146 case REG_ANY:
f2ed9b32 7147 if (utf8_target) {
1aa99e6b 7148 while (scan < loceol && hardcount < max && *scan != '\n') {
ffc61ed2
JH
7149 scan += UTF8SKIP(scan);
7150 hardcount++;
7151 }
7152 } else {
7153 while (scan < loceol && *scan != '\n')
7154 scan++;
a0ed51b3
LW
7155 }
7156 break;
ffc61ed2 7157 case SANY:
f2ed9b32 7158 if (utf8_target) {
a0804c9e 7159 while (scan < loceol && hardcount < max) {
def8e4ea
JH
7160 scan += UTF8SKIP(scan);
7161 hardcount++;
7162 }
7163 }
7164 else
7165 scan = loceol;
a0ed51b3 7166 break;
4063ade8 7167 case CANY: /* Move <scan> forward <max> bytes, unless goes off end */
9597860a 7168 if (utf8_target && loceol - scan > max) {
4063ade8
KW
7169
7170 /* <loceol> hadn't been adjusted in the UTF-8 case */
7171 scan += max;
7172 }
7173 else {
7174 scan = loceol;
7175 }
f33976b4 7176 break;
59d32103 7177 case EXACT:
f9176b44 7178 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
613a425d 7179
59d32103 7180 c = (U8)*STRING(p);
59d32103 7181
5e4a1da1
KW
7182 /* Can use a simple loop if the pattern char to match on is invariant
7183 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
7184 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
7185 * true iff it doesn't matter if the argument is in UTF-8 or not */
f9176b44 7186 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
e9369824 7187 if (utf8_target && loceol - scan > max) {
4063ade8
KW
7188 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
7189 * since here, to match at all, 1 char == 1 byte */
7190 loceol = scan + max;
7191 }
59d32103
KW
7192 while (scan < loceol && UCHARAT(scan) == c) {
7193 scan++;
7194 }
7195 }
f9176b44 7196 else if (reginfo->is_utf8_pat) {
5e4a1da1
KW
7197 if (utf8_target) {
7198 STRLEN scan_char_len;
5e4a1da1 7199
4063ade8 7200 /* When both target and pattern are UTF-8, we have to do
5e4a1da1
KW
7201 * string EQ */
7202 while (hardcount < max
9a902117
KW
7203 && scan < loceol
7204 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
5e4a1da1
KW
7205 && memEQ(scan, STRING(p), scan_char_len))
7206 {
4200a00c 7207 scan += scan_char_len;
5e4a1da1
KW
7208 hardcount++;
7209 }
7210 }
7211 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
b40a2c17 7212
5e4a1da1
KW
7213 /* Target isn't utf8; convert the character in the UTF-8
7214 * pattern to non-UTF8, and do a simple loop */
94bb8c36 7215 c = TWO_BYTE_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
5e4a1da1
KW
7216 while (scan < loceol && UCHARAT(scan) == c) {
7217 scan++;
7218 }
7219 } /* else pattern char is above Latin1, can't possibly match the
7220 non-UTF-8 target */
b40a2c17 7221 }
5e4a1da1 7222 else {
59d32103 7223
5e4a1da1
KW
7224 /* Here, the string must be utf8; pattern isn't, and <c> is
7225 * different in utf8 than not, so can't compare them directly.
7226 * Outside the loop, find the two utf8 bytes that represent c, and
7227 * then look for those in sequence in the utf8 string */
59d32103
KW
7228 U8 high = UTF8_TWO_BYTE_HI(c);
7229 U8 low = UTF8_TWO_BYTE_LO(c);
59d32103
KW
7230
7231 while (hardcount < max
7232 && scan + 1 < loceol
7233 && UCHARAT(scan) == high
7234 && UCHARAT(scan + 1) == low)
7235 {
7236 scan += 2;
7237 hardcount++;
7238 }
7239 }
7240 break;
5e4a1da1 7241
098b07d5
KW
7242 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
7243 assert(! reginfo->is_utf8_pat);
924ba076 7244 /* FALLTHROUGH */
2f7f8cb1 7245 case EXACTFA:
098b07d5 7246 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2f7f8cb1
KW
7247 goto do_exactf;
7248
d4e0b827 7249 case EXACTFL:
cea315b6 7250 utf8_flags = FOLDEQ_LOCALE;
17580e7a
KW
7251 goto do_exactf;
7252
2fdb7295
KW
7253 case EXACTF: /* This node only generated for non-utf8 patterns */
7254 assert(! reginfo->is_utf8_pat);
098b07d5
KW
7255 utf8_flags = 0;
7256 goto do_exactf;
62bf7766 7257
3c760661 7258 case EXACTFU_SS:
9a5a5549 7259 case EXACTFU:
f9176b44 7260 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
59d32103 7261
613a425d
KW
7262 do_exactf: {
7263 int c1, c2;
7264 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
d4e0b827 7265
f9176b44 7266 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
613a425d 7267
984e6dd1 7268 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
aed7b151 7269 reginfo))
984e6dd1 7270 {
613a425d 7271 if (c1 == CHRTEST_VOID) {
49b95fad 7272 /* Use full Unicode fold matching */
220db18a 7273 char *tmpeol = reginfo->strend;
f9176b44 7274 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
49b95fad
KW
7275 while (hardcount < max
7276 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
7277 STRING(p), NULL, pat_len,
f9176b44 7278 reginfo->is_utf8_pat, utf8_flags))
49b95fad
KW
7279 {
7280 scan = tmpeol;
220db18a 7281 tmpeol = reginfo->strend;
49b95fad
KW
7282 hardcount++;
7283 }
613a425d
KW
7284 }
7285 else if (utf8_target) {
7286 if (c1 == c2) {
4063ade8
KW
7287 while (scan < loceol
7288 && hardcount < max
613a425d
KW
7289 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
7290 {
7291 scan += UTF8SKIP(scan);
7292 hardcount++;
7293 }
7294 }
7295 else {
4063ade8
KW
7296 while (scan < loceol
7297 && hardcount < max
613a425d
KW
7298 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
7299 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
7300 {
7301 scan += UTF8SKIP(scan);
7302 hardcount++;
7303 }
7304 }
7305 }
7306 else if (c1 == c2) {
7307 while (scan < loceol && UCHARAT(scan) == c1) {
7308 scan++;
7309 }
7310 }
7311 else {
7312 while (scan < loceol &&
7313 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
7314 {
7315 scan++;
7316 }
7317 }
634c83a2 7318 }
bbce6d69 7319 break;
613a425d 7320 }
a0d0e21e 7321 case ANYOF:
e0193e47 7322 if (utf8_target) {
4e8910e0 7323 while (hardcount < max
9a902117 7324 && scan < loceol
3db24e1e 7325 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
4e8910e0 7326 {
9a902117 7327 scan += UTF8SKIP(scan);
ffc61ed2
JH
7328 hardcount++;
7329 }
7330 } else {
32fc9b6a 7331 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
ffc61ed2
JH
7332 scan++;
7333 }
a0d0e21e 7334 break;
4063ade8 7335
3018b823 7336 /* The argument (FLAGS) to all the POSIX node types is the class number */
980866de 7337
3018b823
KW
7338 case NPOSIXL:
7339 to_complement = 1;
7340 /* FALLTHROUGH */
980866de 7341
3018b823 7342 case POSIXL:
3018b823
KW
7343 if (! utf8_target) {
7344 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
7345 *scan)))
a12cf05f 7346 {
3018b823
KW
7347 scan++;
7348 }
7349 } else {
7350 while (hardcount < max && scan < loceol
7351 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
7352 (U8 *) scan)))
7353 {
7354 scan += UTF8SKIP(scan);
ffc61ed2
JH
7355 hardcount++;
7356 }
a0ed51b3
LW
7357 }
7358 break;
0658cdde 7359
3018b823
KW
7360 case POSIXD:
7361 if (utf8_target) {
7362 goto utf8_posix;
7363 }
7364 /* FALLTHROUGH */
7365
0658cdde 7366 case POSIXA:
0430522f 7367 if (utf8_target && loceol - scan > max) {
4063ade8 7368
7aee35ff
KW
7369 /* We didn't adjust <loceol> at the beginning of this routine
7370 * because is UTF-8, but it is actually ok to do so, since here, to
7371 * match, 1 char == 1 byte. */
4063ade8
KW
7372 loceol = scan + max;
7373 }
7374 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
0658cdde
KW
7375 scan++;
7376 }
7377 break;
980866de 7378
3018b823
KW
7379 case NPOSIXD:
7380 if (utf8_target) {
7381 to_complement = 1;
7382 goto utf8_posix;
7383 }
924ba076 7384 /* FALLTHROUGH */
980866de 7385
3018b823
KW
7386 case NPOSIXA:
7387 if (! utf8_target) {
7388 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
a12cf05f
KW
7389 scan++;
7390 }
4063ade8 7391 }
3018b823 7392 else {
980866de 7393
3018b823 7394 /* The complement of something that matches only ASCII matches all
837226c8 7395 * non-ASCII, plus everything in ASCII that isn't in the class. */
bedac28b 7396 while (hardcount < max && scan < loceol
837226c8 7397 && (! isASCII_utf8(scan)
3018b823 7398 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
a12cf05f 7399 {
3018b823 7400 scan += UTF8SKIP(scan);
ffc61ed2
JH
7401 hardcount++;
7402 }
3018b823
KW
7403 }
7404 break;
980866de 7405
3018b823
KW
7406 case NPOSIXU:
7407 to_complement = 1;
7408 /* FALLTHROUGH */
7409
7410 case POSIXU:
7411 if (! utf8_target) {
7412 while (scan < loceol && to_complement
7413 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
4063ade8 7414 {
3018b823
KW
7415 scan++;
7416 }
cfaf538b
KW
7417 }
7418 else {
3018b823
KW
7419 utf8_posix:
7420 classnum = (_char_class_number) FLAGS(p);
7421 if (classnum < _FIRST_NON_SWASH_CC) {
7422
7423 /* Here, a swash is needed for above-Latin1 code points.
7424 * Process as many Latin1 code points using the built-in rules.
7425 * Go to another loop to finish processing upon encountering
7426 * the first Latin1 code point. We could do that in this loop
7427 * as well, but the other way saves having to test if the swash
7428 * has been loaded every time through the loop: extra space to
7429 * save a test. */
7430 while (hardcount < max && scan < loceol) {
7431 if (UTF8_IS_INVARIANT(*scan)) {
7432 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
7433 classnum))))
7434 {
7435 break;
7436 }
7437 scan++;
7438 }
7439 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
7440 if (! (to_complement
94bb8c36
KW
7441 ^ cBOOL(_generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*scan,
7442 *(scan + 1)),
3018b823
KW
7443 classnum))))
7444 {
7445 break;
7446 }
7447 scan += 2;
7448 }
7449 else {
7450 goto found_above_latin1;
7451 }
7452
7453 hardcount++;
7454 }
7455 }
7456 else {
7457 /* For these character classes, the knowledge of how to handle
7458 * every code point is compiled in to Perl via a macro. This
7459 * code is written for making the loops as tight as possible.
7460 * It could be refactored to save space instead */
7461 switch (classnum) {
7462 case _CC_ENUM_SPACE: /* XXX would require separate code
7463 if we revert the change of \v
7464 matching this */
924ba076 7465 /* FALLTHROUGH */
3018b823
KW
7466 case _CC_ENUM_PSXSPC:
7467 while (hardcount < max
7468 && scan < loceol
7469 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
7470 {
7471 scan += UTF8SKIP(scan);
7472 hardcount++;
7473 }
7474 break;
7475 case _CC_ENUM_BLANK:
7476 while (hardcount < max
7477 && scan < loceol
7478 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
7479 {
7480 scan += UTF8SKIP(scan);
7481 hardcount++;
7482 }
7483 break;
7484 case _CC_ENUM_XDIGIT:
7485 while (hardcount < max
7486 && scan < loceol
7487 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
7488 {
7489 scan += UTF8SKIP(scan);
7490 hardcount++;
7491 }
7492 break;
7493 case _CC_ENUM_VERTSPACE:
7494 while (hardcount < max
7495 && scan < loceol
7496 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
7497 {
7498 scan += UTF8SKIP(scan);
7499 hardcount++;
7500 }
7501 break;
7502 case _CC_ENUM_CNTRL:
7503 while (hardcount < max
7504 && scan < loceol
7505 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
7506 {
7507 scan += UTF8SKIP(scan);
7508 hardcount++;
7509 }
7510 break;
7511 default:
7512 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
7513 }
7514 }
a0ed51b3 7515 }
3018b823 7516 break;
4063ade8 7517
3018b823
KW
7518 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
7519
7520 /* Load the swash if not already present */
7521 if (! PL_utf8_swash_ptrs[classnum]) {
7522 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
7523 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
2a16ac92
KW
7524 "utf8",
7525 "",
7526 &PL_sv_undef, 1, 0,
7527 PL_XPosix_ptrs[classnum], &flags);
4063ade8 7528 }
3018b823
KW
7529
7530 while (hardcount < max && scan < loceol
7531 && to_complement ^ cBOOL(_generic_utf8(
7532 classnum,
7533 scan,
7534 swash_fetch(PL_utf8_swash_ptrs[classnum],
7535 (U8 *) scan,
7536 TRUE))))
7537 {
7538 scan += UTF8SKIP(scan);
7539 hardcount++;
7540 }
7541 break;
7542
e1d1eefb 7543 case LNBREAK:
e64f369d
KW
7544 if (utf8_target) {
7545 while (hardcount < max && scan < loceol &&
7546 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
7547 scan += c;
7548 hardcount++;
7549 }
7550 } else {
7551 /* LNBREAK can match one or two latin chars, which is ok, but we
7552 * have to use hardcount in this situation, and throw away the
7553 * adjustment to <loceol> done before the switch statement */
220db18a 7554 loceol = reginfo->strend;
e64f369d
KW
7555 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
7556 scan+=c;
7557 hardcount++;
7558 }
7559 }
7560 break;
e1d1eefb 7561
584b1f02
KW
7562 case BOUND:
7563 case BOUNDA:
7564 case BOUNDL:
7565 case BOUNDU:
7566 case EOS:
7567 case GPOS:
7568 case KEEPS:
7569 case NBOUND:
7570 case NBOUNDA:
7571 case NBOUNDL:
7572 case NBOUNDU:
7573 case OPFAIL:
7574 case SBOL:
7575 case SEOL:
7576 /* These are all 0 width, so match right here or not at all. */
7577 break;
7578
7579 default:
7580 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
a74ff37d 7581 /* NOTREACHED */
e5964223 7582 NOT_REACHED;
584b1f02 7583
a0d0e21e 7584 }
a687059c 7585
a0ed51b3
LW
7586 if (hardcount)
7587 c = hardcount;
7588 else
f73aaa43
DM
7589 c = scan - *startposp;
7590 *startposp = scan;
a687059c 7591
a3621e74 7592 DEBUG_r({
e68ec53f 7593 GET_RE_DEBUG_FLAGS_DECL;
be8e71aa 7594 DEBUG_EXECUTE_r({
e68ec53f 7595 SV * const prop = sv_newmortal();
8b9781c9 7596 regprop(prog, prop, p, reginfo, NULL);
e68ec53f 7597 PerlIO_printf(Perl_debug_log,
be8e71aa 7598 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
e2e6a0f1 7599 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
a3621e74 7600 });
be8e71aa 7601 });
9041c2e3 7602
a0d0e21e 7603 return(c);
a687059c
LW
7604}
7605
c277df42 7606
be8e71aa 7607#if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
c277df42 7608/*
6c6525b8 7609- regclass_swash - prepare the utf8 swash. Wraps the shared core version to
e0193e47
KW
7610create a copy so that changes the caller makes won't change the shared one.
7611If <altsvp> is non-null, will return NULL in it, for back-compat.
6c6525b8 7612 */
ffc61ed2 7613SV *
5aaab254 7614Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
ffc61ed2 7615{
6c6525b8 7616 PERL_ARGS_ASSERT_REGCLASS_SWASH;
e0193e47
KW
7617
7618 if (altsvp) {
7619 *altsvp = NULL;
7620 }
7621
ef9bc832 7622 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
6c6525b8 7623}
6c6525b8 7624
3e63bed3 7625#endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
ffc61ed2
JH
7626
7627/*
ba7b4546 7628 - reginclass - determine if a character falls into a character class
832705d4 7629
6698fab5
KW
7630 n is the ANYOF regnode
7631 p is the target string
3db24e1e 7632 p_end points to one byte beyond the end of the target string
6698fab5 7633 utf8_target tells whether p is in UTF-8.
832705d4 7634
635cd5d4 7635 Returns true if matched; false otherwise.
eba1359e 7636
d5788240
KW
7637 Note that this can be a synthetic start class, a combination of various
7638 nodes, so things you think might be mutually exclusive, such as locale,
7639 aren't. It can match both locale and non-locale
7640
bbce6d69 7641 */
7642
76e3520e 7643STATIC bool
3db24e1e 7644S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
bbce6d69 7645{
27da23d5 7646 dVAR;
a3b680e6 7647 const char flags = ANYOF_FLAGS(n);
bbce6d69 7648 bool match = FALSE;
cc07378b 7649 UV c = *p;
1aa99e6b 7650
7918f24d
NC
7651 PERL_ARGS_ASSERT_REGINCLASS;
7652
afd2eb18
KW
7653 /* If c is not already the code point, get it. Note that
7654 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
7655 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
635cd5d4 7656 STRLEN c_len = 0;
3db24e1e 7657 c = utf8n_to_uvchr(p, p_end - p, &c_len,
6182169b
KW
7658 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
7659 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
7660 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
7661 * UTF8_ALLOW_FFFF */
f7ab54c6 7662 if (c_len == (STRLEN)-1)
e8a70c6f 7663 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
19f67299 7664 }
4b3cda86 7665
7cdde544 7666 /* If this character is potentially in the bitmap, check it */
dcb20b36 7667 if (c < NUM_ANYOF_CODE_POINTS) {
ffc61ed2
JH
7668 if (ANYOF_BITMAP_TEST(n, c))
7669 match = TRUE;
93e92956
KW
7670 else if ((flags & ANYOF_MATCHES_ALL_NON_UTF8_NON_ASCII)
7671 && ! utf8_target
7672 && ! isASCII(c))
11454c59
KW
7673 {
7674 match = TRUE;
7675 }
1462525b 7676 else if (flags & ANYOF_LOCALE_FLAGS) {
6942fd9a 7677 if ((flags & ANYOF_LOC_FOLD)
e0a1ff7a 7678 && c < 256
6942fd9a
KW
7679 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
7680 {
7681 match = TRUE;
b99851e1 7682 }
e0a1ff7a
KW
7683 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
7684 && c < 256
7685 ) {
31c7f561
KW
7686
7687 /* The data structure is arranged so bits 0, 2, 4, ... are set
7688 * if the class includes the Posix character class given by
7689 * bit/2; and 1, 3, 5, ... are set if the class includes the
7690 * complemented Posix class given by int(bit/2). So we loop
7691 * through the bits, each time changing whether we complement
7692 * the result or not. Suppose for the sake of illustration
7693 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
7694 * is set, it means there is a match for this ANYOF node if the
7695 * character is in the class given by the expression (0 / 2 = 0
7696 * = \w). If it is in that class, isFOO_lc() will return 1,
7697 * and since 'to_complement' is 0, the result will stay TRUE,
7698 * and we exit the loop. Suppose instead that bit 0 is 0, but
7699 * bit 1 is 1. That means there is a match if the character
7700 * matches \W. We won't bother to call isFOO_lc() on bit 0,
7701 * but will on bit 1. On the second iteration 'to_complement'
7702 * will be 1, so the exclusive or will reverse things, so we
7703 * are testing for \W. On the third iteration, 'to_complement'
7704 * will be 0, and we would be testing for \s; the fourth
b0d691b2
KW
7705 * iteration would test for \S, etc.
7706 *
7707 * Note that this code assumes that all the classes are closed
7708 * under folding. For example, if a character matches \w, then
7709 * its fold does too; and vice versa. This should be true for
7710 * any well-behaved locale for all the currently defined Posix
7711 * classes, except for :lower: and :upper:, which are handled
7712 * by the pseudo-class :cased: which matches if either of the
7713 * other two does. To get rid of this assumption, an outer
7714 * loop could be used below to iterate over both the source
7715 * character, and its fold (if different) */
31c7f561
KW
7716
7717 int count = 0;
7718 int to_complement = 0;
522b3c1e 7719
31c7f561 7720 while (count < ANYOF_MAX) {
8efd3f97 7721 if (ANYOF_POSIXL_TEST(n, count)
31c7f561
KW
7722 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
7723 {
7724 match = TRUE;
7725 break;
7726 }
7727 count++;
7728 to_complement ^= 1;
7729 }
ffc61ed2 7730 }
a0ed51b3 7731 }
a0ed51b3
LW
7732 }
7733
31f05a37 7734
7cdde544 7735 /* If the bitmap didn't (or couldn't) match, and something outside the
3b04b210 7736 * bitmap could match, try that. */
ef87b810 7737 if (!match) {
93e92956
KW
7738 if (c >= NUM_ANYOF_CODE_POINTS
7739 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
7740 {
7741 match = TRUE; /* Everything above the bitmap matches */
e051a21d 7742 }
93e92956
KW
7743 else if ((flags & ANYOF_HAS_NONBITMAP_NON_UTF8_MATCHES)
7744 || (utf8_target && (flags & ANYOF_HAS_UTF8_NONBITMAP_MATCHES))
1ee208c4
KW
7745 || ((flags & ANYOF_LOC_FOLD)
7746 && IN_UTF8_CTYPE_LOCALE
93e92956 7747 && ARG(n) != ANYOF_ONLY_HAS_BITMAP))
3b04b210 7748 {
1ee208c4
KW
7749 SV* only_utf8_locale = NULL;
7750 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
ef9bc832 7751 &only_utf8_locale, NULL);
7cdde544 7752 if (sw) {
893ef8be 7753 U8 utf8_buffer[2];
7cdde544
KW
7754 U8 * utf8_p;
7755 if (utf8_target) {
7756 utf8_p = (U8 *) p;
e0193e47 7757 } else { /* Convert to utf8 */
893ef8be
KW
7758 utf8_p = utf8_buffer;
7759 append_utf8_from_native_byte(*p, &utf8_p);
7760 utf8_p = utf8_buffer;
7cdde544 7761 }
f56b6394 7762
e0193e47 7763 if (swash_fetch(sw, utf8_p, TRUE)) {
7cdde544 7764 match = TRUE;
e0193e47 7765 }
7cdde544 7766 }
1ee208c4
KW
7767 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
7768 match = _invlist_contains_cp(only_utf8_locale, c);
7769 }
7cdde544 7770 }
5073ffbd
KW
7771
7772 if (UNICODE_IS_SUPER(c)
ae986089 7773 && (flags & ANYOF_WARN_SUPER)
5073ffbd
KW
7774 && ckWARN_d(WARN_NON_UNICODE))
7775 {
7776 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
2d88a86a 7777 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
5073ffbd 7778 }
7cdde544
KW
7779 }
7780
5dbb0c08
KW
7781#if ANYOF_INVERT != 1
7782 /* Depending on compiler optimization cBOOL takes time, so if don't have to
7783 * use it, don't */
7784# error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
7785#endif
7786
f0fdc1c9 7787 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
5dbb0c08 7788 return (flags & ANYOF_INVERT) ^ match;
a0ed51b3 7789}
161b471a 7790
dfe13c55 7791STATIC U8 *
ea3daa5d 7792S_reghop3(U8 *s, SSize_t off, const U8* lim)
9041c2e3 7793{
6af86488
KW
7794 /* return the position 'off' UTF-8 characters away from 's', forward if
7795 * 'off' >= 0, backwards if negative. But don't go outside of position
7796 * 'lim', which better be < s if off < 0 */
7797
7918f24d
NC
7798 PERL_ARGS_ASSERT_REGHOP3;
7799
a0ed51b3 7800 if (off >= 0) {
1aa99e6b 7801 while (off-- && s < lim) {
ffc61ed2 7802 /* XXX could check well-formedness here */
a0ed51b3 7803 s += UTF8SKIP(s);
ffc61ed2 7804 }
a0ed51b3
LW
7805 }
7806 else {
1de06328
YO
7807 while (off++ && s > lim) {
7808 s--;
7809 if (UTF8_IS_CONTINUED(*s)) {
7810 while (s > lim && UTF8_IS_CONTINUATION(*s))
7811 s--;
a0ed51b3 7812 }
1de06328 7813 /* XXX could check well-formedness here */
a0ed51b3
LW
7814 }
7815 }
7816 return s;
7817}
161b471a 7818
dfe13c55 7819STATIC U8 *
ea3daa5d 7820S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
1de06328 7821{
7918f24d
NC
7822 PERL_ARGS_ASSERT_REGHOP4;
7823
1de06328
YO
7824 if (off >= 0) {
7825 while (off-- && s < rlim) {
7826 /* XXX could check well-formedness here */
7827 s += UTF8SKIP(s);
7828 }
7829 }
7830 else {
7831 while (off++ && s > llim) {
7832 s--;
7833 if (UTF8_IS_CONTINUED(*s)) {
7834 while (s > llim && UTF8_IS_CONTINUATION(*s))
7835 s--;
7836 }
7837 /* XXX could check well-formedness here */
7838 }
7839 }
7840 return s;
7841}
1de06328 7842
557f47af
DM
7843/* like reghop3, but returns NULL on overrun, rather than returning last
7844 * char pos */
7845
1de06328 7846STATIC U8 *
ea3daa5d 7847S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
a0ed51b3 7848{
7918f24d
NC
7849 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7850
a0ed51b3 7851 if (off >= 0) {
1aa99e6b 7852 while (off-- && s < lim) {
ffc61ed2 7853 /* XXX could check well-formedness here */
a0ed51b3 7854 s += UTF8SKIP(s);
ffc61ed2 7855 }
a0ed51b3 7856 if (off >= 0)
3dab1dad 7857 return NULL;
a0ed51b3
LW
7858 }
7859 else {
1de06328
YO
7860 while (off++ && s > lim) {
7861 s--;
7862 if (UTF8_IS_CONTINUED(*s)) {
7863 while (s > lim && UTF8_IS_CONTINUATION(*s))
7864 s--;
a0ed51b3 7865 }
1de06328 7866 /* XXX could check well-formedness here */
a0ed51b3
LW
7867 }
7868 if (off <= 0)
3dab1dad 7869 return NULL;
a0ed51b3
LW
7870 }
7871 return s;
7872}
51371543 7873
a75351a1
DM
7874
7875/* when executing a regex that may have (?{}), extra stuff needs setting
7876 up that will be visible to the called code, even before the current
7877 match has finished. In particular:
7878
7879 * $_ is localised to the SV currently being matched;
7880 * pos($_) is created if necessary, ready to be updated on each call-out
7881 to code;
7882 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
7883 isn't set until the current pattern is successfully finished), so that
7884 $1 etc of the match-so-far can be seen;
7885 * save the old values of subbeg etc of the current regex, and set then
7886 to the current string (again, this is normally only done at the end
7887 of execution)
a75351a1
DM
7888*/
7889
7890static void
7891S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
7892{
7893 MAGIC *mg;
7894 regexp *const rex = ReANY(reginfo->prog);
bf2039a9 7895 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
8adc0f72 7896
8adc0f72 7897 eval_state->rex = rex;
a75351a1 7898
a75351a1
DM
7899 if (reginfo->sv) {
7900 /* Make $_ available to executed code. */
7901 if (reginfo->sv != DEFSV) {
7902 SAVE_DEFSV;
7903 DEFSV_set(reginfo->sv);
7904 }
7905
96c2a8ff 7906 if (!(mg = mg_find_mglob(reginfo->sv))) {
a75351a1 7907 /* prepare for quick setting of pos */
96c2a8ff 7908 mg = sv_magicext_mglob(reginfo->sv);
a75351a1
DM
7909 mg->mg_len = -1;
7910 }
8adc0f72
DM
7911 eval_state->pos_magic = mg;
7912 eval_state->pos = mg->mg_len;
25fdce4a 7913 eval_state->pos_flags = mg->mg_flags;
a75351a1 7914 }
8adc0f72
DM
7915 else
7916 eval_state->pos_magic = NULL;
7917
a75351a1 7918 if (!PL_reg_curpm) {
f65e70f5
DM
7919 /* PL_reg_curpm is a fake PMOP that we can attach the current
7920 * regex to and point PL_curpm at, so that $1 et al are visible
7921 * within a /(?{})/. It's just allocated once per interpreter the
7922 * first time its needed */
a75351a1
DM
7923 Newxz(PL_reg_curpm, 1, PMOP);
7924#ifdef USE_ITHREADS
7925 {
7926 SV* const repointer = &PL_sv_undef;
7927 /* this regexp is also owned by the new PL_reg_curpm, which
7928 will try to free it. */
7929 av_push(PL_regex_padav, repointer);
b9f2b683 7930 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
a75351a1
DM
7931 PL_regex_pad = AvARRAY(PL_regex_padav);
7932 }
7933#endif
7934 }
7935 SET_reg_curpm(reginfo->prog);
8adc0f72 7936 eval_state->curpm = PL_curpm;
a75351a1
DM
7937 PL_curpm = PL_reg_curpm;
7938 if (RXp_MATCH_COPIED(rex)) {
7939 /* Here is a serious problem: we cannot rewrite subbeg,
7940 since it may be needed if this match fails. Thus
7941 $` inside (?{}) could fail... */
8adc0f72
DM
7942 eval_state->subbeg = rex->subbeg;
7943 eval_state->sublen = rex->sublen;
7944 eval_state->suboffset = rex->suboffset;
a8ee055f 7945 eval_state->subcoffset = rex->subcoffset;
a75351a1 7946#ifdef PERL_ANY_COW
8adc0f72 7947 eval_state->saved_copy = rex->saved_copy;
a75351a1
DM
7948#endif
7949 RXp_MATCH_COPIED_off(rex);
7950 }
7951 else
8adc0f72 7952 eval_state->subbeg = NULL;
a75351a1
DM
7953 rex->subbeg = (char *)reginfo->strbeg;
7954 rex->suboffset = 0;
7955 rex->subcoffset = 0;
7956 rex->sublen = reginfo->strend - reginfo->strbeg;
7957}
7958
bf2039a9
DM
7959
7960/* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
a75351a1 7961
51371543 7962static void
bf2039a9 7963S_cleanup_regmatch_info_aux(pTHX_ void *arg)
51371543 7964{
bf2039a9
DM
7965 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
7966 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
331b2dcc 7967 regmatch_slab *s;
bf2039a9 7968
2ac8ff4b
DM
7969 Safefree(aux->poscache);
7970
331b2dcc 7971 if (eval_state) {
bf2039a9 7972
331b2dcc 7973 /* undo the effects of S_setup_eval_state() */
bf2039a9 7974
331b2dcc
DM
7975 if (eval_state->subbeg) {
7976 regexp * const rex = eval_state->rex;
7977 rex->subbeg = eval_state->subbeg;
7978 rex->sublen = eval_state->sublen;
7979 rex->suboffset = eval_state->suboffset;
7980 rex->subcoffset = eval_state->subcoffset;
db2c6cb3 7981#ifdef PERL_ANY_COW
331b2dcc 7982 rex->saved_copy = eval_state->saved_copy;
ed252734 7983#endif
331b2dcc
DM
7984 RXp_MATCH_COPIED_on(rex);
7985 }
7986 if (eval_state->pos_magic)
25fdce4a 7987 {
331b2dcc 7988 eval_state->pos_magic->mg_len = eval_state->pos;
25fdce4a
FC
7989 eval_state->pos_magic->mg_flags =
7990 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
7991 | (eval_state->pos_flags & MGf_BYTES);
7992 }
331b2dcc
DM
7993
7994 PL_curpm = eval_state->curpm;
8adc0f72 7995 }
bf2039a9 7996
331b2dcc
DM
7997 PL_regmatch_state = aux->old_regmatch_state;
7998 PL_regmatch_slab = aux->old_regmatch_slab;
7999
8000 /* free all slabs above current one - this must be the last action
8001 * of this function, as aux and eval_state are allocated within
8002 * slabs and may be freed here */
8003
8004 s = PL_regmatch_slab->next;
8005 if (s) {
8006 PL_regmatch_slab->next = NULL;
8007 while (s) {
8008 regmatch_slab * const osl = s;
8009 s = s->next;
8010 Safefree(osl);
8011 }
8012 }
51371543 8013}
33b8afdf 8014
8adc0f72 8015
33b8afdf 8016STATIC void
5aaab254 8017S_to_utf8_substr(pTHX_ regexp *prog)
33b8afdf 8018{
7e0d5ad7
KW
8019 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
8020 * on the converted value */
8021
a1cac82e 8022 int i = 1;
7918f24d
NC
8023
8024 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
8025
a1cac82e
NC
8026 do {
8027 if (prog->substrs->data[i].substr
8028 && !prog->substrs->data[i].utf8_substr) {
8029 SV* const sv = newSVsv(prog->substrs->data[i].substr);
8030 prog->substrs->data[i].utf8_substr = sv;
8031 sv_utf8_upgrade(sv);
610460f9 8032 if (SvVALID(prog->substrs->data[i].substr)) {
cffe132d 8033 if (SvTAIL(prog->substrs->data[i].substr)) {
610460f9
NC
8034 /* Trim the trailing \n that fbm_compile added last
8035 time. */
8036 SvCUR_set(sv, SvCUR(sv) - 1);
8037 /* Whilst this makes the SV technically "invalid" (as its
8038 buffer is no longer followed by "\0") when fbm_compile()
8039 adds the "\n" back, a "\0" is restored. */
cffe132d
NC
8040 fbm_compile(sv, FBMcf_TAIL);
8041 } else
8042 fbm_compile(sv, 0);
610460f9 8043 }
a1cac82e
NC
8044 if (prog->substrs->data[i].substr == prog->check_substr)
8045 prog->check_utf8 = sv;
8046 }
8047 } while (i--);
33b8afdf
JH
8048}
8049
7e0d5ad7 8050STATIC bool
5aaab254 8051S_to_byte_substr(pTHX_ regexp *prog)
33b8afdf 8052{
7e0d5ad7
KW
8053 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
8054 * on the converted value; returns FALSE if can't be converted. */
8055
a1cac82e 8056 int i = 1;
7918f24d
NC
8057
8058 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
8059
a1cac82e
NC
8060 do {
8061 if (prog->substrs->data[i].utf8_substr
8062 && !prog->substrs->data[i].substr) {
8063 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
7e0d5ad7
KW
8064 if (! sv_utf8_downgrade(sv, TRUE)) {
8065 return FALSE;
8066 }
5400f398
KW
8067 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
8068 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
8069 /* Trim the trailing \n that fbm_compile added last
8070 time. */
8071 SvCUR_set(sv, SvCUR(sv) - 1);
8072 fbm_compile(sv, FBMcf_TAIL);
8073 } else
8074 fbm_compile(sv, 0);
8075 }
a1cac82e
NC
8076 prog->substrs->data[i].substr = sv;
8077 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
8078 prog->check_substr = sv;
33b8afdf 8079 }
a1cac82e 8080 } while (i--);
7e0d5ad7
KW
8081
8082 return TRUE;
33b8afdf 8083}
66610fdd
RGS
8084
8085/*
8086 * Local variables:
8087 * c-indentation-style: bsd
8088 * c-basic-offset: 4
14d04a33 8089 * indent-tabs-mode: nil
66610fdd
RGS
8090 * End:
8091 *
14d04a33 8092 * ex: set ts=8 sts=4 sw=4 et:
37442d52 8093 */