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