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