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