This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlre.pod: Fix omission of /a
[perl5.git] / regcomp.c
CommitLineData
a0d0e21e
LW
1/* regcomp.c
2 */
3
4/*
4ac71550
TC
5 * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
6 *
7 * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
a0d0e21e
LW
8 */
9
61296642
DM
10/* This file contains functions for compiling a regular expression. See
11 * also regexec.c which funnily enough, contains functions for executing
166f8a29 12 * a regular expression.
e4a054ea
DM
13 *
14 * This file is also copied at build time to ext/re/re_comp.c, where
15 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16 * This causes the main functions to be compiled under new names and with
17 * debugging support added, which makes "use re 'debug'" work.
166f8a29
DM
18 */
19
a687059c
LW
20/* NOTE: this is derived from Henry Spencer's regexp code, and should not
21 * confused with the original package (see point 3 below). Thanks, Henry!
22 */
23
24/* Additional note: this code is very heavily munged from Henry's version
25 * in places. In some spots I've traded clarity for efficiency, so don't
26 * blame Henry for some of the lack of readability.
27 */
28
e50aee73 29/* The names of the functions have been changed from regcomp and
3b753521 30 * regexec to pregcomp and pregexec in order to avoid conflicts
e50aee73
AD
31 * with the POSIX routines of the same names.
32*/
33
b9d5759e 34#ifdef PERL_EXT_RE_BUILD
54df2634 35#include "re_top.h"
b81d288d 36#endif
56953603 37
a687059c 38/*
e50aee73 39 * pregcomp and pregexec -- regsub and regerror are not used in perl
a687059c
LW
40 *
41 * Copyright (c) 1986 by University of Toronto.
42 * Written by Henry Spencer. Not derived from licensed software.
43 *
44 * Permission is granted to anyone to use this software for any
45 * purpose on any computer system, and to redistribute it freely,
46 * subject to the following restrictions:
47 *
48 * 1. The author is not responsible for the consequences of use of
49 * this software, no matter how awful, even if they arise
50 * from defects in it.
51 *
52 * 2. The origin of this software must not be misrepresented, either
53 * by explicit claim or by omission.
54 *
55 * 3. Altered versions must be plainly marked as such, and must not
56 * be misrepresented as being the original software.
57 *
58 *
59 **** Alterations to Henry's code are...
60 ****
4bb101f2 61 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
1129b882
NC
62 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63 **** by Larry Wall and others
a687059c 64 ****
9ef589d8
LW
65 **** You may distribute under the terms of either the GNU General Public
66 **** License or the Artistic License, as specified in the README file.
67
a687059c
LW
68 *
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
72 */
73#include "EXTERN.h"
864dbfa3 74#define PERL_IN_REGCOMP_C
a687059c 75#include "perl.h"
d06ea78c 76
acfe0abc 77#ifndef PERL_IN_XSUB_RE
d06ea78c
GS
78# include "INTERN.h"
79#endif
c277df42
IZ
80
81#define REG_COMP_C
54df2634
NC
82#ifdef PERL_IN_XSUB_RE
83# include "re_comp.h"
84#else
85# include "regcomp.h"
86#endif
a687059c 87
04e98a4d
AD
88#include "dquote_static.c"
89
d4cce5f1 90#ifdef op
11343788 91#undef op
d4cce5f1 92#endif /* op */
11343788 93
fe14fcc3 94#ifdef MSDOS
7e4e8c89 95# if defined(BUGGY_MSC6)
fe14fcc3 96 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
7e4e8c89 97# pragma optimize("a",off)
fe14fcc3 98 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
7e4e8c89
NC
99# pragma optimize("w",on )
100# endif /* BUGGY_MSC6 */
fe14fcc3
LW
101#endif /* MSDOS */
102
a687059c
LW
103#ifndef STATIC
104#define STATIC static
105#endif
106
830247a4 107typedef struct RExC_state_t {
e2509266 108 U32 flags; /* are we folding, multilining? */
830247a4 109 char *precomp; /* uncompiled string. */
288b8c02 110 REGEXP *rx_sv; /* The SV that is the regexp. */
f8fc2ecf
YO
111 regexp *rx; /* perl core regexp structure */
112 regexp_internal *rxi; /* internal data for regexp object pprivate field */
fac92740 113 char *start; /* Start of input for compile */
830247a4
IZ
114 char *end; /* End of input for compile */
115 char *parse; /* Input-scan pointer. */
116 I32 whilem_seen; /* number of WHILEM in this expr */
fac92740 117 regnode *emit_start; /* Start of emitted-code area */
3b57cd43 118 regnode *emit_bound; /* First regnode outside of the allocated space */
ffc61ed2 119 regnode *emit; /* Code-emit pointer; &regdummy = don't = compiling */
830247a4
IZ
120 I32 naughty; /* How bad is this pattern? */
121 I32 sawback; /* Did we see \1, ...? */
122 U32 seen;
123 I32 size; /* Code size. */
c74340f9
YO
124 I32 npar; /* Capture buffer count, (OPEN). */
125 I32 cpar; /* Capture buffer count, (CLOSE). */
e2e6a0f1 126 I32 nestroot; /* root parens we are in - used by accept */
830247a4
IZ
127 I32 extralen;
128 I32 seen_zerolen;
129 I32 seen_evals;
40d049e4
YO
130 regnode **open_parens; /* pointers to open parens */
131 regnode **close_parens; /* pointers to close parens */
132 regnode *opend; /* END node in program */
02daf0ab
YO
133 I32 utf8; /* whether the pattern is utf8 or not */
134 I32 orig_utf8; /* whether the pattern was originally in utf8 */
135 /* XXX use this for future optimisation of case
136 * where pattern must be upgraded to utf8. */
81714fb9 137 HV *paren_names; /* Paren names */
1f1031fe 138
40d049e4
YO
139 regnode **recurse; /* Recurse regops */
140 I32 recurse_count; /* Number of recurse regops */
b57e4118 141 I32 in_lookbehind;
830247a4
IZ
142#if ADD_TO_REGEXEC
143 char *starttry; /* -Dr: where regtry was called. */
144#define RExC_starttry (pRExC_state->starttry)
145#endif
3dab1dad 146#ifdef DEBUGGING
be8e71aa 147 const char *lastparse;
3dab1dad 148 I32 lastnum;
1f1031fe 149 AV *paren_name_list; /* idx -> name */
3dab1dad
YO
150#define RExC_lastparse (pRExC_state->lastparse)
151#define RExC_lastnum (pRExC_state->lastnum)
1f1031fe 152#define RExC_paren_name_list (pRExC_state->paren_name_list)
3dab1dad 153#endif
830247a4
IZ
154} RExC_state_t;
155
e2509266 156#define RExC_flags (pRExC_state->flags)
830247a4 157#define RExC_precomp (pRExC_state->precomp)
288b8c02 158#define RExC_rx_sv (pRExC_state->rx_sv)
830247a4 159#define RExC_rx (pRExC_state->rx)
f8fc2ecf 160#define RExC_rxi (pRExC_state->rxi)
fac92740 161#define RExC_start (pRExC_state->start)
830247a4
IZ
162#define RExC_end (pRExC_state->end)
163#define RExC_parse (pRExC_state->parse)
164#define RExC_whilem_seen (pRExC_state->whilem_seen)
7122b237
YO
165#ifdef RE_TRACK_PATTERN_OFFSETS
166#define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
167#endif
830247a4 168#define RExC_emit (pRExC_state->emit)
fac92740 169#define RExC_emit_start (pRExC_state->emit_start)
3b57cd43 170#define RExC_emit_bound (pRExC_state->emit_bound)
830247a4
IZ
171#define RExC_naughty (pRExC_state->naughty)
172#define RExC_sawback (pRExC_state->sawback)
173#define RExC_seen (pRExC_state->seen)
174#define RExC_size (pRExC_state->size)
175#define RExC_npar (pRExC_state->npar)
e2e6a0f1 176#define RExC_nestroot (pRExC_state->nestroot)
830247a4
IZ
177#define RExC_extralen (pRExC_state->extralen)
178#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
179#define RExC_seen_evals (pRExC_state->seen_evals)
1aa99e6b 180#define RExC_utf8 (pRExC_state->utf8)
02daf0ab 181#define RExC_orig_utf8 (pRExC_state->orig_utf8)
40d049e4
YO
182#define RExC_open_parens (pRExC_state->open_parens)
183#define RExC_close_parens (pRExC_state->close_parens)
184#define RExC_opend (pRExC_state->opend)
81714fb9 185#define RExC_paren_names (pRExC_state->paren_names)
40d049e4
YO
186#define RExC_recurse (pRExC_state->recurse)
187#define RExC_recurse_count (pRExC_state->recurse_count)
b57e4118 188#define RExC_in_lookbehind (pRExC_state->in_lookbehind)
830247a4 189
cde0cee5 190
a687059c
LW
191#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
192#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
193 ((*s) == '{' && regcurly(s)))
a687059c 194
35c8bce7
LW
195#ifdef SPSTART
196#undef SPSTART /* dratted cpp namespace... */
197#endif
a687059c
LW
198/*
199 * Flags to be passed up and down.
200 */
a687059c 201#define WORST 0 /* Worst case. */
a3b492c3 202#define HASWIDTH 0x01 /* Known to match non-null strings. */
fda99bee
KW
203
204/* Simple enough to be STAR/PLUS operand, in an EXACT node must be a single
d7b56a3c 205 * character, and if utf8, must be invariant. Note that this is not the same thing as REGNODE_SIMPLE */
fda99bee 206#define SIMPLE 0x02
a3b492c3
YO
207#define SPSTART 0x04 /* Starts with * or +. */
208#define TRYAGAIN 0x08 /* Weeded out a declaration. */
209#define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
a687059c 210
3dab1dad
YO
211#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
212
07be1b83
YO
213/* whether trie related optimizations are enabled */
214#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
215#define TRIE_STUDY_OPT
786e8c11 216#define FULL_TRIE_STUDY
07be1b83
YO
217#define TRIE_STCLASS
218#endif
1de06328
YO
219
220
40d049e4
YO
221
222#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
223#define PBITVAL(paren) (1 << ((paren) & 7))
224#define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
225#define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
226#define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
227
bbd61b5f
KW
228/* If not already in utf8, do a longjmp back to the beginning */
229#define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
230#define REQUIRE_UTF8 STMT_START { \
231 if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
232 } STMT_END
40d049e4 233
1de06328
YO
234/* About scan_data_t.
235
236 During optimisation we recurse through the regexp program performing
237 various inplace (keyhole style) optimisations. In addition study_chunk
238 and scan_commit populate this data structure with information about
239 what strings MUST appear in the pattern. We look for the longest
3b753521 240 string that must appear at a fixed location, and we look for the
1de06328
YO
241 longest string that may appear at a floating location. So for instance
242 in the pattern:
243
244 /FOO[xX]A.*B[xX]BAR/
245
246 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
247 strings (because they follow a .* construct). study_chunk will identify
248 both FOO and BAR as being the longest fixed and floating strings respectively.
249
250 The strings can be composites, for instance
251
252 /(f)(o)(o)/
253
254 will result in a composite fixed substring 'foo'.
255
256 For each string some basic information is maintained:
257
258 - offset or min_offset
259 This is the position the string must appear at, or not before.
260 It also implicitly (when combined with minlenp) tells us how many
3b753521
FN
261 characters must match before the string we are searching for.
262 Likewise when combined with minlenp and the length of the string it
1de06328
YO
263 tells us how many characters must appear after the string we have
264 found.
265
266 - max_offset
267 Only used for floating strings. This is the rightmost point that
3b753521 268 the string can appear at. If set to I32 max it indicates that the
1de06328
YO
269 string can occur infinitely far to the right.
270
271 - minlenp
272 A pointer to the minimum length of the pattern that the string
273 was found inside. This is important as in the case of positive
274 lookahead or positive lookbehind we can have multiple patterns
275 involved. Consider
276
277 /(?=FOO).*F/
278
279 The minimum length of the pattern overall is 3, the minimum length
280 of the lookahead part is 3, but the minimum length of the part that
281 will actually match is 1. So 'FOO's minimum length is 3, but the
282 minimum length for the F is 1. This is important as the minimum length
283 is used to determine offsets in front of and behind the string being
284 looked for. Since strings can be composites this is the length of the
486ec47a 285 pattern at the time it was committed with a scan_commit. Note that
1de06328
YO
286 the length is calculated by study_chunk, so that the minimum lengths
287 are not known until the full pattern has been compiled, thus the
288 pointer to the value.
289
290 - lookbehind
291
292 In the case of lookbehind the string being searched for can be
293 offset past the start point of the final matching string.
294 If this value was just blithely removed from the min_offset it would
295 invalidate some of the calculations for how many chars must match
296 before or after (as they are derived from min_offset and minlen and
297 the length of the string being searched for).
298 When the final pattern is compiled and the data is moved from the
299 scan_data_t structure into the regexp structure the information
300 about lookbehind is factored in, with the information that would
301 have been lost precalculated in the end_shift field for the
302 associated string.
303
304 The fields pos_min and pos_delta are used to store the minimum offset
305 and the delta to the maximum offset at the current point in the pattern.
306
307*/
2c2d71f5
JH
308
309typedef struct scan_data_t {
1de06328
YO
310 /*I32 len_min; unused */
311 /*I32 len_delta; unused */
2c2d71f5
JH
312 I32 pos_min;
313 I32 pos_delta;
314 SV *last_found;
1de06328 315 I32 last_end; /* min value, <0 unless valid. */
2c2d71f5
JH
316 I32 last_start_min;
317 I32 last_start_max;
1de06328
YO
318 SV **longest; /* Either &l_fixed, or &l_float. */
319 SV *longest_fixed; /* longest fixed string found in pattern */
320 I32 offset_fixed; /* offset where it starts */
486ec47a 321 I32 *minlen_fixed; /* pointer to the minlen relevant to the string */
1de06328
YO
322 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
323 SV *longest_float; /* longest floating string found in pattern */
324 I32 offset_float_min; /* earliest point in string it can appear */
325 I32 offset_float_max; /* latest point in string it can appear */
486ec47a 326 I32 *minlen_float; /* pointer to the minlen relevant to the string */
1de06328 327 I32 lookbehind_float; /* is the position of the string modified by LB */
2c2d71f5
JH
328 I32 flags;
329 I32 whilem_c;
cb434fcc 330 I32 *last_closep;
653099ff 331 struct regnode_charclass_class *start_class;
2c2d71f5
JH
332} scan_data_t;
333
a687059c 334/*
e50aee73 335 * Forward declarations for pregcomp()'s friends.
a687059c 336 */
a0d0e21e 337
27da23d5 338static const scan_data_t zero_scan_data =
1de06328 339 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
c277df42
IZ
340
341#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
07be1b83
YO
342#define SF_BEFORE_SEOL 0x0001
343#define SF_BEFORE_MEOL 0x0002
c277df42
IZ
344#define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
345#define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
346
09b7f37c
CB
347#ifdef NO_UNARY_PLUS
348# define SF_FIX_SHIFT_EOL (0+2)
349# define SF_FL_SHIFT_EOL (0+4)
350#else
351# define SF_FIX_SHIFT_EOL (+2)
352# define SF_FL_SHIFT_EOL (+4)
353#endif
c277df42
IZ
354
355#define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
356#define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
357
358#define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
359#define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
07be1b83
YO
360#define SF_IS_INF 0x0040
361#define SF_HAS_PAR 0x0080
362#define SF_IN_PAR 0x0100
363#define SF_HAS_EVAL 0x0200
364#define SCF_DO_SUBSTR 0x0400
653099ff
GS
365#define SCF_DO_STCLASS_AND 0x0800
366#define SCF_DO_STCLASS_OR 0x1000
367#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
e1901655 368#define SCF_WHILEM_VISITED_POS 0x2000
c277df42 369
786e8c11 370#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
e2e6a0f1 371#define SCF_SEEN_ACCEPT 0x8000
07be1b83 372
43fead97 373#define UTF cBOOL(RExC_utf8)
a62b1201
KW
374#define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
375#define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
cfaf538b
KW
376#define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
377#define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
378#define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
a62b1201 379
43fead97 380#define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
a0ed51b3 381
ffc61ed2 382#define OOB_UNICODE 12345678
93733859 383#define OOB_NAMEDCLASS -1
b8c5462f 384
a0ed51b3
LW
385#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
386#define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
387
8615cb43 388
b45f050a
JF
389/* length of regex to show in messages that don't mark a position within */
390#define RegexLengthToShowInErrorMessages 127
391
392/*
393 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
394 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
395 * op/pragma/warn/regcomp.
396 */
7253e4e3
RK
397#define MARKER1 "<-- HERE" /* marker as it appears in the description */
398#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
b81d288d 399
7253e4e3 400#define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
b45f050a
JF
401
402/*
403 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
404 * arg. Show regex, up to a maximum length. If it's too long, chop and add
405 * "...".
406 */
58e23c8d 407#define _FAIL(code) STMT_START { \
bfed75c6 408 const char *ellipses = ""; \
ccb2c380
MP
409 IV len = RExC_end - RExC_precomp; \
410 \
411 if (!SIZE_ONLY) \
288b8c02 412 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
413 if (len > RegexLengthToShowInErrorMessages) { \
414 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
415 len = RegexLengthToShowInErrorMessages - 10; \
416 ellipses = "..."; \
417 } \
58e23c8d 418 code; \
ccb2c380 419} STMT_END
8615cb43 420
58e23c8d
YO
421#define FAIL(msg) _FAIL( \
422 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
423 msg, (int)len, RExC_precomp, ellipses))
424
425#define FAIL2(msg,arg) _FAIL( \
426 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
427 arg, (int)len, RExC_precomp, ellipses))
428
b45f050a 429/*
b45f050a
JF
430 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
431 */
ccb2c380 432#define Simple_vFAIL(m) STMT_START { \
a28509cc 433 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
434 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
435 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
436} STMT_END
b45f050a
JF
437
438/*
439 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
440 */
ccb2c380
MP
441#define vFAIL(m) STMT_START { \
442 if (!SIZE_ONLY) \
288b8c02 443 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
444 Simple_vFAIL(m); \
445} STMT_END
b45f050a
JF
446
447/*
448 * Like Simple_vFAIL(), but accepts two arguments.
449 */
ccb2c380 450#define Simple_vFAIL2(m,a1) STMT_START { \
a28509cc 451 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
452 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
453 (int)offset, RExC_precomp, RExC_precomp + offset); \
454} STMT_END
b45f050a
JF
455
456/*
457 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
458 */
ccb2c380
MP
459#define vFAIL2(m,a1) STMT_START { \
460 if (!SIZE_ONLY) \
288b8c02 461 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
462 Simple_vFAIL2(m, a1); \
463} STMT_END
b45f050a
JF
464
465
466/*
467 * Like Simple_vFAIL(), but accepts three arguments.
468 */
ccb2c380 469#define Simple_vFAIL3(m, a1, a2) STMT_START { \
a28509cc 470 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
471 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
472 (int)offset, RExC_precomp, RExC_precomp + offset); \
473} STMT_END
b45f050a
JF
474
475/*
476 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
477 */
ccb2c380
MP
478#define vFAIL3(m,a1,a2) STMT_START { \
479 if (!SIZE_ONLY) \
288b8c02 480 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
481 Simple_vFAIL3(m, a1, a2); \
482} STMT_END
b45f050a
JF
483
484/*
485 * Like Simple_vFAIL(), but accepts four arguments.
486 */
ccb2c380 487#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
a28509cc 488 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
489 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
490 (int)offset, RExC_precomp, RExC_precomp + offset); \
491} STMT_END
b45f050a 492
668c081a 493#define ckWARNreg(loc,m) STMT_START { \
a28509cc 494 const IV offset = loc - RExC_precomp; \
f10f4c18
NC
495 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
496 (int)offset, RExC_precomp, RExC_precomp + offset); \
ccb2c380
MP
497} STMT_END
498
668c081a 499#define ckWARNregdep(loc,m) STMT_START { \
a28509cc 500 const IV offset = loc - RExC_precomp; \
d1d15184 501 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
f10f4c18
NC
502 m REPORT_LOCATION, \
503 (int)offset, RExC_precomp, RExC_precomp + offset); \
ccb2c380
MP
504} STMT_END
505
668c081a 506#define ckWARN2reg(loc, m, a1) STMT_START { \
a28509cc 507 const IV offset = loc - RExC_precomp; \
668c081a 508 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
ccb2c380
MP
509 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
510} STMT_END
511
512#define vWARN3(loc, m, a1, a2) STMT_START { \
a28509cc 513 const IV offset = loc - RExC_precomp; \
ccb2c380
MP
514 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
515 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
516} STMT_END
517
668c081a
NC
518#define ckWARN3reg(loc, m, a1, a2) STMT_START { \
519 const IV offset = loc - RExC_precomp; \
520 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
521 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
522} STMT_END
523
ccb2c380 524#define vWARN4(loc, m, a1, a2, a3) STMT_START { \
a28509cc 525 const IV offset = loc - RExC_precomp; \
ccb2c380
MP
526 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
527 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
528} STMT_END
529
668c081a
NC
530#define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
531 const IV offset = loc - RExC_precomp; \
532 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
533 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
534} STMT_END
535
ccb2c380 536#define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
a28509cc 537 const IV offset = loc - RExC_precomp; \
ccb2c380
MP
538 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
539 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
540} STMT_END
9d1d55b5 541
8615cb43 542
cd439c50 543/* Allow for side effects in s */
ccb2c380
MP
544#define REGC(c,s) STMT_START { \
545 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
546} STMT_END
cd439c50 547
fac92740
MJD
548/* Macros for recording node offsets. 20001227 mjd@plover.com
549 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
550 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
551 * Element 0 holds the number n.
07be1b83 552 * Position is 1 indexed.
fac92740 553 */
7122b237
YO
554#ifndef RE_TRACK_PATTERN_OFFSETS
555#define Set_Node_Offset_To_R(node,byte)
556#define Set_Node_Offset(node,byte)
557#define Set_Cur_Node_Offset
558#define Set_Node_Length_To_R(node,len)
559#define Set_Node_Length(node,len)
560#define Set_Node_Cur_Length(node)
561#define Node_Offset(n)
562#define Node_Length(n)
563#define Set_Node_Offset_Length(node,offset,len)
564#define ProgLen(ri) ri->u.proglen
565#define SetProgLen(ri,x) ri->u.proglen = x
566#else
567#define ProgLen(ri) ri->u.offsets[0]
568#define SetProgLen(ri,x) ri->u.offsets[0] = x
ccb2c380
MP
569#define Set_Node_Offset_To_R(node,byte) STMT_START { \
570 if (! SIZE_ONLY) { \
571 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
2a49f0f5 572 __LINE__, (int)(node), (int)(byte))); \
ccb2c380 573 if((node) < 0) { \
551405c4 574 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
ccb2c380
MP
575 } else { \
576 RExC_offsets[2*(node)-1] = (byte); \
577 } \
578 } \
579} STMT_END
580
581#define Set_Node_Offset(node,byte) \
582 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
583#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
584
585#define Set_Node_Length_To_R(node,len) STMT_START { \
586 if (! SIZE_ONLY) { \
587 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
551405c4 588 __LINE__, (int)(node), (int)(len))); \
ccb2c380 589 if((node) < 0) { \
551405c4 590 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
ccb2c380
MP
591 } else { \
592 RExC_offsets[2*(node)] = (len); \
593 } \
594 } \
595} STMT_END
596
597#define Set_Node_Length(node,len) \
598 Set_Node_Length_To_R((node)-RExC_emit_start, len)
599#define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
600#define Set_Node_Cur_Length(node) \
601 Set_Node_Length(node, RExC_parse - parse_start)
fac92740
MJD
602
603/* Get offsets and lengths */
604#define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
605#define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
606
07be1b83
YO
607#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
608 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
609 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
610} STMT_END
7122b237 611#endif
07be1b83
YO
612
613#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
614#define EXPERIMENTAL_INPLACESCAN
f427392e 615#endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
07be1b83 616
304ee84b
YO
617#define DEBUG_STUDYDATA(str,data,depth) \
618DEBUG_OPTIMISE_MORE_r(if(data){ \
1de06328 619 PerlIO_printf(Perl_debug_log, \
304ee84b
YO
620 "%*s" str "Pos:%"IVdf"/%"IVdf \
621 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
1de06328
YO
622 (int)(depth)*2, "", \
623 (IV)((data)->pos_min), \
624 (IV)((data)->pos_delta), \
304ee84b 625 (UV)((data)->flags), \
1de06328 626 (IV)((data)->whilem_c), \
304ee84b
YO
627 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
628 is_inf ? "INF " : "" \
1de06328
YO
629 ); \
630 if ((data)->last_found) \
631 PerlIO_printf(Perl_debug_log, \
632 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
633 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
634 SvPVX_const((data)->last_found), \
635 (IV)((data)->last_end), \
636 (IV)((data)->last_start_min), \
637 (IV)((data)->last_start_max), \
638 ((data)->longest && \
639 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
640 SvPVX_const((data)->longest_fixed), \
641 (IV)((data)->offset_fixed), \
642 ((data)->longest && \
643 (data)->longest==&((data)->longest_float)) ? "*" : "", \
644 SvPVX_const((data)->longest_float), \
645 (IV)((data)->offset_float_min), \
646 (IV)((data)->offset_float_max) \
647 ); \
648 PerlIO_printf(Perl_debug_log,"\n"); \
649});
650
acfe0abc 651static void clear_re(pTHX_ void *r);
4327152a 652
653099ff 653/* Mark that we cannot extend a found fixed substring at this point.
786e8c11 654 Update the longest found anchored substring and the longest found
653099ff
GS
655 floating substrings if needed. */
656
4327152a 657STATIC void
304ee84b 658S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
c277df42 659{
e1ec3a88
AL
660 const STRLEN l = CHR_SVLEN(data->last_found);
661 const STRLEN old_l = CHR_SVLEN(*data->longest);
1de06328 662 GET_RE_DEBUG_FLAGS_DECL;
b81d288d 663
7918f24d
NC
664 PERL_ARGS_ASSERT_SCAN_COMMIT;
665
c277df42 666 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
6b43b216 667 SvSetMagicSV(*data->longest, data->last_found);
c277df42
IZ
668 if (*data->longest == data->longest_fixed) {
669 data->offset_fixed = l ? data->last_start_min : data->pos_min;
670 if (data->flags & SF_BEFORE_EOL)
b81d288d 671 data->flags
c277df42
IZ
672 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
673 else
674 data->flags &= ~SF_FIX_BEFORE_EOL;
1de06328
YO
675 data->minlen_fixed=minlenp;
676 data->lookbehind_fixed=0;
a0ed51b3 677 }
304ee84b 678 else { /* *data->longest == data->longest_float */
c277df42 679 data->offset_float_min = l ? data->last_start_min : data->pos_min;
b81d288d
AB
680 data->offset_float_max = (l
681 ? data->last_start_max
c277df42 682 : data->pos_min + data->pos_delta);
304ee84b 683 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
9051bda5 684 data->offset_float_max = I32_MAX;
c277df42 685 if (data->flags & SF_BEFORE_EOL)
b81d288d 686 data->flags
c277df42
IZ
687 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
688 else
689 data->flags &= ~SF_FL_BEFORE_EOL;
1de06328
YO
690 data->minlen_float=minlenp;
691 data->lookbehind_float=0;
c277df42
IZ
692 }
693 }
694 SvCUR_set(data->last_found, 0);
0eda9292 695 {
a28509cc 696 SV * const sv = data->last_found;
097eb12c
AL
697 if (SvUTF8(sv) && SvMAGICAL(sv)) {
698 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
699 if (mg)
700 mg->mg_len = 0;
701 }
0eda9292 702 }
c277df42
IZ
703 data->last_end = -1;
704 data->flags &= ~SF_BEFORE_EOL;
bcdf7404 705 DEBUG_STUDYDATA("commit: ",data,0);
c277df42
IZ
706}
707
653099ff
GS
708/* Can match anything (initialization) */
709STATIC void
097eb12c 710S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
653099ff 711{
7918f24d
NC
712 PERL_ARGS_ASSERT_CL_ANYTHING;
713
653099ff 714 ANYOF_CLASS_ZERO(cl);
f8bef550 715 ANYOF_BITMAP_SETALL(cl);
11454c59 716 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL|ANYOF_LOC_NONBITMAP_FOLD|ANYOF_NON_UTF8_LATIN1_ALL;
653099ff
GS
717 if (LOC)
718 cl->flags |= ANYOF_LOCALE;
719}
720
721/* Can match anything (initialization) */
722STATIC int
5f66b61c 723S_cl_is_anything(const struct regnode_charclass_class *cl)
653099ff
GS
724{
725 int value;
726
7918f24d
NC
727 PERL_ARGS_ASSERT_CL_IS_ANYTHING;
728
aaa51d5e 729 for (value = 0; value <= ANYOF_MAX; value += 2)
653099ff
GS
730 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
731 return 1;
1aa99e6b
IH
732 if (!(cl->flags & ANYOF_UNICODE_ALL))
733 return 0;
10edeb5d 734 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
f8bef550 735 return 0;
653099ff
GS
736 return 1;
737}
738
739/* Can match anything (initialization) */
740STATIC void
097eb12c 741S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
653099ff 742{
7918f24d
NC
743 PERL_ARGS_ASSERT_CL_INIT;
744
8ecf7187 745 Zero(cl, 1, struct regnode_charclass_class);
653099ff 746 cl->type = ANYOF;
830247a4 747 cl_anything(pRExC_state, cl);
653099ff
GS
748}
749
750STATIC void
097eb12c 751S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
653099ff 752{
7918f24d
NC
753 PERL_ARGS_ASSERT_CL_INIT_ZERO;
754
8ecf7187 755 Zero(cl, 1, struct regnode_charclass_class);
653099ff 756 cl->type = ANYOF;
830247a4 757 cl_anything(pRExC_state, cl);
653099ff
GS
758 if (LOC)
759 cl->flags |= ANYOF_LOCALE;
760}
761
762/* 'And' a given class with another one. Can create false positives */
763/* We assume that cl is not inverted */
764STATIC void
5f66b61c 765S_cl_and(struct regnode_charclass_class *cl,
a28509cc 766 const struct regnode_charclass_class *and_with)
653099ff 767{
7918f24d 768 PERL_ARGS_ASSERT_CL_AND;
40d049e4
YO
769
770 assert(and_with->type == ANYOF);
1e6ade67
KW
771
772 if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
773 && !(ANYOF_CLASS_TEST_ANY_SET(cl))
653099ff 774 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
39065660
KW
775 && !(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
776 && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) {
653099ff
GS
777 int i;
778
779 if (and_with->flags & ANYOF_INVERT)
780 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
781 cl->bitmap[i] &= ~and_with->bitmap[i];
782 else
783 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
784 cl->bitmap[i] &= and_with->bitmap[i];
785 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
786 if (!(and_with->flags & ANYOF_EOS))
787 cl->flags &= ~ANYOF_EOS;
1aa99e6b 788
39065660
KW
789 if (!(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD))
790 cl->flags &= ~ANYOF_LOC_NONBITMAP_FOLD;
11454c59
KW
791 if (!(and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL))
792 cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
8951c461 793
3ff7ceb3 794 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_NONBITMAP &&
14ebb1a2 795 !(and_with->flags & ANYOF_INVERT)) {
1aa99e6b 796 cl->flags &= ~ANYOF_UNICODE_ALL;
ef87b810
KW
797 cl->flags |= and_with->flags & ANYOF_NONBITMAP; /* field is 2 bits; use
798 only the one(s)
799 actually set */
1aa99e6b
IH
800 ARG_SET(cl, ARG(and_with));
801 }
14ebb1a2
JH
802 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
803 !(and_with->flags & ANYOF_INVERT))
1aa99e6b 804 cl->flags &= ~ANYOF_UNICODE_ALL;
3ff7ceb3 805 if (!(and_with->flags & (ANYOF_NONBITMAP|ANYOF_UNICODE_ALL)) &&
14ebb1a2 806 !(and_with->flags & ANYOF_INVERT))
3ff7ceb3 807 cl->flags &= ~ANYOF_NONBITMAP;
653099ff
GS
808}
809
810/* 'OR' a given class with another one. Can create false positives */
811/* We assume that cl is not inverted */
812STATIC void
097eb12c 813S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
653099ff 814{
7918f24d
NC
815 PERL_ARGS_ASSERT_CL_OR;
816
653099ff
GS
817 if (or_with->flags & ANYOF_INVERT) {
818 /* We do not use
819 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
820 * <= (B1 | !B2) | (CL1 | !CL2)
821 * which is wasteful if CL2 is small, but we ignore CL2:
822 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
823 * XXXX Can we handle case-fold? Unclear:
824 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
825 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
826 */
827 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
39065660
KW
828 && !(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
829 && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD) ) {
653099ff
GS
830 int i;
831
832 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
833 cl->bitmap[i] |= ~or_with->bitmap[i];
834 } /* XXXX: logic is complicated otherwise */
835 else {
830247a4 836 cl_anything(pRExC_state, cl);
653099ff
GS
837 }
838 } else {
839 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
840 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
39065660
KW
841 && (!(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
842 || (cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) ) {
653099ff
GS
843 int i;
844
845 /* OR char bitmap and class bitmap separately */
846 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
847 cl->bitmap[i] |= or_with->bitmap[i];
1e6ade67 848 if (ANYOF_CLASS_TEST_ANY_SET(or_with)) {
653099ff
GS
849 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
850 cl->classflags[i] |= or_with->classflags[i];
851 cl->flags |= ANYOF_CLASS;
852 }
853 }
854 else { /* XXXX: logic is complicated, leave it along for a moment. */
830247a4 855 cl_anything(pRExC_state, cl);
653099ff
GS
856 }
857 }
858 if (or_with->flags & ANYOF_EOS)
859 cl->flags |= ANYOF_EOS;
11454c59
KW
860 if (!(or_with->flags & ANYOF_NON_UTF8_LATIN1_ALL))
861 cl->flags |= ANYOF_NON_UTF8_LATIN1_ALL;
1aa99e6b 862
39065660
KW
863 if (or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
864 cl->flags |= ANYOF_LOC_NONBITMAP_FOLD;
8951c461 865
9826f543
KW
866 /* If both nodes match something outside the bitmap, but what they match
867 * outside is not the same pointer, and hence not easily compared, give up
868 * and allow the start class to match everything outside the bitmap */
3ff7ceb3 869 if (cl->flags & ANYOF_NONBITMAP && or_with->flags & ANYOF_NONBITMAP &&
1aa99e6b
IH
870 ARG(cl) != ARG(or_with)) {
871 cl->flags |= ANYOF_UNICODE_ALL;
1aa99e6b 872 }
9826f543 873
1aa99e6b
IH
874 if (or_with->flags & ANYOF_UNICODE_ALL) {
875 cl->flags |= ANYOF_UNICODE_ALL;
1aa99e6b 876 }
653099ff
GS
877}
878
a3621e74
YO
879#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
880#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
881#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
882#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
883
3dab1dad
YO
884
885#ifdef DEBUGGING
07be1b83 886/*
2b8b4781
NC
887 dump_trie(trie,widecharmap,revcharmap)
888 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
889 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
3dab1dad
YO
890
891 These routines dump out a trie in a somewhat readable format.
07be1b83
YO
892 The _interim_ variants are used for debugging the interim
893 tables that are used to generate the final compressed
894 representation which is what dump_trie expects.
895
486ec47a 896 Part of the reason for their existence is to provide a form
3dab1dad 897 of documentation as to how the different representations function.
07be1b83
YO
898
899*/
3dab1dad
YO
900
901/*
3dab1dad
YO
902 Dumps the final compressed table form of the trie to Perl_debug_log.
903 Used for debugging make_trie().
904*/
b9a59e08 905
3dab1dad 906STATIC void
2b8b4781
NC
907S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
908 AV *revcharmap, U32 depth)
3dab1dad
YO
909{
910 U32 state;
ab3bbdeb 911 SV *sv=sv_newmortal();
55eed653 912 int colwidth= widecharmap ? 6 : 4;
2e64971a 913 U16 word;
3dab1dad
YO
914 GET_RE_DEBUG_FLAGS_DECL;
915
7918f24d 916 PERL_ARGS_ASSERT_DUMP_TRIE;
ab3bbdeb 917
3dab1dad
YO
918 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
919 (int)depth * 2 + 2,"",
920 "Match","Base","Ofs" );
921
922 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2b8b4781 923 SV ** const tmp = av_fetch( revcharmap, state, 0);
3dab1dad 924 if ( tmp ) {
ab3bbdeb
YO
925 PerlIO_printf( Perl_debug_log, "%*s",
926 colwidth,
ddc5bc0f 927 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
928 PL_colors[0], PL_colors[1],
929 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
930 PERL_PV_ESCAPE_FIRSTCHAR
931 )
932 );
3dab1dad
YO
933 }
934 }
935 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
936 (int)depth * 2 + 2,"");
937
938 for( state = 0 ; state < trie->uniquecharcount ; state++ )
ab3bbdeb 939 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
3dab1dad
YO
940 PerlIO_printf( Perl_debug_log, "\n");
941
1e2e3d02 942 for( state = 1 ; state < trie->statecount ; state++ ) {
be8e71aa 943 const U32 base = trie->states[ state ].trans.base;
3dab1dad
YO
944
945 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
946
947 if ( trie->states[ state ].wordnum ) {
948 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
949 } else {
950 PerlIO_printf( Perl_debug_log, "%6s", "" );
951 }
952
953 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
954
955 if ( base ) {
956 U32 ofs = 0;
957
958 while( ( base + ofs < trie->uniquecharcount ) ||
959 ( base + ofs - trie->uniquecharcount < trie->lasttrans
960 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
961 ofs++;
962
963 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
964
965 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
966 if ( ( base + ofs >= trie->uniquecharcount ) &&
967 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
968 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
969 {
ab3bbdeb
YO
970 PerlIO_printf( Perl_debug_log, "%*"UVXf,
971 colwidth,
3dab1dad
YO
972 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
973 } else {
ab3bbdeb 974 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
3dab1dad
YO
975 }
976 }
977
978 PerlIO_printf( Perl_debug_log, "]");
979
980 }
981 PerlIO_printf( Perl_debug_log, "\n" );
982 }
2e64971a
DM
983 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
984 for (word=1; word <= trie->wordcount; word++) {
985 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
986 (int)word, (int)(trie->wordinfo[word].prev),
987 (int)(trie->wordinfo[word].len));
988 }
989 PerlIO_printf(Perl_debug_log, "\n" );
3dab1dad
YO
990}
991/*
3dab1dad
YO
992 Dumps a fully constructed but uncompressed trie in list form.
993 List tries normally only are used for construction when the number of
994 possible chars (trie->uniquecharcount) is very high.
995 Used for debugging make_trie().
996*/
997STATIC void
55eed653 998S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
999 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1000 U32 depth)
3dab1dad
YO
1001{
1002 U32 state;
ab3bbdeb 1003 SV *sv=sv_newmortal();
55eed653 1004 int colwidth= widecharmap ? 6 : 4;
3dab1dad 1005 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1006
1007 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1008
3dab1dad 1009 /* print out the table precompression. */
ab3bbdeb
YO
1010 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1011 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1012 "------:-----+-----------------\n" );
3dab1dad
YO
1013
1014 for( state=1 ; state < next_alloc ; state ++ ) {
1015 U16 charid;
1016
ab3bbdeb 1017 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
3dab1dad
YO
1018 (int)depth * 2 + 2,"", (UV)state );
1019 if ( ! trie->states[ state ].wordnum ) {
1020 PerlIO_printf( Perl_debug_log, "%5s| ","");
1021 } else {
1022 PerlIO_printf( Perl_debug_log, "W%4x| ",
1023 trie->states[ state ].wordnum
1024 );
1025 }
1026 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2b8b4781 1027 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
ab3bbdeb
YO
1028 if ( tmp ) {
1029 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1030 colwidth,
ddc5bc0f 1031 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1032 PL_colors[0], PL_colors[1],
1033 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1034 PERL_PV_ESCAPE_FIRSTCHAR
1035 ) ,
1e2e3d02
YO
1036 TRIE_LIST_ITEM(state,charid).forid,
1037 (UV)TRIE_LIST_ITEM(state,charid).newstate
1038 );
1039 if (!(charid % 10))
664e119d
RGS
1040 PerlIO_printf(Perl_debug_log, "\n%*s| ",
1041 (int)((depth * 2) + 14), "");
1e2e3d02 1042 }
ab3bbdeb
YO
1043 }
1044 PerlIO_printf( Perl_debug_log, "\n");
3dab1dad
YO
1045 }
1046}
1047
1048/*
3dab1dad
YO
1049 Dumps a fully constructed but uncompressed trie in table form.
1050 This is the normal DFA style state transition table, with a few
1051 twists to facilitate compression later.
1052 Used for debugging make_trie().
1053*/
1054STATIC void
55eed653 1055S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
1056 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1057 U32 depth)
3dab1dad
YO
1058{
1059 U32 state;
1060 U16 charid;
ab3bbdeb 1061 SV *sv=sv_newmortal();
55eed653 1062 int colwidth= widecharmap ? 6 : 4;
3dab1dad 1063 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1064
1065 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
3dab1dad
YO
1066
1067 /*
1068 print out the table precompression so that we can do a visual check
1069 that they are identical.
1070 */
1071
1072 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1073
1074 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2b8b4781 1075 SV ** const tmp = av_fetch( revcharmap, charid, 0);
3dab1dad 1076 if ( tmp ) {
ab3bbdeb
YO
1077 PerlIO_printf( Perl_debug_log, "%*s",
1078 colwidth,
ddc5bc0f 1079 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1080 PL_colors[0], PL_colors[1],
1081 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1082 PERL_PV_ESCAPE_FIRSTCHAR
1083 )
1084 );
3dab1dad
YO
1085 }
1086 }
1087
1088 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1089
1090 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb 1091 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
3dab1dad
YO
1092 }
1093
1094 PerlIO_printf( Perl_debug_log, "\n" );
1095
1096 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1097
1098 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1099 (int)depth * 2 + 2,"",
1100 (UV)TRIE_NODENUM( state ) );
1101
1102 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb
YO
1103 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1104 if (v)
1105 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1106 else
1107 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
3dab1dad
YO
1108 }
1109 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1110 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1111 } else {
1112 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1113 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1114 }
1115 }
07be1b83 1116}
3dab1dad
YO
1117
1118#endif
1119
2e64971a 1120
786e8c11
YO
1121/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1122 startbranch: the first branch in the whole branch sequence
1123 first : start branch of sequence of branch-exact nodes.
1124 May be the same as startbranch
1125 last : Thing following the last branch.
1126 May be the same as tail.
1127 tail : item following the branch sequence
1128 count : words in the sequence
1129 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1130 depth : indent depth
3dab1dad 1131
786e8c11 1132Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
07be1b83 1133
786e8c11
YO
1134A trie is an N'ary tree where the branches are determined by digital
1135decomposition of the key. IE, at the root node you look up the 1st character and
1136follow that branch repeat until you find the end of the branches. Nodes can be
1137marked as "accepting" meaning they represent a complete word. Eg:
07be1b83 1138
786e8c11 1139 /he|she|his|hers/
72f13be8 1140
786e8c11
YO
1141would convert into the following structure. Numbers represent states, letters
1142following numbers represent valid transitions on the letter from that state, if
1143the number is in square brackets it represents an accepting state, otherwise it
1144will be in parenthesis.
07be1b83 1145
786e8c11
YO
1146 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1147 | |
1148 | (2)
1149 | |
1150 (1) +-i->(6)-+-s->[7]
1151 |
1152 +-s->(3)-+-h->(4)-+-e->[5]
07be1b83 1153
786e8c11
YO
1154 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1155
1156This shows that when matching against the string 'hers' we will begin at state 1
1157read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1158then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1159is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1160single traverse. We store a mapping from accepting to state to which word was
1161matched, and then when we have multiple possibilities we try to complete the
1162rest of the regex in the order in which they occured in the alternation.
1163
1164The only prior NFA like behaviour that would be changed by the TRIE support is
1165the silent ignoring of duplicate alternations which are of the form:
1166
1167 / (DUPE|DUPE) X? (?{ ... }) Y /x
1168
4b714af6 1169Thus EVAL blocks following a trie may be called a different number of times with
786e8c11 1170and without the optimisation. With the optimisations dupes will be silently
486ec47a 1171ignored. This inconsistent behaviour of EVAL type nodes is well established as
786e8c11
YO
1172the following demonstrates:
1173
1174 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1175
1176which prints out 'word' three times, but
1177
1178 'words'=~/(word|word|word)(?{ print $1 })S/
1179
1180which doesnt print it out at all. This is due to other optimisations kicking in.
1181
1182Example of what happens on a structural level:
1183
486ec47a 1184The regexp /(ac|ad|ab)+/ will produce the following debug output:
786e8c11
YO
1185
1186 1: CURLYM[1] {1,32767}(18)
1187 5: BRANCH(8)
1188 6: EXACT <ac>(16)
1189 8: BRANCH(11)
1190 9: EXACT <ad>(16)
1191 11: BRANCH(14)
1192 12: EXACT <ab>(16)
1193 16: SUCCEED(0)
1194 17: NOTHING(18)
1195 18: END(0)
1196
1197This would be optimizable with startbranch=5, first=5, last=16, tail=16
1198and should turn into:
1199
1200 1: CURLYM[1] {1,32767}(18)
1201 5: TRIE(16)
1202 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1203 <ac>
1204 <ad>
1205 <ab>
1206 16: SUCCEED(0)
1207 17: NOTHING(18)
1208 18: END(0)
1209
1210Cases where tail != last would be like /(?foo|bar)baz/:
1211
1212 1: BRANCH(4)
1213 2: EXACT <foo>(8)
1214 4: BRANCH(7)
1215 5: EXACT <bar>(8)
1216 7: TAIL(8)
1217 8: EXACT <baz>(10)
1218 10: END(0)
1219
1220which would be optimizable with startbranch=1, first=1, last=7, tail=8
1221and would end up looking like:
1222
1223 1: TRIE(8)
1224 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1225 <foo>
1226 <bar>
1227 7: TAIL(8)
1228 8: EXACT <baz>(10)
1229 10: END(0)
1230
1231 d = uvuni_to_utf8_flags(d, uv, 0);
1232
1233is the recommended Unicode-aware way of saying
1234
1235 *(d++) = uv;
1236*/
1237
1e2e3d02 1238#define TRIE_STORE_REVCHAR \
786e8c11 1239 STMT_START { \
73031816
NC
1240 if (UTF) { \
1241 SV *zlopp = newSV(2); \
88c9ea1e
CB
1242 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
1243 unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
73031816
NC
1244 SvCUR_set(zlopp, kapow - flrbbbbb); \
1245 SvPOK_on(zlopp); \
1246 SvUTF8_on(zlopp); \
1247 av_push(revcharmap, zlopp); \
1248 } else { \
6bdeddd2 1249 char ooooff = (char)uvc; \
73031816
NC
1250 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
1251 } \
1252 } STMT_END
786e8c11
YO
1253
1254#define TRIE_READ_CHAR STMT_START { \
1255 wordlen++; \
1256 if ( UTF ) { \
1257 if ( folder ) { \
1258 if ( foldlen > 0 ) { \
1259 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1260 foldlen -= len; \
1261 scan += len; \
1262 len = 0; \
1263 } else { \
1264 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1265 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1266 foldlen -= UNISKIP( uvc ); \
1267 scan = foldbuf + UNISKIP( uvc ); \
1268 } \
1269 } else { \
1270 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1271 } \
1272 } else { \
1273 uvc = (U32)*uc; \
1274 len = 1; \
1275 } \
1276} STMT_END
1277
1278
1279
1280#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1281 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
f9003953
NC
1282 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1283 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
786e8c11
YO
1284 } \
1285 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1286 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1287 TRIE_LIST_CUR( state )++; \
1288} STMT_END
07be1b83 1289
786e8c11
YO
1290#define TRIE_LIST_NEW(state) STMT_START { \
1291 Newxz( trie->states[ state ].trans.list, \
1292 4, reg_trie_trans_le ); \
1293 TRIE_LIST_CUR( state ) = 1; \
1294 TRIE_LIST_LEN( state ) = 4; \
1295} STMT_END
07be1b83 1296
786e8c11
YO
1297#define TRIE_HANDLE_WORD(state) STMT_START { \
1298 U16 dupe= trie->states[ state ].wordnum; \
1299 regnode * const noper_next = regnext( noper ); \
1300 \
786e8c11
YO
1301 DEBUG_r({ \
1302 /* store the word for dumping */ \
1303 SV* tmp; \
1304 if (OP(noper) != NOTHING) \
740cce10 1305 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
786e8c11 1306 else \
740cce10 1307 tmp = newSVpvn_utf8( "", 0, UTF ); \
2b8b4781 1308 av_push( trie_words, tmp ); \
786e8c11
YO
1309 }); \
1310 \
1311 curword++; \
2e64971a
DM
1312 trie->wordinfo[curword].prev = 0; \
1313 trie->wordinfo[curword].len = wordlen; \
1314 trie->wordinfo[curword].accept = state; \
786e8c11
YO
1315 \
1316 if ( noper_next < tail ) { \
1317 if (!trie->jump) \
c944940b 1318 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
7f69552c 1319 trie->jump[curword] = (U16)(noper_next - convert); \
786e8c11
YO
1320 if (!jumper) \
1321 jumper = noper_next; \
1322 if (!nextbranch) \
1323 nextbranch= regnext(cur); \
1324 } \
1325 \
1326 if ( dupe ) { \
2e64971a
DM
1327 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
1328 /* chain, so that when the bits of chain are later */\
1329 /* linked together, the dups appear in the chain */\
1330 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1331 trie->wordinfo[dupe].prev = curword; \
786e8c11
YO
1332 } else { \
1333 /* we haven't inserted this word yet. */ \
1334 trie->states[ state ].wordnum = curword; \
1335 } \
1336} STMT_END
07be1b83 1337
3dab1dad 1338
786e8c11
YO
1339#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1340 ( ( base + charid >= ucharcount \
1341 && base + charid < ubound \
1342 && state == trie->trans[ base - ucharcount + charid ].check \
1343 && trie->trans[ base - ucharcount + charid ].next ) \
1344 ? trie->trans[ base - ucharcount + charid ].next \
1345 : ( state==1 ? special : 0 ) \
1346 )
3dab1dad 1347
786e8c11
YO
1348#define MADE_TRIE 1
1349#define MADE_JUMP_TRIE 2
1350#define MADE_EXACT_TRIE 4
3dab1dad 1351
a3621e74 1352STATIC I32
786e8c11 1353S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
a3621e74 1354{
27da23d5 1355 dVAR;
a3621e74
YO
1356 /* first pass, loop through and scan words */
1357 reg_trie_data *trie;
55eed653 1358 HV *widecharmap = NULL;
2b8b4781 1359 AV *revcharmap = newAV();
a3621e74 1360 regnode *cur;
9f7f3913 1361 const U32 uniflags = UTF8_ALLOW_DEFAULT;
a3621e74
YO
1362 STRLEN len = 0;
1363 UV uvc = 0;
1364 U16 curword = 0;
1365 U32 next_alloc = 0;
786e8c11
YO
1366 regnode *jumper = NULL;
1367 regnode *nextbranch = NULL;
7f69552c 1368 regnode *convert = NULL;
2e64971a 1369 U32 *prev_states; /* temp array mapping each state to previous one */
a3621e74 1370 /* we just use folder as a flag in utf8 */
1e696034 1371 const U8 * folder = NULL;
a3621e74 1372
2b8b4781
NC
1373#ifdef DEBUGGING
1374 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1375 AV *trie_words = NULL;
1376 /* along with revcharmap, this only used during construction but both are
1377 * useful during debugging so we store them in the struct when debugging.
8e11feef 1378 */
2b8b4781
NC
1379#else
1380 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
3dab1dad 1381 STRLEN trie_charcount=0;
3dab1dad 1382#endif
2b8b4781 1383 SV *re_trie_maxbuff;
a3621e74 1384 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1385
1386 PERL_ARGS_ASSERT_MAKE_TRIE;
72f13be8
YO
1387#ifndef DEBUGGING
1388 PERL_UNUSED_ARG(depth);
1389#endif
a3621e74 1390
1e696034
KW
1391 switch (flags) {
1392 case EXACTFU: folder = PL_fold_latin1; break;
1393 case EXACTF: folder = PL_fold; break;
1394 case EXACTFL: folder = PL_fold_locale; break;
1395 }
1396
c944940b 1397 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
a3621e74 1398 trie->refcount = 1;
3dab1dad 1399 trie->startstate = 1;
786e8c11 1400 trie->wordcount = word_count;
f8fc2ecf 1401 RExC_rxi->data->data[ data_slot ] = (void*)trie;
c944940b 1402 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
3dab1dad 1403 if (!(UTF && folder))
c944940b 1404 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2e64971a
DM
1405 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1406 trie->wordcount+1, sizeof(reg_trie_wordinfo));
1407
a3621e74 1408 DEBUG_r({
2b8b4781 1409 trie_words = newAV();
a3621e74 1410 });
a3621e74 1411
0111c4fd 1412 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
a3621e74 1413 if (!SvIOK(re_trie_maxbuff)) {
0111c4fd 1414 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
a3621e74 1415 }
3dab1dad
YO
1416 DEBUG_OPTIMISE_r({
1417 PerlIO_printf( Perl_debug_log,
786e8c11 1418 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
3dab1dad
YO
1419 (int)depth * 2 + 2, "",
1420 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
786e8c11 1421 REG_NODE_NUM(last), REG_NODE_NUM(tail),
85c3142d 1422 (int)depth);
3dab1dad 1423 });
7f69552c
YO
1424
1425 /* Find the node we are going to overwrite */
1426 if ( first == startbranch && OP( last ) != BRANCH ) {
1427 /* whole branch chain */
1428 convert = first;
1429 } else {
1430 /* branch sub-chain */
1431 convert = NEXTOPER( first );
1432 }
1433
a3621e74
YO
1434 /* -- First loop and Setup --
1435
1436 We first traverse the branches and scan each word to determine if it
1437 contains widechars, and how many unique chars there are, this is
1438 important as we have to build a table with at least as many columns as we
1439 have unique chars.
1440
1441 We use an array of integers to represent the character codes 0..255
38a44b82 1442 (trie->charmap) and we use a an HV* to store Unicode characters. We use the
a3621e74
YO
1443 native representation of the character value as the key and IV's for the
1444 coded index.
1445
1446 *TODO* If we keep track of how many times each character is used we can
1447 remap the columns so that the table compression later on is more
3b753521 1448 efficient in terms of memory by ensuring the most common value is in the
a3621e74
YO
1449 middle and the least common are on the outside. IMO this would be better
1450 than a most to least common mapping as theres a decent chance the most
1451 common letter will share a node with the least common, meaning the node
486ec47a 1452 will not be compressible. With a middle is most common approach the worst
a3621e74
YO
1453 case is when we have the least common nodes twice.
1454
1455 */
1456
a3621e74 1457 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
c445ea15 1458 regnode * const noper = NEXTOPER( cur );
e1ec3a88 1459 const U8 *uc = (U8*)STRING( noper );
a28509cc 1460 const U8 * const e = uc + STR_LEN( noper );
a3621e74
YO
1461 STRLEN foldlen = 0;
1462 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2af232bd 1463 const U8 *scan = (U8*)NULL;
07be1b83 1464 U32 wordlen = 0; /* required init */
02daf0ab
YO
1465 STRLEN chars = 0;
1466 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
a3621e74 1467
3dab1dad
YO
1468 if (OP(noper) == NOTHING) {
1469 trie->minlen= 0;
1470 continue;
1471 }
02daf0ab
YO
1472 if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
1473 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1474 regardless of encoding */
1475
a3621e74 1476 for ( ; uc < e ; uc += len ) {
3dab1dad 1477 TRIE_CHARCOUNT(trie)++;
a3621e74 1478 TRIE_READ_CHAR;
3dab1dad 1479 chars++;
a3621e74
YO
1480 if ( uvc < 256 ) {
1481 if ( !trie->charmap[ uvc ] ) {
1482 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1483 if ( folder )
1484 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
3dab1dad 1485 TRIE_STORE_REVCHAR;
a3621e74 1486 }
02daf0ab 1487 if ( set_bit ) {
62012aee
KW
1488 /* store the codepoint in the bitmap, and its folded
1489 * equivalent. */
02daf0ab 1490 TRIE_BITMAP_SET(trie,uvc);
0921ee73
T
1491
1492 /* store the folded codepoint */
1493 if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
1494
1495 if ( !UTF ) {
1496 /* store first byte of utf8 representation of
acdf4139
KW
1497 variant codepoints */
1498 if (! UNI_IS_INVARIANT(uvc)) {
1499 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
0921ee73
T
1500 }
1501 }
02daf0ab
YO
1502 set_bit = 0; /* We've done our bit :-) */
1503 }
a3621e74
YO
1504 } else {
1505 SV** svpp;
55eed653
NC
1506 if ( !widecharmap )
1507 widecharmap = newHV();
a3621e74 1508
55eed653 1509 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
a3621e74
YO
1510
1511 if ( !svpp )
e4584336 1512 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
a3621e74
YO
1513
1514 if ( !SvTRUE( *svpp ) ) {
1515 sv_setiv( *svpp, ++trie->uniquecharcount );
3dab1dad 1516 TRIE_STORE_REVCHAR;
a3621e74
YO
1517 }
1518 }
1519 }
3dab1dad
YO
1520 if( cur == first ) {
1521 trie->minlen=chars;
1522 trie->maxlen=chars;
1523 } else if (chars < trie->minlen) {
1524 trie->minlen=chars;
1525 } else if (chars > trie->maxlen) {
1526 trie->maxlen=chars;
1527 }
1528
a3621e74
YO
1529 } /* end first pass */
1530 DEBUG_TRIE_COMPILE_r(
3dab1dad
YO
1531 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1532 (int)depth * 2 + 2,"",
55eed653 1533 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
be8e71aa
YO
1534 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1535 (int)trie->minlen, (int)trie->maxlen )
a3621e74 1536 );
a3621e74
YO
1537
1538 /*
1539 We now know what we are dealing with in terms of unique chars and
1540 string sizes so we can calculate how much memory a naive
0111c4fd
RGS
1541 representation using a flat table will take. If it's over a reasonable
1542 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
a3621e74
YO
1543 conservative but potentially much slower representation using an array
1544 of lists.
1545
1546 At the end we convert both representations into the same compressed
1547 form that will be used in regexec.c for matching with. The latter
1548 is a form that cannot be used to construct with but has memory
1549 properties similar to the list form and access properties similar
1550 to the table form making it both suitable for fast searches and
1551 small enough that its feasable to store for the duration of a program.
1552
1553 See the comment in the code where the compressed table is produced
1554 inplace from the flat tabe representation for an explanation of how
1555 the compression works.
1556
1557 */
1558
1559
2e64971a
DM
1560 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1561 prev_states[1] = 0;
1562
3dab1dad 1563 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
a3621e74
YO
1564 /*
1565 Second Pass -- Array Of Lists Representation
1566
1567 Each state will be represented by a list of charid:state records
1568 (reg_trie_trans_le) the first such element holds the CUR and LEN
1569 points of the allocated array. (See defines above).
1570
1571 We build the initial structure using the lists, and then convert
1572 it into the compressed table form which allows faster lookups
1573 (but cant be modified once converted).
a3621e74
YO
1574 */
1575
a3621e74
YO
1576 STRLEN transcount = 1;
1577
1e2e3d02
YO
1578 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1579 "%*sCompiling trie using list compiler\n",
1580 (int)depth * 2 + 2, ""));
446bd890 1581
c944940b
JH
1582 trie->states = (reg_trie_state *)
1583 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1584 sizeof(reg_trie_state) );
a3621e74
YO
1585 TRIE_LIST_NEW(1);
1586 next_alloc = 2;
1587
1588 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1589
c445ea15
AL
1590 regnode * const noper = NEXTOPER( cur );
1591 U8 *uc = (U8*)STRING( noper );
1592 const U8 * const e = uc + STR_LEN( noper );
1593 U32 state = 1; /* required init */
1594 U16 charid = 0; /* sanity init */
1595 U8 *scan = (U8*)NULL; /* sanity init */
1596 STRLEN foldlen = 0; /* required init */
07be1b83 1597 U32 wordlen = 0; /* required init */
c445ea15
AL
1598 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1599
3dab1dad 1600 if (OP(noper) != NOTHING) {
786e8c11 1601 for ( ; uc < e ; uc += len ) {
c445ea15 1602
786e8c11 1603 TRIE_READ_CHAR;
c445ea15 1604
786e8c11
YO
1605 if ( uvc < 256 ) {
1606 charid = trie->charmap[ uvc ];
c445ea15 1607 } else {
55eed653 1608 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
786e8c11
YO
1609 if ( !svpp ) {
1610 charid = 0;
1611 } else {
1612 charid=(U16)SvIV( *svpp );
1613 }
c445ea15 1614 }
786e8c11
YO
1615 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1616 if ( charid ) {
a3621e74 1617
786e8c11
YO
1618 U16 check;
1619 U32 newstate = 0;
a3621e74 1620
786e8c11
YO
1621 charid--;
1622 if ( !trie->states[ state ].trans.list ) {
1623 TRIE_LIST_NEW( state );
c445ea15 1624 }
786e8c11
YO
1625 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1626 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1627 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1628 break;
1629 }
1630 }
1631 if ( ! newstate ) {
1632 newstate = next_alloc++;
2e64971a 1633 prev_states[newstate] = state;
786e8c11
YO
1634 TRIE_LIST_PUSH( state, charid, newstate );
1635 transcount++;
1636 }
1637 state = newstate;
1638 } else {
1639 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
c445ea15 1640 }
a28509cc 1641 }
c445ea15 1642 }
3dab1dad 1643 TRIE_HANDLE_WORD(state);
a3621e74
YO
1644
1645 } /* end second pass */
1646
1e2e3d02
YO
1647 /* next alloc is the NEXT state to be allocated */
1648 trie->statecount = next_alloc;
c944940b
JH
1649 trie->states = (reg_trie_state *)
1650 PerlMemShared_realloc( trie->states,
1651 next_alloc
1652 * sizeof(reg_trie_state) );
a3621e74 1653
3dab1dad 1654 /* and now dump it out before we compress it */
2b8b4781
NC
1655 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1656 revcharmap, next_alloc,
1657 depth+1)
1e2e3d02 1658 );
a3621e74 1659
c944940b
JH
1660 trie->trans = (reg_trie_trans *)
1661 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
a3621e74
YO
1662 {
1663 U32 state;
a3621e74
YO
1664 U32 tp = 0;
1665 U32 zp = 0;
1666
1667
1668 for( state=1 ; state < next_alloc ; state ++ ) {
1669 U32 base=0;
1670
1671 /*
1672 DEBUG_TRIE_COMPILE_MORE_r(
1673 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1674 );
1675 */
1676
1677 if (trie->states[state].trans.list) {
1678 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1679 U16 maxid=minid;
a28509cc 1680 U16 idx;
a3621e74
YO
1681
1682 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15
AL
1683 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1684 if ( forid < minid ) {
1685 minid=forid;
1686 } else if ( forid > maxid ) {
1687 maxid=forid;
1688 }
a3621e74
YO
1689 }
1690 if ( transcount < tp + maxid - minid + 1) {
1691 transcount *= 2;
c944940b
JH
1692 trie->trans = (reg_trie_trans *)
1693 PerlMemShared_realloc( trie->trans,
446bd890
NC
1694 transcount
1695 * sizeof(reg_trie_trans) );
a3621e74
YO
1696 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1697 }
1698 base = trie->uniquecharcount + tp - minid;
1699 if ( maxid == minid ) {
1700 U32 set = 0;
1701 for ( ; zp < tp ; zp++ ) {
1702 if ( ! trie->trans[ zp ].next ) {
1703 base = trie->uniquecharcount + zp - minid;
1704 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1705 trie->trans[ zp ].check = state;
1706 set = 1;
1707 break;
1708 }
1709 }
1710 if ( !set ) {
1711 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1712 trie->trans[ tp ].check = state;
1713 tp++;
1714 zp = tp;
1715 }
1716 } else {
1717 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15 1718 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
a3621e74
YO
1719 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1720 trie->trans[ tid ].check = state;
1721 }
1722 tp += ( maxid - minid + 1 );
1723 }
1724 Safefree(trie->states[ state ].trans.list);
1725 }
1726 /*
1727 DEBUG_TRIE_COMPILE_MORE_r(
1728 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1729 );
1730 */
1731 trie->states[ state ].trans.base=base;
1732 }
cc601c31 1733 trie->lasttrans = tp + 1;
a3621e74
YO
1734 }
1735 } else {
1736 /*
1737 Second Pass -- Flat Table Representation.
1738
1739 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1740 We know that we will need Charcount+1 trans at most to store the data
1741 (one row per char at worst case) So we preallocate both structures
1742 assuming worst case.
1743
1744 We then construct the trie using only the .next slots of the entry
1745 structs.
1746
3b753521 1747 We use the .check field of the first entry of the node temporarily to
a3621e74
YO
1748 make compression both faster and easier by keeping track of how many non
1749 zero fields are in the node.
1750
1751 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1752 transition.
1753
1754 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1755 number representing the first entry of the node, and state as a
1756 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1757 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1758 are 2 entrys per node. eg:
1759
1760 A B A B
1761 1. 2 4 1. 3 7
1762 2. 0 3 3. 0 5
1763 3. 0 0 5. 0 0
1764 4. 0 0 7. 0 0
1765
1766 The table is internally in the right hand, idx form. However as we also
1767 have to deal with the states array which is indexed by nodenum we have to
1768 use TRIE_NODENUM() to convert.
1769
1770 */
1e2e3d02
YO
1771 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1772 "%*sCompiling trie using table compiler\n",
1773 (int)depth * 2 + 2, ""));
3dab1dad 1774
c944940b
JH
1775 trie->trans = (reg_trie_trans *)
1776 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1777 * trie->uniquecharcount + 1,
1778 sizeof(reg_trie_trans) );
1779 trie->states = (reg_trie_state *)
1780 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1781 sizeof(reg_trie_state) );
a3621e74
YO
1782 next_alloc = trie->uniquecharcount + 1;
1783
3dab1dad 1784
a3621e74
YO
1785 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1786
c445ea15 1787 regnode * const noper = NEXTOPER( cur );
a28509cc
AL
1788 const U8 *uc = (U8*)STRING( noper );
1789 const U8 * const e = uc + STR_LEN( noper );
a3621e74
YO
1790
1791 U32 state = 1; /* required init */
1792
1793 U16 charid = 0; /* sanity init */
1794 U32 accept_state = 0; /* sanity init */
1795 U8 *scan = (U8*)NULL; /* sanity init */
1796
1797 STRLEN foldlen = 0; /* required init */
07be1b83 1798 U32 wordlen = 0; /* required init */
a3621e74
YO
1799 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1800
3dab1dad 1801 if ( OP(noper) != NOTHING ) {
786e8c11 1802 for ( ; uc < e ; uc += len ) {
a3621e74 1803
786e8c11 1804 TRIE_READ_CHAR;
a3621e74 1805
786e8c11
YO
1806 if ( uvc < 256 ) {
1807 charid = trie->charmap[ uvc ];
1808 } else {
55eed653 1809 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
786e8c11 1810 charid = svpp ? (U16)SvIV(*svpp) : 0;
a3621e74 1811 }
786e8c11
YO
1812 if ( charid ) {
1813 charid--;
1814 if ( !trie->trans[ state + charid ].next ) {
1815 trie->trans[ state + charid ].next = next_alloc;
1816 trie->trans[ state ].check++;
2e64971a
DM
1817 prev_states[TRIE_NODENUM(next_alloc)]
1818 = TRIE_NODENUM(state);
786e8c11
YO
1819 next_alloc += trie->uniquecharcount;
1820 }
1821 state = trie->trans[ state + charid ].next;
1822 } else {
1823 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1824 }
1825 /* charid is now 0 if we dont know the char read, or nonzero if we do */
a3621e74 1826 }
a3621e74 1827 }
3dab1dad
YO
1828 accept_state = TRIE_NODENUM( state );
1829 TRIE_HANDLE_WORD(accept_state);
a3621e74
YO
1830
1831 } /* end second pass */
1832
3dab1dad 1833 /* and now dump it out before we compress it */
2b8b4781
NC
1834 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1835 revcharmap,
1836 next_alloc, depth+1));
a3621e74 1837
a3621e74
YO
1838 {
1839 /*
1840 * Inplace compress the table.*
1841
1842 For sparse data sets the table constructed by the trie algorithm will
1843 be mostly 0/FAIL transitions or to put it another way mostly empty.
1844 (Note that leaf nodes will not contain any transitions.)
1845
1846 This algorithm compresses the tables by eliminating most such
1847 transitions, at the cost of a modest bit of extra work during lookup:
1848
1849 - Each states[] entry contains a .base field which indicates the
1850 index in the state[] array wheres its transition data is stored.
1851
3b753521 1852 - If .base is 0 there are no valid transitions from that node.
a3621e74
YO
1853
1854 - If .base is nonzero then charid is added to it to find an entry in
1855 the trans array.
1856
1857 -If trans[states[state].base+charid].check!=state then the
1858 transition is taken to be a 0/Fail transition. Thus if there are fail
1859 transitions at the front of the node then the .base offset will point
1860 somewhere inside the previous nodes data (or maybe even into a node
1861 even earlier), but the .check field determines if the transition is
1862 valid.
1863
786e8c11 1864 XXX - wrong maybe?
a3621e74 1865 The following process inplace converts the table to the compressed
3b753521 1866 table: We first do not compress the root node 1,and mark all its
a3621e74 1867 .check pointers as 1 and set its .base pointer as 1 as well. This
3b753521
FN
1868 allows us to do a DFA construction from the compressed table later,
1869 and ensures that any .base pointers we calculate later are greater
1870 than 0.
a3621e74
YO
1871
1872 - We set 'pos' to indicate the first entry of the second node.
1873
1874 - We then iterate over the columns of the node, finding the first and
1875 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1876 and set the .check pointers accordingly, and advance pos
1877 appropriately and repreat for the next node. Note that when we copy
1878 the next pointers we have to convert them from the original
1879 NODEIDX form to NODENUM form as the former is not valid post
1880 compression.
1881
1882 - If a node has no transitions used we mark its base as 0 and do not
1883 advance the pos pointer.
1884
1885 - If a node only has one transition we use a second pointer into the
1886 structure to fill in allocated fail transitions from other states.
1887 This pointer is independent of the main pointer and scans forward
1888 looking for null transitions that are allocated to a state. When it
1889 finds one it writes the single transition into the "hole". If the
786e8c11 1890 pointer doesnt find one the single transition is appended as normal.
a3621e74
YO
1891
1892 - Once compressed we can Renew/realloc the structures to release the
1893 excess space.
1894
1895 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1896 specifically Fig 3.47 and the associated pseudocode.
1897
1898 demq
1899 */
a3b680e6 1900 const U32 laststate = TRIE_NODENUM( next_alloc );
a28509cc 1901 U32 state, charid;
a3621e74 1902 U32 pos = 0, zp=0;
1e2e3d02 1903 trie->statecount = laststate;
a3621e74
YO
1904
1905 for ( state = 1 ; state < laststate ; state++ ) {
1906 U8 flag = 0;
a28509cc
AL
1907 const U32 stateidx = TRIE_NODEIDX( state );
1908 const U32 o_used = trie->trans[ stateidx ].check;
1909 U32 used = trie->trans[ stateidx ].check;
a3621e74
YO
1910 trie->trans[ stateidx ].check = 0;
1911
1912 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1913 if ( flag || trie->trans[ stateidx + charid ].next ) {
1914 if ( trie->trans[ stateidx + charid ].next ) {
1915 if (o_used == 1) {
1916 for ( ; zp < pos ; zp++ ) {
1917 if ( ! trie->trans[ zp ].next ) {
1918 break;
1919 }
1920 }
1921 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1922 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1923 trie->trans[ zp ].check = state;
1924 if ( ++zp > pos ) pos = zp;
1925 break;
1926 }
1927 used--;
1928 }
1929 if ( !flag ) {
1930 flag = 1;
1931 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1932 }
1933 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1934 trie->trans[ pos ].check = state;
1935 pos++;
1936 }
1937 }
1938 }
cc601c31 1939 trie->lasttrans = pos + 1;
c944940b
JH
1940 trie->states = (reg_trie_state *)
1941 PerlMemShared_realloc( trie->states, laststate
1942 * sizeof(reg_trie_state) );
a3621e74 1943 DEBUG_TRIE_COMPILE_MORE_r(
e4584336 1944 PerlIO_printf( Perl_debug_log,
3dab1dad
YO
1945 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1946 (int)depth * 2 + 2,"",
1947 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
5d7488b2
AL
1948 (IV)next_alloc,
1949 (IV)pos,
a3621e74
YO
1950 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1951 );
1952
1953 } /* end table compress */
1954 }
1e2e3d02
YO
1955 DEBUG_TRIE_COMPILE_MORE_r(
1956 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1957 (int)depth * 2 + 2, "",
1958 (UV)trie->statecount,
1959 (UV)trie->lasttrans)
1960 );
cc601c31 1961 /* resize the trans array to remove unused space */
c944940b
JH
1962 trie->trans = (reg_trie_trans *)
1963 PerlMemShared_realloc( trie->trans, trie->lasttrans
1964 * sizeof(reg_trie_trans) );
a3621e74 1965
3b753521 1966 { /* Modify the program and insert the new TRIE node */
3dab1dad
YO
1967 U8 nodetype =(U8)(flags & 0xFF);
1968 char *str=NULL;
786e8c11 1969
07be1b83 1970#ifdef DEBUGGING
e62cc96a 1971 regnode *optimize = NULL;
7122b237
YO
1972#ifdef RE_TRACK_PATTERN_OFFSETS
1973
b57a0404
JH
1974 U32 mjd_offset = 0;
1975 U32 mjd_nodelen = 0;
7122b237
YO
1976#endif /* RE_TRACK_PATTERN_OFFSETS */
1977#endif /* DEBUGGING */
a3621e74 1978 /*
3dab1dad
YO
1979 This means we convert either the first branch or the first Exact,
1980 depending on whether the thing following (in 'last') is a branch
1981 or not and whther first is the startbranch (ie is it a sub part of
1982 the alternation or is it the whole thing.)
3b753521 1983 Assuming its a sub part we convert the EXACT otherwise we convert
3dab1dad 1984 the whole branch sequence, including the first.
a3621e74 1985 */
3dab1dad 1986 /* Find the node we are going to overwrite */
7f69552c 1987 if ( first != startbranch || OP( last ) == BRANCH ) {
07be1b83 1988 /* branch sub-chain */
3dab1dad 1989 NEXT_OFF( first ) = (U16)(last - first);
7122b237 1990#ifdef RE_TRACK_PATTERN_OFFSETS
07be1b83
YO
1991 DEBUG_r({
1992 mjd_offset= Node_Offset((convert));
1993 mjd_nodelen= Node_Length((convert));
1994 });
7122b237 1995#endif
7f69552c 1996 /* whole branch chain */
7122b237
YO
1997 }
1998#ifdef RE_TRACK_PATTERN_OFFSETS
1999 else {
7f69552c
YO
2000 DEBUG_r({
2001 const regnode *nop = NEXTOPER( convert );
2002 mjd_offset= Node_Offset((nop));
2003 mjd_nodelen= Node_Length((nop));
2004 });
07be1b83
YO
2005 }
2006 DEBUG_OPTIMISE_r(
2007 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2008 (int)depth * 2 + 2, "",
786e8c11 2009 (UV)mjd_offset, (UV)mjd_nodelen)
07be1b83 2010 );
7122b237 2011#endif
3dab1dad
YO
2012 /* But first we check to see if there is a common prefix we can
2013 split out as an EXACT and put in front of the TRIE node. */
2014 trie->startstate= 1;
55eed653 2015 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3dab1dad 2016 U32 state;
1e2e3d02 2017 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
a3621e74 2018 U32 ofs = 0;
8e11feef
RGS
2019 I32 idx = -1;
2020 U32 count = 0;
2021 const U32 base = trie->states[ state ].trans.base;
a3621e74 2022
3dab1dad 2023 if ( trie->states[state].wordnum )
8e11feef 2024 count = 1;
a3621e74 2025
8e11feef 2026 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
cc601c31
YO
2027 if ( ( base + ofs >= trie->uniquecharcount ) &&
2028 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
a3621e74
YO
2029 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2030 {
3dab1dad 2031 if ( ++count > 1 ) {
2b8b4781 2032 SV **tmp = av_fetch( revcharmap, ofs, 0);
07be1b83 2033 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2034 if ( state == 1 ) break;
3dab1dad
YO
2035 if ( count == 2 ) {
2036 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2037 DEBUG_OPTIMISE_r(
8e11feef
RGS
2038 PerlIO_printf(Perl_debug_log,
2039 "%*sNew Start State=%"UVuf" Class: [",
2040 (int)depth * 2 + 2, "",
786e8c11 2041 (UV)state));
be8e71aa 2042 if (idx >= 0) {
2b8b4781 2043 SV ** const tmp = av_fetch( revcharmap, idx, 0);
be8e71aa 2044 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2045
3dab1dad 2046 TRIE_BITMAP_SET(trie,*ch);
8e11feef
RGS
2047 if ( folder )
2048 TRIE_BITMAP_SET(trie, folder[ *ch ]);
3dab1dad 2049 DEBUG_OPTIMISE_r(
f1f66076 2050 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3dab1dad 2051 );
8e11feef
RGS
2052 }
2053 }
2054 TRIE_BITMAP_SET(trie,*ch);
2055 if ( folder )
2056 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2057 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2058 }
2059 idx = ofs;
2060 }
3dab1dad
YO
2061 }
2062 if ( count == 1 ) {
2b8b4781 2063 SV **tmp = av_fetch( revcharmap, idx, 0);
c490c714
YO
2064 STRLEN len;
2065 char *ch = SvPV( *tmp, len );
de734bd5
A
2066 DEBUG_OPTIMISE_r({
2067 SV *sv=sv_newmortal();
8e11feef
RGS
2068 PerlIO_printf( Perl_debug_log,
2069 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2070 (int)depth * 2 + 2, "",
de734bd5
A
2071 (UV)state, (UV)idx,
2072 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
2073 PL_colors[0], PL_colors[1],
2074 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2075 PERL_PV_ESCAPE_FIRSTCHAR
2076 )
2077 );
2078 });
3dab1dad
YO
2079 if ( state==1 ) {
2080 OP( convert ) = nodetype;
2081 str=STRING(convert);
2082 STR_LEN(convert)=0;
2083 }
c490c714
YO
2084 STR_LEN(convert) += len;
2085 while (len--)
de734bd5 2086 *str++ = *ch++;
8e11feef 2087 } else {
f9049ba1 2088#ifdef DEBUGGING
8e11feef
RGS
2089 if (state>1)
2090 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
f9049ba1 2091#endif
8e11feef
RGS
2092 break;
2093 }
2094 }
2e64971a 2095 trie->prefixlen = (state-1);
3dab1dad 2096 if (str) {
8e11feef 2097 regnode *n = convert+NODE_SZ_STR(convert);
07be1b83 2098 NEXT_OFF(convert) = NODE_SZ_STR(convert);
8e11feef 2099 trie->startstate = state;
07be1b83
YO
2100 trie->minlen -= (state - 1);
2101 trie->maxlen -= (state - 1);
33809eae
JH
2102#ifdef DEBUGGING
2103 /* At least the UNICOS C compiler choked on this
2104 * being argument to DEBUG_r(), so let's just have
2105 * it right here. */
2106 if (
2107#ifdef PERL_EXT_RE_BUILD
2108 1
2109#else
2110 DEBUG_r_TEST
2111#endif
2112 ) {
2113 regnode *fix = convert;
2114 U32 word = trie->wordcount;
2115 mjd_nodelen++;
2116 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2117 while( ++fix < n ) {
2118 Set_Node_Offset_Length(fix, 0, 0);
2119 }
2120 while (word--) {
2121 SV ** const tmp = av_fetch( trie_words, word, 0 );
2122 if (tmp) {
2123 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2124 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2125 else
2126 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2127 }
2128 }
2129 }
2130#endif
8e11feef
RGS
2131 if (trie->maxlen) {
2132 convert = n;
2133 } else {
3dab1dad 2134 NEXT_OFF(convert) = (U16)(tail - convert);
a5ca303d 2135 DEBUG_r(optimize= n);
3dab1dad
YO
2136 }
2137 }
2138 }
a5ca303d
YO
2139 if (!jumper)
2140 jumper = last;
3dab1dad 2141 if ( trie->maxlen ) {
8e11feef
RGS
2142 NEXT_OFF( convert ) = (U16)(tail - convert);
2143 ARG_SET( convert, data_slot );
786e8c11
YO
2144 /* Store the offset to the first unabsorbed branch in
2145 jump[0], which is otherwise unused by the jump logic.
2146 We use this when dumping a trie and during optimisation. */
2147 if (trie->jump)
7f69552c 2148 trie->jump[0] = (U16)(nextbranch - convert);
a5ca303d 2149
6c48061a
YO
2150 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2151 * and there is a bitmap
2152 * and the first "jump target" node we found leaves enough room
2153 * then convert the TRIE node into a TRIEC node, with the bitmap
2154 * embedded inline in the opcode - this is hypothetically faster.
2155 */
2156 if ( !trie->states[trie->startstate].wordnum
2157 && trie->bitmap
2158 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
786e8c11
YO
2159 {
2160 OP( convert ) = TRIEC;
2161 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
446bd890 2162 PerlMemShared_free(trie->bitmap);
786e8c11
YO
2163 trie->bitmap= NULL;
2164 } else
2165 OP( convert ) = TRIE;
a3621e74 2166
3dab1dad
YO
2167 /* store the type in the flags */
2168 convert->flags = nodetype;
a5ca303d
YO
2169 DEBUG_r({
2170 optimize = convert
2171 + NODE_STEP_REGNODE
2172 + regarglen[ OP( convert ) ];
2173 });
2174 /* XXX We really should free up the resource in trie now,
2175 as we won't use them - (which resources?) dmq */
3dab1dad 2176 }
a3621e74 2177 /* needed for dumping*/
e62cc96a 2178 DEBUG_r(if (optimize) {
07be1b83 2179 regnode *opt = convert;
bcdf7404 2180
e62cc96a 2181 while ( ++opt < optimize) {
07be1b83
YO
2182 Set_Node_Offset_Length(opt,0,0);
2183 }
786e8c11
YO
2184 /*
2185 Try to clean up some of the debris left after the
2186 optimisation.
a3621e74 2187 */
786e8c11 2188 while( optimize < jumper ) {
07be1b83 2189 mjd_nodelen += Node_Length((optimize));
a3621e74 2190 OP( optimize ) = OPTIMIZED;
07be1b83 2191 Set_Node_Offset_Length(optimize,0,0);
a3621e74
YO
2192 optimize++;
2193 }
07be1b83 2194 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
a3621e74
YO
2195 });
2196 } /* end node insert */
2e64971a
DM
2197
2198 /* Finish populating the prev field of the wordinfo array. Walk back
2199 * from each accept state until we find another accept state, and if
2200 * so, point the first word's .prev field at the second word. If the
2201 * second already has a .prev field set, stop now. This will be the
2202 * case either if we've already processed that word's accept state,
3b753521
FN
2203 * or that state had multiple words, and the overspill words were
2204 * already linked up earlier.
2e64971a
DM
2205 */
2206 {
2207 U16 word;
2208 U32 state;
2209 U16 prev;
2210
2211 for (word=1; word <= trie->wordcount; word++) {
2212 prev = 0;
2213 if (trie->wordinfo[word].prev)
2214 continue;
2215 state = trie->wordinfo[word].accept;
2216 while (state) {
2217 state = prev_states[state];
2218 if (!state)
2219 break;
2220 prev = trie->states[state].wordnum;
2221 if (prev)
2222 break;
2223 }
2224 trie->wordinfo[word].prev = prev;
2225 }
2226 Safefree(prev_states);
2227 }
2228
2229
2230 /* and now dump out the compressed format */
2231 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2232
55eed653 2233 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2b8b4781
NC
2234#ifdef DEBUGGING
2235 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2236 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2237#else
2238 SvREFCNT_dec(revcharmap);
07be1b83 2239#endif
786e8c11
YO
2240 return trie->jump
2241 ? MADE_JUMP_TRIE
2242 : trie->startstate>1
2243 ? MADE_EXACT_TRIE
2244 : MADE_TRIE;
2245}
2246
2247STATIC void
2248S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2249{
3b753521 2250/* The Trie is constructed and compressed now so we can build a fail array if it's needed
786e8c11
YO
2251
2252 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2253 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2254 ISBN 0-201-10088-6
2255
2256 We find the fail state for each state in the trie, this state is the longest proper
3b753521
FN
2257 suffix of the current state's 'word' that is also a proper prefix of another word in our
2258 trie. State 1 represents the word '' and is thus the default fail state. This allows
786e8c11
YO
2259 the DFA not to have to restart after its tried and failed a word at a given point, it
2260 simply continues as though it had been matching the other word in the first place.
2261 Consider
2262 'abcdgu'=~/abcdefg|cdgu/
2263 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
3b753521
FN
2264 fail, which would bring us to the state representing 'd' in the second word where we would
2265 try 'g' and succeed, proceeding to match 'cdgu'.
786e8c11
YO
2266 */
2267 /* add a fail transition */
3251b653
NC
2268 const U32 trie_offset = ARG(source);
2269 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
786e8c11
YO
2270 U32 *q;
2271 const U32 ucharcount = trie->uniquecharcount;
1e2e3d02 2272 const U32 numstates = trie->statecount;
786e8c11
YO
2273 const U32 ubound = trie->lasttrans + ucharcount;
2274 U32 q_read = 0;
2275 U32 q_write = 0;
2276 U32 charid;
2277 U32 base = trie->states[ 1 ].trans.base;
2278 U32 *fail;
2279 reg_ac_data *aho;
2280 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2281 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2282
2283 PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
786e8c11
YO
2284#ifndef DEBUGGING
2285 PERL_UNUSED_ARG(depth);
2286#endif
2287
2288
2289 ARG_SET( stclass, data_slot );
c944940b 2290 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
f8fc2ecf 2291 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3251b653 2292 aho->trie=trie_offset;
446bd890
NC
2293 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2294 Copy( trie->states, aho->states, numstates, reg_trie_state );
786e8c11 2295 Newxz( q, numstates, U32);
c944940b 2296 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
786e8c11
YO
2297 aho->refcount = 1;
2298 fail = aho->fail;
2299 /* initialize fail[0..1] to be 1 so that we always have
2300 a valid final fail state */
2301 fail[ 0 ] = fail[ 1 ] = 1;
2302
2303 for ( charid = 0; charid < ucharcount ; charid++ ) {
2304 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2305 if ( newstate ) {
2306 q[ q_write ] = newstate;
2307 /* set to point at the root */
2308 fail[ q[ q_write++ ] ]=1;
2309 }
2310 }
2311 while ( q_read < q_write) {
2312 const U32 cur = q[ q_read++ % numstates ];
2313 base = trie->states[ cur ].trans.base;
2314
2315 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2316 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2317 if (ch_state) {
2318 U32 fail_state = cur;
2319 U32 fail_base;
2320 do {
2321 fail_state = fail[ fail_state ];
2322 fail_base = aho->states[ fail_state ].trans.base;
2323 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2324
2325 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2326 fail[ ch_state ] = fail_state;
2327 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2328 {
2329 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2330 }
2331 q[ q_write++ % numstates] = ch_state;
2332 }
2333 }
2334 }
2335 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2336 when we fail in state 1, this allows us to use the
2337 charclass scan to find a valid start char. This is based on the principle
2338 that theres a good chance the string being searched contains lots of stuff
2339 that cant be a start char.
2340 */
2341 fail[ 0 ] = fail[ 1 ] = 0;
2342 DEBUG_TRIE_COMPILE_r({
6d99fb9b
JH
2343 PerlIO_printf(Perl_debug_log,
2344 "%*sStclass Failtable (%"UVuf" states): 0",
2345 (int)(depth * 2), "", (UV)numstates
1e2e3d02 2346 );
786e8c11
YO
2347 for( q_read=1; q_read<numstates; q_read++ ) {
2348 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2349 }
2350 PerlIO_printf(Perl_debug_log, "\n");
2351 });
2352 Safefree(q);
2353 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
a3621e74
YO
2354}
2355
786e8c11 2356
a3621e74 2357/*
5d1c421c
JH
2358 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2359 * These need to be revisited when a newer toolchain becomes available.
2360 */
2361#if defined(__sparc64__) && defined(__GNUC__)
2362# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2363# undef SPARC64_GCC_WORKAROUND
2364# define SPARC64_GCC_WORKAROUND 1
2365# endif
2366#endif
2367
07be1b83 2368#define DEBUG_PEEP(str,scan,depth) \
b515a41d 2369 DEBUG_OPTIMISE_r({if (scan){ \
07be1b83
YO
2370 SV * const mysv=sv_newmortal(); \
2371 regnode *Next = regnext(scan); \
2372 regprop(RExC_rx, mysv, scan); \
7f69552c 2373 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
07be1b83
YO
2374 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2375 Next ? (REG_NODE_NUM(Next)) : 0 ); \
b515a41d 2376 }});
07be1b83 2377
1de06328
YO
2378
2379
2380
2381
07be1b83
YO
2382#define JOIN_EXACT(scan,min,flags) \
2383 if (PL_regkind[OP(scan)] == EXACT) \
2384 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2385
be8e71aa 2386STATIC U32
07be1b83
YO
2387S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2388 /* Merge several consecutive EXACTish nodes into one. */
2389 regnode *n = regnext(scan);
2390 U32 stringok = 1;
2391 regnode *next = scan + NODE_SZ_STR(scan);
2392 U32 merged = 0;
2393 U32 stopnow = 0;
2394#ifdef DEBUGGING
2395 regnode *stop = scan;
72f13be8 2396 GET_RE_DEBUG_FLAGS_DECL;
f9049ba1 2397#else
d47053eb
RGS
2398 PERL_UNUSED_ARG(depth);
2399#endif
7918f24d
NC
2400
2401 PERL_ARGS_ASSERT_JOIN_EXACT;
d47053eb 2402#ifndef EXPERIMENTAL_INPLACESCAN
f9049ba1
SP
2403 PERL_UNUSED_ARG(flags);
2404 PERL_UNUSED_ARG(val);
07be1b83 2405#endif
07be1b83
YO
2406 DEBUG_PEEP("join",scan,depth);
2407
2408 /* Skip NOTHING, merge EXACT*. */
2409 while (n &&
2410 ( PL_regkind[OP(n)] == NOTHING ||
2411 (stringok && (OP(n) == OP(scan))))
2412 && NEXT_OFF(n)
2413 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2414
2415 if (OP(n) == TAIL || n > next)
2416 stringok = 0;
2417 if (PL_regkind[OP(n)] == NOTHING) {
07be1b83
YO
2418 DEBUG_PEEP("skip:",n,depth);
2419 NEXT_OFF(scan) += NEXT_OFF(n);
2420 next = n + NODE_STEP_REGNODE;
2421#ifdef DEBUGGING
2422 if (stringok)
2423 stop = n;
2424#endif
2425 n = regnext(n);
2426 }
2427 else if (stringok) {
786e8c11 2428 const unsigned int oldl = STR_LEN(scan);
07be1b83
YO
2429 regnode * const nnext = regnext(n);
2430
2431 DEBUG_PEEP("merg",n,depth);
2432
2433 merged++;
2434 if (oldl + STR_LEN(n) > U8_MAX)
2435 break;
2436 NEXT_OFF(scan) += NEXT_OFF(n);
2437 STR_LEN(scan) += STR_LEN(n);
2438 next = n + NODE_SZ_STR(n);
2439 /* Now we can overwrite *n : */
2440 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2441#ifdef DEBUGGING
2442 stop = next - 1;
2443#endif
2444 n = nnext;
2445 if (stopnow) break;
2446 }
2447
d47053eb
RGS
2448#ifdef EXPERIMENTAL_INPLACESCAN
2449 if (flags && !NEXT_OFF(n)) {
2450 DEBUG_PEEP("atch", val, depth);
2451 if (reg_off_by_arg[OP(n)]) {
2452 ARG_SET(n, val - n);
2453 }
2454 else {
2455 NEXT_OFF(n) = val - n;
2456 }
2457 stopnow = 1;
2458 }
07be1b83
YO
2459#endif
2460 }
ced7f090
KW
2461#define GREEK_SMALL_LETTER_IOTA_WITH_DIALYTIKA_AND_TONOS 0x0390
2462#define IOTA_D_T GREEK_SMALL_LETTER_IOTA_WITH_DIALYTIKA_AND_TONOS
2463#define GREEK_SMALL_LETTER_UPSILON_WITH_DIALYTIKA_AND_TONOS 0x03B0
2464#define UPSILON_D_T GREEK_SMALL_LETTER_UPSILON_WITH_DIALYTIKA_AND_TONOS
2c2b7f86
KW
2465
2466 if (UTF
2467 && ( OP(scan) == EXACTF || OP(scan) == EXACTFU)
2468 && ( STR_LEN(scan) >= 6 ) )
2469 {
07be1b83
YO
2470 /*
2471 Two problematic code points in Unicode casefolding of EXACT nodes:
2472
2473 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2474 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2475
2476 which casefold to
2477
2478 Unicode UTF-8
2479
2480 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2481 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2482
2483 This means that in case-insensitive matching (or "loose matching",
2484 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2485 length of the above casefolded versions) can match a target string
2486 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2487 This would rather mess up the minimum length computation.
2488
2489 What we'll do is to look for the tail four bytes, and then peek
2490 at the preceding two bytes to see whether we need to decrease
2491 the minimum length by four (six minus two).
2492
2493 Thanks to the design of UTF-8, there cannot be false matches:
2494 A sequence of valid UTF-8 bytes cannot be a subsequence of
2495 another valid sequence of UTF-8 bytes.
2496
2497 */
2498 char * const s0 = STRING(scan), *s, *t;
2499 char * const s1 = s0 + STR_LEN(scan) - 1;
2500 char * const s2 = s1 - 4;
e294cc5d
JH
2501#ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2502 const char t0[] = "\xaf\x49\xaf\x42";
2503#else
07be1b83 2504 const char t0[] = "\xcc\x88\xcc\x81";
e294cc5d 2505#endif
07be1b83
YO
2506 const char * const t1 = t0 + 3;
2507
2508 for (s = s0 + 2;
2509 s < s2 && (t = ninstr(s, s1, t0, t1));
2510 s = t + 4) {
e294cc5d
JH
2511#ifdef EBCDIC
2512 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2513 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2514#else
07be1b83
YO
2515 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2516 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
e294cc5d 2517#endif
07be1b83
YO
2518 *min -= 4;
2519 }
2520 }
2521
2522#ifdef DEBUGGING
2523 /* Allow dumping */
2524 n = scan + NODE_SZ_STR(scan);
2525 while (n <= stop) {
2526 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2527 OP(n) = OPTIMIZED;
2528 NEXT_OFF(n) = 0;
2529 }
2530 n++;
2531 }
2532#endif
2533 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2534 return stopnow;
2535}
2536
486ec47a 2537/* REx optimizer. Converts nodes into quicker variants "in place".
653099ff
GS
2538 Finds fixed substrings. */
2539
a0288114 2540/* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
c277df42
IZ
2541 to the position after last scanned or to NULL. */
2542
40d049e4
YO
2543#define INIT_AND_WITHP \
2544 assert(!and_withp); \
2545 Newx(and_withp,1,struct regnode_charclass_class); \
2546 SAVEFREEPV(and_withp)
07be1b83 2547
b515a41d 2548/* this is a chain of data about sub patterns we are processing that
486ec47a 2549 need to be handled separately/specially in study_chunk. Its so
b515a41d
YO
2550 we can simulate recursion without losing state. */
2551struct scan_frame;
2552typedef struct scan_frame {
2553 regnode *last; /* last node to process in this frame */
2554 regnode *next; /* next node to process when last is reached */
2555 struct scan_frame *prev; /*previous frame*/
2556 I32 stop; /* what stopparen do we use */
2557} scan_frame;
2558
304ee84b
YO
2559
2560#define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2561
e1d1eefb
YO
2562#define CASE_SYNST_FNC(nAmE) \
2563case nAmE: \
2564 if (flags & SCF_DO_STCLASS_AND) { \
2565 for (value = 0; value < 256; value++) \
2566 if (!is_ ## nAmE ## _cp(value)) \
2567 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2568 } \
2569 else { \
2570 for (value = 0; value < 256; value++) \
2571 if (is_ ## nAmE ## _cp(value)) \
2572 ANYOF_BITMAP_SET(data->start_class, value); \
2573 } \
2574 break; \
2575case N ## nAmE: \
2576 if (flags & SCF_DO_STCLASS_AND) { \
2577 for (value = 0; value < 256; value++) \
2578 if (is_ ## nAmE ## _cp(value)) \
2579 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2580 } \
2581 else { \
2582 for (value = 0; value < 256; value++) \
2583 if (!is_ ## nAmE ## _cp(value)) \
2584 ANYOF_BITMAP_SET(data->start_class, value); \
2585 } \
2586 break
2587
2588
2589
76e3520e 2590STATIC I32
40d049e4 2591S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
1de06328 2592 I32 *minlenp, I32 *deltap,
40d049e4
YO
2593 regnode *last,
2594 scan_data_t *data,
2595 I32 stopparen,
2596 U8* recursed,
2597 struct regnode_charclass_class *and_withp,
2598 U32 flags, U32 depth)
c277df42
IZ
2599 /* scanp: Start here (read-write). */
2600 /* deltap: Write maxlen-minlen here. */
2601 /* last: Stop before this one. */
40d049e4
YO
2602 /* data: string data about the pattern */
2603 /* stopparen: treat close N as END */
2604 /* recursed: which subroutines have we recursed into */
2605 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
c277df42 2606{
97aff369 2607 dVAR;
c277df42
IZ
2608 I32 min = 0, pars = 0, code;
2609 regnode *scan = *scanp, *next;
2610 I32 delta = 0;
2611 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
aca2d497 2612 int is_inf_internal = 0; /* The studied chunk is infinite */
c277df42
IZ
2613 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2614 scan_data_t data_fake;
a3621e74 2615 SV *re_trie_maxbuff = NULL;
786e8c11 2616 regnode *first_non_open = scan;
e2e6a0f1 2617 I32 stopmin = I32_MAX;
8aa23a47 2618 scan_frame *frame = NULL;
a3621e74 2619 GET_RE_DEBUG_FLAGS_DECL;
8aa23a47 2620
7918f24d
NC
2621 PERL_ARGS_ASSERT_STUDY_CHUNK;
2622
13a24bad 2623#ifdef DEBUGGING
40d049e4 2624 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
13a24bad 2625#endif
40d049e4 2626
786e8c11 2627 if ( depth == 0 ) {
40d049e4 2628 while (first_non_open && OP(first_non_open) == OPEN)
786e8c11
YO
2629 first_non_open=regnext(first_non_open);
2630 }
2631
b81d288d 2632
8aa23a47
YO
2633 fake_study_recurse:
2634 while ( scan && OP(scan) != END && scan < last ){
2635 /* Peephole optimizer: */
304ee84b 2636 DEBUG_STUDYDATA("Peep:", data,depth);
8aa23a47
YO
2637 DEBUG_PEEP("Peep",scan,depth);
2638 JOIN_EXACT(scan,&min,0);
2639
2640 /* Follow the next-chain of the current node and optimize
2641 away all the NOTHINGs from it. */
2642 if (OP(scan) != CURLYX) {
2643 const int max = (reg_off_by_arg[OP(scan)]
2644 ? I32_MAX
2645 /* I32 may be smaller than U16 on CRAYs! */
2646 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2647 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2648 int noff;
2649 regnode *n = scan;
2650
2651 /* Skip NOTHING and LONGJMP. */
2652 while ((n = regnext(n))
2653 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2654 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2655 && off + noff < max)
2656 off += noff;
2657 if (reg_off_by_arg[OP(scan)])
2658 ARG(scan) = off;
2659 else
2660 NEXT_OFF(scan) = off;
2661 }
a3621e74 2662
c277df42 2663
8aa23a47
YO
2664
2665 /* The principal pseudo-switch. Cannot be a switch, since we
2666 look into several different things. */
2667 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2668 || OP(scan) == IFTHEN) {
2669 next = regnext(scan);
2670 code = OP(scan);
2671 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2672
2673 if (OP(next) == code || code == IFTHEN) {
2674 /* NOTE - There is similar code to this block below for handling
2675 TRIE nodes on a re-study. If you change stuff here check there
2676 too. */
2677 I32 max1 = 0, min1 = I32_MAX, num = 0;
2678 struct regnode_charclass_class accum;
2679 regnode * const startbranch=scan;
2680
2681 if (flags & SCF_DO_SUBSTR)
304ee84b 2682 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
8aa23a47
YO
2683 if (flags & SCF_DO_STCLASS)
2684 cl_init_zero(pRExC_state, &accum);
2685
2686 while (OP(scan) == code) {
2687 I32 deltanext, minnext, f = 0, fake;
2688 struct regnode_charclass_class this_class;
2689
2690 num++;
2691 data_fake.flags = 0;
2692 if (data) {
2693 data_fake.whilem_c = data->whilem_c;
2694 data_fake.last_closep = data->last_closep;
2695 }
2696 else
2697 data_fake.last_closep = &fake;
58e23c8d
YO
2698
2699 data_fake.pos_delta = delta;
8aa23a47
YO
2700 next = regnext(scan);
2701 scan = NEXTOPER(scan);
2702 if (code != BRANCH)
c277df42 2703 scan = NEXTOPER(scan);
8aa23a47
YO
2704 if (flags & SCF_DO_STCLASS) {
2705 cl_init(pRExC_state, &this_class);
2706 data_fake.start_class = &this_class;
2707 f = SCF_DO_STCLASS_AND;
58e23c8d 2708 }
8aa23a47
YO
2709 if (flags & SCF_WHILEM_VISITED_POS)
2710 f |= SCF_WHILEM_VISITED_POS;
2711
2712 /* we suppose the run is continuous, last=next...*/
2713 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2714 next, &data_fake,
2715 stopparen, recursed, NULL, f,depth+1);
2716 if (min1 > minnext)
2717 min1 = minnext;
2718 if (max1 < minnext + deltanext)
2719 max1 = minnext + deltanext;
2720 if (deltanext == I32_MAX)
2721 is_inf = is_inf_internal = 1;
2722 scan = next;
2723 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2724 pars++;
2725 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2726 if ( stopmin > minnext)
2727 stopmin = min + min1;
2728 flags &= ~SCF_DO_SUBSTR;
2729 if (data)
2730 data->flags |= SCF_SEEN_ACCEPT;
2731 }
2732 if (data) {
2733 if (data_fake.flags & SF_HAS_EVAL)
2734 data->flags |= SF_HAS_EVAL;
2735 data->whilem_c = data_fake.whilem_c;
3dab1dad 2736 }
8aa23a47
YO
2737 if (flags & SCF_DO_STCLASS)
2738 cl_or(pRExC_state, &accum, &this_class);
2739 }
2740 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2741 min1 = 0;
2742 if (flags & SCF_DO_SUBSTR) {
2743 data->pos_min += min1;
2744 data->pos_delta += max1 - min1;
2745 if (max1 != min1 || is_inf)
2746 data->longest = &(data->longest_float);
2747 }
2748 min += min1;
2749 delta += max1 - min1;
2750 if (flags & SCF_DO_STCLASS_OR) {
2751 cl_or(pRExC_state, data->start_class, &accum);
2752 if (min1) {
2753 cl_and(data->start_class, and_withp);
2754 flags &= ~SCF_DO_STCLASS;
653099ff 2755 }
8aa23a47
YO
2756 }
2757 else if (flags & SCF_DO_STCLASS_AND) {
2758 if (min1) {
2759 cl_and(data->start_class, &accum);
2760 flags &= ~SCF_DO_STCLASS;
de0c8cb8 2761 }
8aa23a47
YO
2762 else {
2763 /* Switch to OR mode: cache the old value of
2764 * data->start_class */
2765 INIT_AND_WITHP;
2766 StructCopy(data->start_class, and_withp,
2767 struct regnode_charclass_class);
2768 flags &= ~SCF_DO_STCLASS_AND;
2769 StructCopy(&accum, data->start_class,
2770 struct regnode_charclass_class);
2771 flags |= SCF_DO_STCLASS_OR;
2772 data->start_class->flags |= ANYOF_EOS;
de0c8cb8 2773 }
8aa23a47 2774 }
a3621e74 2775
8aa23a47
YO
2776 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2777 /* demq.
a3621e74 2778
8aa23a47
YO
2779 Assuming this was/is a branch we are dealing with: 'scan' now
2780 points at the item that follows the branch sequence, whatever
2781 it is. We now start at the beginning of the sequence and look
2782 for subsequences of
a3621e74 2783
8aa23a47
YO
2784 BRANCH->EXACT=>x1
2785 BRANCH->EXACT=>x2
2786 tail
a3621e74 2787
8aa23a47 2788 which would be constructed from a pattern like /A|LIST|OF|WORDS/
a3621e74 2789
486ec47a 2790 If we can find such a subsequence we need to turn the first
8aa23a47
YO
2791 element into a trie and then add the subsequent branch exact
2792 strings to the trie.
a3621e74 2793
8aa23a47 2794 We have two cases
a3621e74 2795
3b753521 2796 1. patterns where the whole set of branches can be converted.
a3621e74 2797
8aa23a47 2798 2. patterns where only a subset can be converted.
a3621e74 2799
8aa23a47
YO
2800 In case 1 we can replace the whole set with a single regop
2801 for the trie. In case 2 we need to keep the start and end
3b753521 2802 branches so
a3621e74 2803
8aa23a47
YO
2804 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2805 becomes BRANCH TRIE; BRANCH X;
786e8c11 2806
8aa23a47
YO
2807 There is an additional case, that being where there is a
2808 common prefix, which gets split out into an EXACT like node
2809 preceding the TRIE node.
a3621e74 2810
8aa23a47
YO
2811 If x(1..n)==tail then we can do a simple trie, if not we make
2812 a "jump" trie, such that when we match the appropriate word
486ec47a 2813 we "jump" to the appropriate tail node. Essentially we turn
8aa23a47 2814 a nested if into a case structure of sorts.
b515a41d 2815
8aa23a47
YO
2816 */
2817
2818 int made=0;
2819 if (!re_trie_maxbuff) {
2820 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2821 if (!SvIOK(re_trie_maxbuff))
2822 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2823 }
2824 if ( SvIV(re_trie_maxbuff)>=0 ) {
2825 regnode *cur;
2826 regnode *first = (regnode *)NULL;
2827 regnode *last = (regnode *)NULL;
2828 regnode *tail = scan;
2829 U8 optype = 0;
2830 U32 count=0;
a3621e74
YO
2831
2832#ifdef DEBUGGING
8aa23a47 2833 SV * const mysv = sv_newmortal(); /* for dumping */
a3621e74 2834#endif
8aa23a47
YO
2835 /* var tail is used because there may be a TAIL
2836 regop in the way. Ie, the exacts will point to the
2837 thing following the TAIL, but the last branch will
2838 point at the TAIL. So we advance tail. If we
2839 have nested (?:) we may have to move through several
2840 tails.
2841 */
2842
2843 while ( OP( tail ) == TAIL ) {
2844 /* this is the TAIL generated by (?:) */
2845 tail = regnext( tail );
2846 }
a3621e74 2847
8aa23a47
YO
2848
2849 DEBUG_OPTIMISE_r({
2850 regprop(RExC_rx, mysv, tail );
2851 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2852 (int)depth * 2 + 2, "",
2853 "Looking for TRIE'able sequences. Tail node is: ",
2854 SvPV_nolen_const( mysv )
2855 );
2856 });
2857
2858 /*
2859
2860 step through the branches, cur represents each
2861 branch, noper is the first thing to be matched
2862 as part of that branch and noper_next is the
2863 regnext() of that node. if noper is an EXACT
2864 and noper_next is the same as scan (our current
2865 position in the regex) then the EXACT branch is
2866 a possible optimization target. Once we have
486ec47a 2867 two or more consecutive such branches we can
8aa23a47
YO
2868 create a trie of the EXACT's contents and stich
2869 it in place. If the sequence represents all of
2870 the branches we eliminate the whole thing and
2871 replace it with a single TRIE. If it is a
2872 subsequence then we need to stitch it in. This
2873 means the first branch has to remain, and needs
2874 to be repointed at the item on the branch chain
2875 following the last branch optimized. This could
2876 be either a BRANCH, in which case the
2877 subsequence is internal, or it could be the
2878 item following the branch sequence in which
2879 case the subsequence is at the end.
2880
2881 */
2882
2883 /* dont use tail as the end marker for this traverse */
2884 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2885 regnode * const noper = NEXTOPER( cur );
b515a41d 2886#if defined(DEBUGGING) || defined(NOJUMPTRIE)
8aa23a47 2887 regnode * const noper_next = regnext( noper );
b515a41d
YO
2888#endif
2889
8aa23a47
YO
2890 DEBUG_OPTIMISE_r({
2891 regprop(RExC_rx, mysv, cur);
2892 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2893 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2894
2895 regprop(RExC_rx, mysv, noper);
2896 PerlIO_printf( Perl_debug_log, " -> %s",
2897 SvPV_nolen_const(mysv));
2898
2899 if ( noper_next ) {
2900 regprop(RExC_rx, mysv, noper_next );
2901 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2902 SvPV_nolen_const(mysv));
2903 }
2904 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2905 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2906 });
2907 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2908 : PL_regkind[ OP( noper ) ] == EXACT )
2909 || OP(noper) == NOTHING )
786e8c11 2910#ifdef NOJUMPTRIE
8aa23a47 2911 && noper_next == tail
786e8c11 2912#endif
8aa23a47
YO
2913 && count < U16_MAX)
2914 {
2915 count++;
2916 if ( !first || optype == NOTHING ) {
2917 if (!first) first = cur;
2918 optype = OP( noper );
2919 } else {
2920 last = cur;
2921 }
2922 } else {
a0a388a1 2923/*
0abd0d78
YO
2924 Currently we do not believe that the trie logic can
2925 handle case insensitive matching properly when the
2926 pattern is not unicode (thus forcing unicode semantics).
2927
2928 If/when this is fixed the following define can be swapped
2929 in below to fully enable trie logic.
2930
a0a388a1 2931#define TRIE_TYPE_IS_SAFE 1
0abd0d78
YO
2932
2933*/
2934#define TRIE_TYPE_IS_SAFE (UTF || optype==EXACT)
2935
a0a388a1 2936 if ( last && TRIE_TYPE_IS_SAFE ) {
8aa23a47
YO
2937 make_trie( pRExC_state,
2938 startbranch, first, cur, tail, count,
2939 optype, depth+1 );
2940 }
2941 if ( PL_regkind[ OP( noper ) ] == EXACT
786e8c11 2942#ifdef NOJUMPTRIE
8aa23a47 2943 && noper_next == tail
786e8c11 2944#endif
8aa23a47
YO
2945 ){
2946 count = 1;
2947 first = cur;
2948 optype = OP( noper );
2949 } else {
2950 count = 0;
2951 first = NULL;
2952 optype = 0;
2953 }
2954 last = NULL;
2955 }
2956 }
2957 DEBUG_OPTIMISE_r({
2958 regprop(RExC_rx, mysv, cur);
2959 PerlIO_printf( Perl_debug_log,
2960 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2961 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2962
2963 });
a0a388a1
YO
2964
2965 if ( last && TRIE_TYPE_IS_SAFE ) {
8aa23a47 2966 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
3dab1dad 2967#ifdef TRIE_STUDY_OPT
8aa23a47
YO
2968 if ( ((made == MADE_EXACT_TRIE &&
2969 startbranch == first)
2970 || ( first_non_open == first )) &&
2971 depth==0 ) {
2972 flags |= SCF_TRIE_RESTUDY;
2973 if ( startbranch == first
2974 && scan == tail )
2975 {
2976 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2977 }
2978 }
3dab1dad 2979#endif
8aa23a47
YO
2980 }
2981 }
2982
2983 } /* do trie */
2984
653099ff 2985 }
8aa23a47
YO
2986 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2987 scan = NEXTOPER(NEXTOPER(scan));
2988 } else /* single branch is optimized. */
2989 scan = NEXTOPER(scan);
2990 continue;
2991 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2992 scan_frame *newframe = NULL;
2993 I32 paren;
2994 regnode *start;
2995 regnode *end;
2996
2997 if (OP(scan) != SUSPEND) {
2998 /* set the pointer */
2999 if (OP(scan) == GOSUB) {
3000 paren = ARG(scan);
3001 RExC_recurse[ARG2L(scan)] = scan;
3002 start = RExC_open_parens[paren-1];
3003 end = RExC_close_parens[paren-1];
3004 } else {
3005 paren = 0;
f8fc2ecf 3006 start = RExC_rxi->program + 1;
8aa23a47
YO
3007 end = RExC_opend;
3008 }
3009 if (!recursed) {
3010 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3011 SAVEFREEPV(recursed);
3012 }
3013 if (!PAREN_TEST(recursed,paren+1)) {
3014 PAREN_SET(recursed,paren+1);
3015 Newx(newframe,1,scan_frame);
3016 } else {
3017 if (flags & SCF_DO_SUBSTR) {
304ee84b 3018 SCAN_COMMIT(pRExC_state,data,minlenp);
8aa23a47
YO
3019 data->longest = &(data->longest_float);
3020 }
3021 is_inf = is_inf_internal = 1;
3022 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3023 cl_anything(pRExC_state, data->start_class);
3024 flags &= ~SCF_DO_STCLASS;
3025 }
3026 } else {
3027 Newx(newframe,1,scan_frame);
3028 paren = stopparen;
3029 start = scan+2;
3030 end = regnext(scan);
3031 }
3032 if (newframe) {
3033 assert(start);
3034 assert(end);
3035 SAVEFREEPV(newframe);
3036 newframe->next = regnext(scan);
3037 newframe->last = last;
3038 newframe->stop = stopparen;
3039 newframe->prev = frame;
3040
3041 frame = newframe;
3042 scan = start;
3043 stopparen = paren;
3044 last = end;
3045
3046 continue;
3047 }
3048 }
3049 else if (OP(scan) == EXACT) {
3050 I32 l = STR_LEN(scan);
3051 UV uc;
3052 if (UTF) {
3053 const U8 * const s = (U8*)STRING(scan);
3054 l = utf8_length(s, s + l);
3055 uc = utf8_to_uvchr(s, NULL);
3056 } else {
3057 uc = *((U8*)STRING(scan));
3058 }
3059 min += l;
3060 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3061 /* The code below prefers earlier match for fixed
3062 offset, later match for variable offset. */
3063 if (data->last_end == -1) { /* Update the start info. */
3064 data->last_start_min = data->pos_min;
3065 data->last_start_max = is_inf
3066 ? I32_MAX : data->pos_min + data->pos_delta;
b515a41d 3067 }
8aa23a47
YO
3068 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3069 if (UTF)
3070 SvUTF8_on(data->last_found);
3071 {
3072 SV * const sv = data->last_found;
3073 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3074 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3075 if (mg && mg->mg_len >= 0)
3076 mg->mg_len += utf8_length((U8*)STRING(scan),
3077 (U8*)STRING(scan)+STR_LEN(scan));
b515a41d 3078 }
8aa23a47
YO
3079 data->last_end = data->pos_min + l;
3080 data->pos_min += l; /* As in the first entry. */
3081 data->flags &= ~SF_BEFORE_EOL;
3082 }
3083 if (flags & SCF_DO_STCLASS_AND) {
3084 /* Check whether it is compatible with what we know already! */
3085 int compat = 1;
3086
54251c2e 3087
486ec47a 3088 /* If compatible, we or it in below. It is compatible if is
54251c2e
KW
3089 * in the bitmp and either 1) its bit or its fold is set, or 2)
3090 * it's for a locale. Even if there isn't unicode semantics
3091 * here, at runtime there may be because of matching against a
3092 * utf8 string, so accept a possible false positive for
3093 * latin1-range folds */
8aa23a47
YO
3094 if (uc >= 0x100 ||
3095 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3096 && !ANYOF_BITMAP_TEST(data->start_class, uc)
39065660 3097 && (!(data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD)
54251c2e 3098 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
8aa23a47
YO
3099 )
3100 compat = 0;
3101 ANYOF_CLASS_ZERO(data->start_class);
3102 ANYOF_BITMAP_ZERO(data->start_class);
3103 if (compat)
3104 ANYOF_BITMAP_SET(data->start_class, uc);
3105 data->start_class->flags &= ~ANYOF_EOS;
3106 if (uc < 0x100)
3107 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3108 }
3109 else if (flags & SCF_DO_STCLASS_OR) {
3110 /* false positive possible if the class is case-folded */
3111 if (uc < 0x100)
3112 ANYOF_BITMAP_SET(data->start_class, uc);
3113 else
3114 data->start_class->flags |= ANYOF_UNICODE_ALL;
3115 data->start_class->flags &= ~ANYOF_EOS;
3116 cl_and(data->start_class, and_withp);
3117 }
3118 flags &= ~SCF_DO_STCLASS;
3119 }
3120 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3121 I32 l = STR_LEN(scan);
3122 UV uc = *((U8*)STRING(scan));
3123
3124 /* Search for fixed substrings supports EXACT only. */
3125 if (flags & SCF_DO_SUBSTR) {
3126 assert(data);
304ee84b 3127 SCAN_COMMIT(pRExC_state, data, minlenp);
8aa23a47
YO
3128 }
3129 if (UTF) {
3130 const U8 * const s = (U8 *)STRING(scan);
3131 l = utf8_length(s, s + l);
3132 uc = utf8_to_uvchr(s, NULL);
3133 }
3134 min += l;
3135 if (flags & SCF_DO_SUBSTR)
3136 data->pos_min += l;
3137 if (flags & SCF_DO_STCLASS_AND) {
3138 /* Check whether it is compatible with what we know already! */
3139 int compat = 1;
8aa23a47 3140 if (uc >= 0x100 ||
54251c2e
KW
3141 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3142 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3143 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3144 {
8aa23a47 3145 compat = 0;
54251c2e 3146 }
8aa23a47
YO
3147 ANYOF_CLASS_ZERO(data->start_class);
3148 ANYOF_BITMAP_ZERO(data->start_class);
3149 if (compat) {
3150 ANYOF_BITMAP_SET(data->start_class, uc);
653099ff 3151 data->start_class->flags &= ~ANYOF_EOS;
39065660 3152 data->start_class->flags |= ANYOF_LOC_NONBITMAP_FOLD;
970c8436 3153 if (OP(scan) == EXACTFL) {
8aa23a47 3154 data->start_class->flags |= ANYOF_LOCALE;
970c8436
KW
3155 }
3156 else {
3157
54251c2e
KW
3158 /* Also set the other member of the fold pair. In case
3159 * that unicode semantics is called for at runtime, use
3160 * the full latin1 fold. (Can't do this for locale,
3161 * because not known until runtime */
3162 ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
970c8436 3163 }
653099ff 3164 }
8aa23a47
YO
3165 }
3166 else if (flags & SCF_DO_STCLASS_OR) {
39065660 3167 if (data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD) {
8aa23a47
YO
3168 /* false positive possible if the class is case-folded.
3169 Assume that the locale settings are the same... */
970c8436 3170 if (uc < 0x100) {
1aa99e6b 3171 ANYOF_BITMAP_SET(data->start_class, uc);
970c8436
KW
3172 if (OP(scan) != EXACTFL) {
3173
3174 /* And set the other member of the fold pair, but
3175 * can't do that in locale because not known until
3176 * run-time */
3177 ANYOF_BITMAP_SET(data->start_class,
54251c2e 3178 PL_fold_latin1[uc]);
970c8436
KW
3179 }
3180 }
653099ff
GS
3181 data->start_class->flags &= ~ANYOF_EOS;
3182 }
8aa23a47 3183 cl_and(data->start_class, and_withp);
653099ff 3184 }
8aa23a47
YO
3185 flags &= ~SCF_DO_STCLASS;
3186 }
e52fc539 3187 else if (REGNODE_VARIES(OP(scan))) {
8aa23a47
YO
3188 I32 mincount, maxcount, minnext, deltanext, fl = 0;
3189 I32 f = flags, pos_before = 0;
3190 regnode * const oscan = scan;
3191 struct regnode_charclass_class this_class;
3192 struct regnode_charclass_class *oclass = NULL;
3193 I32 next_is_eval = 0;
3194
3195 switch (PL_regkind[OP(scan)]) {
3196 case WHILEM: /* End of (?:...)* . */
3197 scan = NEXTOPER(scan);
3198 goto finish;
3199 case PLUS:
3200 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3201 next = NEXTOPER(scan);
3202 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3203 mincount = 1;
3204 maxcount = REG_INFTY;
3205 next = regnext(scan);
3206 scan = NEXTOPER(scan);
3207 goto do_curly;
3208 }
3209 }
3210 if (flags & SCF_DO_SUBSTR)
3211 data->pos_min++;
3212 min++;
3213 /* Fall through. */
3214 case STAR:
3215 if (flags & SCF_DO_STCLASS) {
3216 mincount = 0;
3217 maxcount = REG_INFTY;
3218 next = regnext(scan);
3219 scan = NEXTOPER(scan);
3220 goto do_curly;
3221 }
3222 is_inf = is_inf_internal = 1;
3223 scan = regnext(scan);
c277df42 3224 if (flags & SCF_DO_SUBSTR) {
304ee84b 3225 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
8aa23a47 3226 data->longest = &(data->longest_float);
c277df42 3227 }
8aa23a47
YO
3228 goto optimize_curly_tail;
3229 case CURLY:
3230 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3231 && (scan->flags == stopparen))
3232 {
3233 mincount = 1;
3234 maxcount = 1;
3235 } else {
3236 mincount = ARG1(scan);
3237 maxcount = ARG2(scan);
653099ff 3238 }
8aa23a47
YO
3239 next = regnext(scan);
3240 if (OP(scan) == CURLYX) {
3241 I32 lp = (data ? *(data->last_closep) : 0);
3242 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
653099ff 3243 }
8aa23a47
YO
3244 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3245 next_is_eval = (OP(scan) == EVAL);
3246 do_curly:
3247 if (flags & SCF_DO_SUBSTR) {
304ee84b 3248 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
8aa23a47 3249 pos_before = data->pos_min;
b45f050a 3250 }
8aa23a47
YO
3251 if (data) {
3252 fl = data->flags;
3253 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3254 if (is_inf)
3255 data->flags |= SF_IS_INF;
3256 }
3257 if (flags & SCF_DO_STCLASS) {
3258 cl_init(pRExC_state, &this_class);
3259 oclass = data->start_class;
3260 data->start_class = &this_class;
3261 f |= SCF_DO_STCLASS_AND;
3262 f &= ~SCF_DO_STCLASS_OR;
3263 }
779bcb7d
NC
3264 /* Exclude from super-linear cache processing any {n,m}
3265 regops for which the combination of input pos and regex
3266 pos is not enough information to determine if a match
3267 will be possible.
3268
3269 For example, in the regex /foo(bar\s*){4,8}baz/ with the
3270 regex pos at the \s*, the prospects for a match depend not
3271 only on the input position but also on how many (bar\s*)
3272 repeats into the {4,8} we are. */
3273 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
8aa23a47 3274 f &= ~SCF_WHILEM_VISITED_POS;
b45f050a 3275
8aa23a47
YO
3276 /* This will finish on WHILEM, setting scan, or on NULL: */
3277 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3278 last, data, stopparen, recursed, NULL,
3279 (mincount == 0
3280 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
b515a41d 3281
8aa23a47
YO
3282 if (flags & SCF_DO_STCLASS)
3283 data->start_class = oclass;
3284 if (mincount == 0 || minnext == 0) {
3285 if (flags & SCF_DO_STCLASS_OR) {
3286 cl_or(pRExC_state, data->start_class, &this_class);
3287 }
3288 else if (flags & SCF_DO_STCLASS_AND) {
3289 /* Switch to OR mode: cache the old value of
3290 * data->start_class */
3291 INIT_AND_WITHP;
3292 StructCopy(data->start_class, and_withp,
3293 struct regnode_charclass_class);
3294 flags &= ~SCF_DO_STCLASS_AND;
3295 StructCopy(&this_class, data->start_class,
3296 struct regnode_charclass_class);
3297 flags |= SCF_DO_STCLASS_OR;
3298 data->start_class->flags |= ANYOF_EOS;
3299 }
3300 } else { /* Non-zero len */
3301 if (flags & SCF_DO_STCLASS_OR) {
3302 cl_or(pRExC_state, data->start_class, &this_class);
3303 cl_and(data->start_class, and_withp);
3304 }
3305 else if (flags & SCF_DO_STCLASS_AND)
3306 cl_and(data->start_class, &this_class);
3307 flags &= ~SCF_DO_STCLASS;
3308 }
3309 if (!scan) /* It was not CURLYX, but CURLY. */
3310 scan = next;
3311 if ( /* ? quantifier ok, except for (?{ ... }) */
3312 (next_is_eval || !(mincount == 0 && maxcount == 1))
3313 && (minnext == 0) && (deltanext == 0)
3314 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
668c081a 3315 && maxcount <= REG_INFTY/3) /* Complement check for big count */
8aa23a47 3316 {
668c081a
NC
3317 ckWARNreg(RExC_parse,
3318 "Quantifier unexpected on zero-length expression");
8aa23a47
YO
3319 }
3320
3321 min += minnext * mincount;
3322 is_inf_internal |= ((maxcount == REG_INFTY
3323 && (minnext + deltanext) > 0)
3324 || deltanext == I32_MAX);
3325 is_inf |= is_inf_internal;
3326 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3327
3328 /* Try powerful optimization CURLYX => CURLYN. */
3329 if ( OP(oscan) == CURLYX && data
3330 && data->flags & SF_IN_PAR
3331 && !(data->flags & SF_HAS_EVAL)
3332 && !deltanext && minnext == 1 ) {
3333 /* Try to optimize to CURLYN. */
3334 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3335 regnode * const nxt1 = nxt;
497b47a8 3336#ifdef DEBUGGING
8aa23a47 3337 regnode *nxt2;
497b47a8 3338#endif
c277df42 3339
8aa23a47
YO
3340 /* Skip open. */
3341 nxt = regnext(nxt);
e52fc539 3342 if (!REGNODE_SIMPLE(OP(nxt))
8aa23a47
YO
3343 && !(PL_regkind[OP(nxt)] == EXACT
3344 && STR_LEN(nxt) == 1))
3345 goto nogo;
497b47a8 3346#ifdef DEBUGGING
8aa23a47 3347 nxt2 = nxt;
497b47a8 3348#endif
8aa23a47
YO
3349 nxt = regnext(nxt);
3350 if (OP(nxt) != CLOSE)
3351 goto nogo;
3352 if (RExC_open_parens) {
3353 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3354 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3355 }
3356 /* Now we know that nxt2 is the only contents: */
3357 oscan->flags = (U8)ARG(nxt);
3358 OP(oscan) = CURLYN;
3359 OP(nxt1) = NOTHING; /* was OPEN. */
40d049e4 3360
c277df42 3361#ifdef DEBUGGING
8aa23a47 3362 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
fda99bee
KW
3363 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3364 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
8aa23a47
YO
3365 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3366 OP(nxt + 1) = OPTIMIZED; /* was count. */
fda99bee 3367 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
b81d288d 3368#endif
8aa23a47
YO
3369 }
3370 nogo:
3371
3372 /* Try optimization CURLYX => CURLYM. */
3373 if ( OP(oscan) == CURLYX && data
3374 && !(data->flags & SF_HAS_PAR)
3375 && !(data->flags & SF_HAS_EVAL)
3376 && !deltanext /* atom is fixed width */
3377 && minnext != 0 /* CURLYM can't handle zero width */
3378 ) {
3379 /* XXXX How to optimize if data == 0? */
3380 /* Optimize to a simpler form. */
3381 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3382 regnode *nxt2;
3383
3384 OP(oscan) = CURLYM;
3385 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3386 && (OP(nxt2) != WHILEM))
3387 nxt = nxt2;
3388 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3389 /* Need to optimize away parenths. */
b3c0965f 3390 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
8aa23a47
YO
3391 /* Set the parenth number. */
3392 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3393
8aa23a47
YO
3394 oscan->flags = (U8)ARG(nxt);
3395 if (RExC_open_parens) {
3396 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3397 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
40d049e4 3398 }
8aa23a47
YO
3399 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3400 OP(nxt) = OPTIMIZED; /* was CLOSE. */
40d049e4 3401
c277df42 3402#ifdef DEBUGGING
8aa23a47
YO
3403 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3404 OP(nxt + 1) = OPTIMIZED; /* was count. */
486ec47a
PA
3405 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
3406 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
b81d288d 3407#endif
c277df42 3408#if 0
8aa23a47
YO
3409 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3410 regnode *nnxt = regnext(nxt1);
8aa23a47
YO
3411 if (nnxt == nxt) {
3412 if (reg_off_by_arg[OP(nxt1)])
3413 ARG_SET(nxt1, nxt2 - nxt1);
3414 else if (nxt2 - nxt1 < U16_MAX)
3415 NEXT_OFF(nxt1) = nxt2 - nxt1;
3416 else
3417 OP(nxt) = NOTHING; /* Cannot beautify */
c277df42 3418 }
8aa23a47 3419 nxt1 = nnxt;
c277df42 3420 }
5d1c421c 3421#endif
8aa23a47
YO
3422 /* Optimize again: */
3423 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3424 NULL, stopparen, recursed, NULL, 0,depth+1);
3425 }
3426 else
3427 oscan->flags = 0;
3428 }
3429 else if ((OP(oscan) == CURLYX)
3430 && (flags & SCF_WHILEM_VISITED_POS)
3431 /* See the comment on a similar expression above.
3b753521 3432 However, this time it's not a subexpression
8aa23a47
YO
3433 we care about, but the expression itself. */
3434 && (maxcount == REG_INFTY)
3435 && data && ++data->whilem_c < 16) {
3436 /* This stays as CURLYX, we can put the count/of pair. */
3437 /* Find WHILEM (as in regexec.c) */
3438 regnode *nxt = oscan + NEXT_OFF(oscan);
3439
3440 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3441 nxt += ARG(nxt);
3442 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3443 | (RExC_whilem_seen << 4)); /* On WHILEM */
3444 }
3445 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3446 pars++;
3447 if (flags & SCF_DO_SUBSTR) {
3448 SV *last_str = NULL;
3449 int counted = mincount != 0;
a0ed51b3 3450
8aa23a47
YO
3451 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3452#if defined(SPARC64_GCC_WORKAROUND)
3453 I32 b = 0;
3454 STRLEN l = 0;
3455 const char *s = NULL;
3456 I32 old = 0;
b515a41d 3457
8aa23a47
YO
3458 if (pos_before >= data->last_start_min)
3459 b = pos_before;
3460 else
3461 b = data->last_start_min;
b515a41d 3462
8aa23a47
YO
3463 l = 0;
3464 s = SvPV_const(data->last_found, l);
3465 old = b - data->last_start_min;
3466
3467#else
3468 I32 b = pos_before >= data->last_start_min
3469 ? pos_before : data->last_start_min;
3470 STRLEN l;
3471 const char * const s = SvPV_const(data->last_found, l);
3472 I32 old = b - data->last_start_min;
3473#endif
3474
3475 if (UTF)
3476 old = utf8_hop((U8*)s, old) - (U8*)s;
8aa23a47
YO
3477 l -= old;
3478 /* Get the added string: */
740cce10 3479 last_str = newSVpvn_utf8(s + old, l, UTF);
8aa23a47
YO
3480 if (deltanext == 0 && pos_before == b) {
3481 /* What was added is a constant string */
3482 if (mincount > 1) {
3483 SvGROW(last_str, (mincount * l) + 1);
3484 repeatcpy(SvPVX(last_str) + l,
3485 SvPVX_const(last_str), l, mincount - 1);
3486 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3487 /* Add additional parts. */
3488 SvCUR_set(data->last_found,
3489 SvCUR(data->last_found) - l);
3490 sv_catsv(data->last_found, last_str);
3491 {
3492 SV * sv = data->last_found;
3493 MAGIC *mg =
3494 SvUTF8(sv) && SvMAGICAL(sv) ?
3495 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3496 if (mg && mg->mg_len >= 0)
bd94e887 3497 mg->mg_len += CHR_SVLEN(last_str) - l;
b515a41d 3498 }
8aa23a47 3499 data->last_end += l * (mincount - 1);
b515a41d 3500 }
8aa23a47
YO
3501 } else {
3502 /* start offset must point into the last copy */
3503 data->last_start_min += minnext * (mincount - 1);
3504 data->last_start_max += is_inf ? I32_MAX
3505 : (maxcount - 1) * (minnext + data->pos_delta);
3506 }
c277df42 3507 }
8aa23a47
YO
3508 /* It is counted once already... */
3509 data->pos_min += minnext * (mincount - counted);
3510 data->pos_delta += - counted * deltanext +
3511 (minnext + deltanext) * maxcount - minnext * mincount;
3512 if (mincount != maxcount) {
3513 /* Cannot extend fixed substrings found inside
3514 the group. */
304ee84b 3515 SCAN_COMMIT(pRExC_state,data,minlenp);
8aa23a47
YO
3516 if (mincount && last_str) {
3517 SV * const sv = data->last_found;
3518 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3519 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3520
3521 if (mg)
3522 mg->mg_len = -1;
3523 sv_setsv(sv, last_str);
3524 data->last_end = data->pos_min;
3525 data->last_start_min =
3526 data->pos_min - CHR_SVLEN(last_str);
3527 data->last_start_max = is_inf
3528 ? I32_MAX
3529 : data->pos_min + data->pos_delta
3530 - CHR_SVLEN(last_str);
3531 }
3532 data->longest = &(data->longest_float);
3533 }
3534 SvREFCNT_dec(last_str);
c277df42 3535 }
8aa23a47
YO
3536 if (data && (fl & SF_HAS_EVAL))
3537 data->flags |= SF_HAS_EVAL;
3538 optimize_curly_tail:
3539 if (OP(oscan) != CURLYX) {
3540 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3541 && NEXT_OFF(next))
3542 NEXT_OFF(oscan) += NEXT_OFF(next);
3543 }
3544 continue;
f56b6394 3545 default: /* REF, ANYOFV, and CLUMP only? */
8aa23a47 3546 if (flags & SCF_DO_SUBSTR) {
304ee84b 3547 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
8aa23a47
YO
3548 data->longest = &(data->longest_float);
3549 }
3550 is_inf = is_inf_internal = 1;
3551 if (flags & SCF_DO_STCLASS_OR)
3552 cl_anything(pRExC_state, data->start_class);
3553 flags &= ~SCF_DO_STCLASS;
3554 break;
c277df42 3555 }
8aa23a47 3556 }
e1d1eefb
YO
3557 else if (OP(scan) == LNBREAK) {
3558 if (flags & SCF_DO_STCLASS) {
3559 int value = 0;
3560 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3561 if (flags & SCF_DO_STCLASS_AND) {
3562 for (value = 0; value < 256; value++)
e64b1bd1 3563 if (!is_VERTWS_cp(value))
b9a59e08
KW
3564 ANYOF_BITMAP_CLEAR(data->start_class, value);
3565 }
3566 else {
e1d1eefb 3567 for (value = 0; value < 256; value++)
e64b1bd1 3568 if (is_VERTWS_cp(value))
b9a59e08
KW
3569 ANYOF_BITMAP_SET(data->start_class, value);
3570 }
e1d1eefb
YO
3571 if (flags & SCF_DO_STCLASS_OR)
3572 cl_and(data->start_class, and_withp);
3573 flags &= ~SCF_DO_STCLASS;
3574 }
3575 min += 1;
f9a79580 3576 delta += 1;
e1d1eefb
YO
3577 if (flags & SCF_DO_SUBSTR) {
3578 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3579 data->pos_min += 1;
f9a79580 3580 data->pos_delta += 1;
e1d1eefb
YO
3581 data->longest = &(data->longest_float);
3582 }
e1d1eefb 3583 }
f9a79580 3584 else if (OP(scan) == FOLDCHAR) {
ced7f090 3585 int d = ARG(scan) == LATIN_SMALL_LETTER_SHARP_S ? 1 : 2;
f9a79580
RGS
3586 flags &= ~SCF_DO_STCLASS;
3587 min += 1;
3588 delta += d;
3589 if (flags & SCF_DO_SUBSTR) {
3590 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3591 data->pos_min += 1;
3592 data->pos_delta += d;
3593 data->longest = &(data->longest_float);
3594 }
3595 }
e52fc539 3596 else if (REGNODE_SIMPLE(OP(scan))) {
8aa23a47 3597 int value = 0;
653099ff 3598
8aa23a47 3599 if (flags & SCF_DO_SUBSTR) {
304ee84b 3600 SCAN_COMMIT(pRExC_state,data,minlenp);
8aa23a47
YO
3601 data->pos_min++;
3602 }
3603 min++;
3604 if (flags & SCF_DO_STCLASS) {
3605 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
b515a41d 3606
8aa23a47
YO
3607 /* Some of the logic below assumes that switching
3608 locale on will only add false positives. */
3609 switch (PL_regkind[OP(scan)]) {
3610 case SANY:
3611 default:
3612 do_default:
3613 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3614 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3615 cl_anything(pRExC_state, data->start_class);
3616 break;
3617 case REG_ANY:
3618 if (OP(scan) == SANY)
3619 goto do_default;
3620 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3621 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3a15e693 3622 || ANYOF_CLASS_TEST_ANY_SET(data->start_class));
8aa23a47 3623 cl_anything(pRExC_state, data->start_class);
653099ff 3624 }
8aa23a47
YO
3625 if (flags & SCF_DO_STCLASS_AND || !value)
3626 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3627 break;
3628 case ANYOF:
3629 if (flags & SCF_DO_STCLASS_AND)
3630 cl_and(data->start_class,
3631 (struct regnode_charclass_class*)scan);
653099ff 3632 else
8aa23a47
YO
3633 cl_or(pRExC_state, data->start_class,
3634 (struct regnode_charclass_class*)scan);
3635 break;
3636 case ALNUM:
3637 if (flags & SCF_DO_STCLASS_AND) {
3638 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3639 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
980866de 3640 if (OP(scan) == ALNUMU) {
a12cf05f
KW
3641 for (value = 0; value < 256; value++) {
3642 if (!isWORDCHAR_L1(value)) {
3643 ANYOF_BITMAP_CLEAR(data->start_class, value);
3644 }
3645 }
3646 } else {
3647 for (value = 0; value < 256; value++) {
3648 if (!isALNUM(value)) {
3649 ANYOF_BITMAP_CLEAR(data->start_class, value);
3650 }
3651 }
3652 }
8aa23a47 3653 }
653099ff 3654 }
8aa23a47
YO
3655 else {
3656 if (data->start_class->flags & ANYOF_LOCALE)
3657 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
980866de 3658 else if (OP(scan) == ALNUMU) {
a12cf05f
KW
3659 for (value = 0; value < 256; value++) {
3660 if (isWORDCHAR_L1(value)) {
3661 ANYOF_BITMAP_SET(data->start_class, value);
3662 }
3663 }
3664 } else {
3665 for (value = 0; value < 256; value++) {
3666 if (isALNUM(value)) {
3667 ANYOF_BITMAP_SET(data->start_class, value);
3668 }
3669 }
3670 }
8aa23a47
YO
3671 }
3672 break;
8aa23a47
YO
3673 case NALNUM:
3674 if (flags & SCF_DO_STCLASS_AND) {
3675 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3676 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
980866de 3677 if (OP(scan) == NALNUMU) {
a12cf05f
KW
3678 for (value = 0; value < 256; value++) {
3679 if (isWORDCHAR_L1(value)) {
3680 ANYOF_BITMAP_CLEAR(data->start_class, value);
3681 }
3682 }
3683 } else {
3684 for (value = 0; value < 256; value++) {
3685 if (isALNUM(value)) {
36