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