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