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