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