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