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