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