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