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