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