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