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