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