This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Re├źnable qr caching for (??{}) retval where possible
[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 }