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