This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Convert more EXACTFish nodes to EXACT when possible
[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 */
927 if (ANYOF_FLAGS(ssc) & ANYOF_POSIXL) {
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);
cfafade5 961 ANYOF_FLAGS(ssc) |= ANYOF_LOCALE|ANYOF_POSIXL;
cdd87c1d
KW
962 }
963 else {
964 ANYOF_POSIXL_ZERO(ssc);
965 }
653099ff
GS
966}
967
b423522f
KW
968STATIC int
969S_ssc_is_cp_posixl_init(pTHX_ const RExC_state_t *pRExC_state,
970 const regnode_ssc *ssc)
971{
972 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
973 * to the list of code points matched, and locale posix classes; hence does
974 * not check its flags) */
975
976 UV start, end;
977 bool ret;
978
979 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
980
71068078 981 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
982
983 invlist_iterinit(ssc->invlist);
984 ret = invlist_iternext(ssc->invlist, &start, &end)
985 && start == 0
986 && end == UV_MAX;
987
988 invlist_iterfinish(ssc->invlist);
989
990 if (! ret) {
991 return FALSE;
992 }
993
31f05a37
KW
994 if (RExC_contains_locale
995 && ! ((ANYOF_FLAGS(ssc) & ANYOF_LOCALE)
996 || ! (ANYOF_FLAGS(ssc) & ANYOF_POSIXL)
997 || ! ANYOF_POSIXL_TEST_ALL_SET(ssc)))
998 {
999 return FALSE;
b423522f
KW
1000 }
1001
1002 return TRUE;
1003}
1004
1005STATIC SV*
1006S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
31f05a37 1007 const regnode_charclass_posixl_fold* const node)
b423522f
KW
1008{
1009 /* Returns a mortal inversion list defining which code points are matched
1010 * by 'node', which is of type ANYOF. Handles complementing the result if
1011 * appropriate. If some code points aren't knowable at this time, the
31f05a37
KW
1012 * returned list must, and will, contain every code point that is a
1013 * possibility. */
b423522f
KW
1014
1015 SV* invlist = sv_2mortal(_new_invlist(0));
1016 unsigned int i;
1017 const U32 n = ARG(node);
31f05a37 1018 bool new_node_has_latin1 = FALSE;
b423522f
KW
1019
1020 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1021
1022 /* Look at the data structure created by S_set_ANYOF_arg() */
1023 if (n != ANYOF_NONBITMAP_EMPTY) {
1024 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1025 AV * const av = MUTABLE_AV(SvRV(rv));
1026 SV **const ary = AvARRAY(av);
1027 assert(RExC_rxi->data->what[n] == 's');
1028
1029 if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1030 invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1])));
1031 }
1032 else if (ary[0] && ary[0] != &PL_sv_undef) {
1033
1034 /* Here, no compile-time swash, and there are things that won't be
1035 * known until runtime -- we have to assume it could be anything */
1036 return _add_range_to_invlist(invlist, 0, UV_MAX);
1037 }
1038 else {
1039
1040 /* Here no compile-time swash, and no run-time only data. Use the
1041 * node's inversion list */
1042 invlist = sv_2mortal(invlist_clone(ary[2]));
1043 }
1044 }
1045
1046 /* An ANYOF node contains a bitmap for the first 256 code points, and an
1047 * inversion list for the others, but if there are code points that should
1048 * match only conditionally on the target string being UTF-8, those are
1049 * placed in the inversion list, and not the bitmap. Since there are
1050 * circumstances under which they could match, they are included in the
1051 * SSC. But if the ANYOF node is to be inverted, we have to exclude them
1052 * here, so that when we invert below, the end result actually does include
1053 * them. (Think about "\xe0" =~ /[^\xc0]/di;). We have to do this here
1054 * before we add the unconditionally matched code points */
1055 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1056 _invlist_intersection_complement_2nd(invlist,
1057 PL_UpperLatin1,
1058 &invlist);
1059 }
1060
1061 /* Add in the points from the bit map */
1062 for (i = 0; i < 256; i++) {
1063 if (ANYOF_BITMAP_TEST(node, i)) {
1064 invlist = add_cp_to_invlist(invlist, i);
31f05a37 1065 new_node_has_latin1 = TRUE;
b423522f
KW
1066 }
1067 }
1068
1069 /* If this can match all upper Latin1 code points, have to add them
1070 * as well */
7bc66b18 1071 if (ANYOF_FLAGS(node) & ANYOF_NON_UTF8_NON_ASCII_ALL) {
b423522f
KW
1072 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1073 }
1074
1075 /* Similarly for these */
1076 if (ANYOF_FLAGS(node) & ANYOF_ABOVE_LATIN1_ALL) {
1077 invlist = _add_range_to_invlist(invlist, 256, UV_MAX);
1078 }
1079
1080 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1081 _invlist_invert(invlist);
1082 }
31f05a37
KW
1083 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOF_LOC_FOLD) {
1084
1085 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1086 * locale. We can skip this if there are no 0-255 at all. */
1087 _invlist_union(invlist, PL_Latin1, &invlist);
1088 }
1089
1090 /* Similarly add the UTF-8 locale possible matches */
1091 if (ANYOF_FLAGS(node) & ANYOF_LOC_FOLD && ANYOF_UTF8_LOCALE_INVLIST(node))
1092 {
1093 _invlist_union_maybe_complement_2nd(invlist,
1094 ANYOF_UTF8_LOCALE_INVLIST(node),
1095 ANYOF_FLAGS(node) & ANYOF_INVERT,
1096 &invlist);
1097 }
b423522f
KW
1098
1099 return invlist;
1100}
1101
1051e1c4 1102/* These two functions currently do the exact same thing */
557bd3fb 1103#define ssc_init_zero ssc_init
653099ff 1104
cdd87c1d
KW
1105#define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1106#define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1107
b423522f
KW
1108STATIC void
1109S_ssc_flags_and(regnode_ssc *ssc, const U8 and_with)
1110{
1111 /* Take the flags 'and_with' and accumulate them anded into the flags for
a0dd4231
KW
1112 * the SSC 'ssc'. The non-SSC related flags in 'and_with' are ignored.
1113 * The flags 'and_with' should not come from another SSC (otherwise the
1114 * EMPTY_STRING flag won't work) */
b423522f 1115
eff8b7dc 1116 const U8 ssc_only_flags = ANYOF_FLAGS(ssc) & ~ANYOF_COMMON_FLAGS;
b423522f
KW
1117
1118 PERL_ARGS_ASSERT_SSC_FLAGS_AND;
1119
1120 /* Use just the SSC-related flags from 'and_with' */
eff8b7dc 1121 ANYOF_FLAGS(ssc) &= (and_with & ANYOF_COMMON_FLAGS);
b423522f
KW
1122 ANYOF_FLAGS(ssc) |= ssc_only_flags;
1123}
1124
557bd3fb 1125/* 'AND' a given class with another one. Can create false positives. 'ssc'
8efd3f97 1126 * should not be inverted. 'and_with->flags & ANYOF_POSIXL' should be 0 if
b8f7bb16 1127 * 'and_with' is a regnode_charclass instead of a regnode_ssc. */
cdd87c1d 1128
653099ff 1129STATIC void
b423522f 1130S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
7dcac5f6 1131 const regnode_charclass *and_with)
653099ff 1132{
cdd87c1d
KW
1133 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1134 * another SSC or a regular ANYOF class. Can create false positives. */
40d049e4 1135
a0dd4231
KW
1136 SV* anded_cp_list;
1137 U8 anded_flags;
1e6ade67 1138
cdd87c1d 1139 PERL_ARGS_ASSERT_SSC_AND;
653099ff 1140
71068078 1141 assert(is_ANYOF_SYNTHETIC(ssc));
a0dd4231
KW
1142
1143 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1144 * the code point inversion list and just the relevant flags */
71068078 1145 if (is_ANYOF_SYNTHETIC(and_with)) {
7dcac5f6 1146 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
a0dd4231 1147 anded_flags = ANYOF_FLAGS(and_with);
e9b08962
KW
1148
1149 /* XXX This is a kludge around what appears to be deficiencies in the
1150 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1151 * there are paths through the optimizer where it doesn't get weeded
1152 * out when it should. And if we don't make some extra provision for
1153 * it like the code just below, it doesn't get added when it should.
1154 * This solution is to add it only when AND'ing, which is here, and
1155 * only when what is being AND'ed is the pristine, original node
1156 * matching anything. Thus it is like adding it to ssc_anything() but
1157 * only when the result is to be AND'ed. Probably the same solution
1158 * could be adopted for the same problem we have with /l matching,
1159 * which is solved differently in S_ssc_init(), and that would lead to
1160 * fewer false positives than that solution has. But if this solution
1161 * creates bugs, the consequences are only that a warning isn't raised
1162 * that should be; while the consequences for having /l bugs is
1163 * incorrect matches */
7dcac5f6 1164 if (ssc_is_anything((regnode_ssc *)and_with)) {
e9b08962
KW
1165 anded_flags |= ANYOF_WARN_SUPER;
1166 }
a0dd4231
KW
1167 }
1168 else {
1169 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state,
31f05a37 1170 (regnode_charclass_posixl_fold*) and_with);
eff8b7dc 1171 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
a0dd4231
KW
1172 }
1173
1174 ANYOF_FLAGS(ssc) &= anded_flags;
cdd87c1d
KW
1175
1176 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1177 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1178 * 'and_with' may be inverted. When not inverted, we have the situation of
1179 * computing:
1180 * (C1 | P1) & (C2 | P2)
1181 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1182 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1183 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1184 * <= ((C1 & C2) | P1 | P2)
1185 * Alternatively, the last few steps could be:
1186 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1187 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1188 * <= (C1 | C2 | (P1 & P2))
1189 * We favor the second approach if either P1 or P2 is non-empty. This is
1190 * because these components are a barrier to doing optimizations, as what
1191 * they match cannot be known until the moment of matching as they are
1192 * dependent on the current locale, 'AND"ing them likely will reduce or
1193 * eliminate them.
1194 * But we can do better if we know that C1,P1 are in their initial state (a
1195 * frequent occurrence), each matching everything:
1196 * (<everything>) & (C2 | P2) = C2 | P2
1197 * Similarly, if C2,P2 are in their initial state (again a frequent
1198 * occurrence), the result is a no-op
1199 * (C1 | P1) & (<everything>) = C1 | P1
1200 *
1201 * Inverted, we have
1202 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1203 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1204 * <= (C1 & ~C2) | (P1 & ~P2)
1205 * */
1aa99e6b 1206
a0dd4231 1207 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
71068078 1208 && ! is_ANYOF_SYNTHETIC(and_with))
a0dd4231 1209 {
cdd87c1d 1210 unsigned int i;
8951c461 1211
cdd87c1d
KW
1212 ssc_intersection(ssc,
1213 anded_cp_list,
1214 FALSE /* Has already been inverted */
1215 );
c6b76537 1216
cdd87c1d
KW
1217 /* If either P1 or P2 is empty, the intersection will be also; can skip
1218 * the loop */
1219 if (! (ANYOF_FLAGS(and_with) & ANYOF_POSIXL)) {
1220 ANYOF_POSIXL_ZERO(ssc);
1221 }
1222 else if (ANYOF_POSIXL_TEST_ANY_SET(ssc)) {
1223
1224 /* Note that the Posix class component P from 'and_with' actually
1225 * looks like:
1226 * P = Pa | Pb | ... | Pn
1227 * where each component is one posix class, such as in [\w\s].
1228 * Thus
1229 * ~P = ~(Pa | Pb | ... | Pn)
1230 * = ~Pa & ~Pb & ... & ~Pn
1231 * <= ~Pa | ~Pb | ... | ~Pn
1232 * The last is something we can easily calculate, but unfortunately
1233 * is likely to have many false positives. We could do better
1234 * in some (but certainly not all) instances if two classes in
1235 * P have known relationships. For example
1236 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1237 * So
1238 * :lower: & :print: = :lower:
1239 * And similarly for classes that must be disjoint. For example,
1240 * since \s and \w can have no elements in common based on rules in
1241 * the POSIX standard,
1242 * \w & ^\S = nothing
1243 * Unfortunately, some vendor locales do not meet the Posix
1244 * standard, in particular almost everything by Microsoft.
1245 * The loop below just changes e.g., \w into \W and vice versa */
1246
31f05a37 1247 regnode_charclass_posixl_fold temp;
cdd87c1d
KW
1248 int add = 1; /* To calculate the index of the complement */
1249
1250 ANYOF_POSIXL_ZERO(&temp);
1251 for (i = 0; i < ANYOF_MAX; i++) {
1252 assert(i % 2 != 0
7dcac5f6
KW
1253 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1254 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
cdd87c1d 1255
7dcac5f6 1256 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
cdd87c1d
KW
1257 ANYOF_POSIXL_SET(&temp, i + add);
1258 }
1259 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1260 }
1261 ANYOF_POSIXL_AND(&temp, ssc);
c6b76537 1262
cdd87c1d
KW
1263 } /* else ssc already has no posixes */
1264 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1265 in its initial state */
71068078 1266 else if (! is_ANYOF_SYNTHETIC(and_with)
7dcac5f6 1267 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
cdd87c1d
KW
1268 {
1269 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1270 * copy it over 'ssc' */
1271 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
71068078 1272 if (is_ANYOF_SYNTHETIC(and_with)) {
cdd87c1d
KW
1273 StructCopy(and_with, ssc, regnode_ssc);
1274 }
1275 else {
1276 ssc->invlist = anded_cp_list;
1277 ANYOF_POSIXL_ZERO(ssc);
1278 if (ANYOF_FLAGS(and_with) & ANYOF_POSIXL) {
7dcac5f6 1279 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
cdd87c1d
KW
1280 }
1281 }
1282 }
1283 else if ((ANYOF_FLAGS(ssc) & ANYOF_POSIXL)
1284 || (ANYOF_FLAGS(and_with) & ANYOF_POSIXL))
1285 {
1286 /* One or the other of P1, P2 is non-empty. */
7dcac5f6 1287 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
cdd87c1d
KW
1288 ssc_union(ssc, anded_cp_list, FALSE);
1289 }
1290 else { /* P1 = P2 = empty */
1291 ssc_intersection(ssc, anded_cp_list, FALSE);
1292 }
137165a6 1293 }
653099ff
GS
1294}
1295
653099ff 1296STATIC void
cdd87c1d 1297S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
7dcac5f6 1298 const regnode_charclass *or_with)
653099ff 1299{
cdd87c1d
KW
1300 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1301 * another SSC or a regular ANYOF class. Can create false positives if
1302 * 'or_with' is to be inverted. */
7918f24d 1303
a0dd4231
KW
1304 SV* ored_cp_list;
1305 U8 ored_flags;
c6b76537 1306
cdd87c1d 1307 PERL_ARGS_ASSERT_SSC_OR;
c6b76537 1308
71068078 1309 assert(is_ANYOF_SYNTHETIC(ssc));
a0dd4231
KW
1310
1311 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1312 * the code point inversion list and just the relevant flags */
71068078 1313 if (is_ANYOF_SYNTHETIC(or_with)) {
7dcac5f6 1314 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
a0dd4231
KW
1315 ored_flags = ANYOF_FLAGS(or_with);
1316 }
1317 else {
1318 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state,
31f05a37 1319 (regnode_charclass_posixl_fold*) or_with);
eff8b7dc 1320 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
a0dd4231
KW
1321 }
1322
1323 ANYOF_FLAGS(ssc) |= ored_flags;
cdd87c1d
KW
1324
1325 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1326 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1327 * 'or_with' may be inverted. When not inverted, we have the simple
1328 * situation of computing:
1329 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1330 * If P1|P2 yields a situation with both a class and its complement are
1331 * set, like having both \w and \W, this matches all code points, and we
1332 * can delete these from the P component of the ssc going forward. XXX We
1333 * might be able to delete all the P components, but I (khw) am not certain
1334 * about this, and it is better to be safe.
1335 *
1336 * Inverted, we have
1337 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1338 * <= (C1 | P1) | ~C2
1339 * <= (C1 | ~C2) | P1
1340 * (which results in actually simpler code than the non-inverted case)
1341 * */
9826f543 1342
a0dd4231 1343 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
71068078 1344 && ! is_ANYOF_SYNTHETIC(or_with))
a0dd4231 1345 {
cdd87c1d
KW
1346 /* We ignore P2, leaving P1 going forward */
1347 }
1348 else { /* Not inverted */
7dcac5f6 1349 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
cdd87c1d
KW
1350 if (ANYOF_POSIXL_TEST_ANY_SET(ssc)) {
1351 unsigned int i;
1352 for (i = 0; i < ANYOF_MAX; i += 2) {
1353 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1354 {
1355 ssc_match_all_cp(ssc);
1356 ANYOF_POSIXL_CLEAR(ssc, i);
1357 ANYOF_POSIXL_CLEAR(ssc, i+1);
1358 if (! ANYOF_POSIXL_TEST_ANY_SET(ssc)) {
1359 ANYOF_FLAGS(ssc) &= ~ANYOF_POSIXL;
1360 }
1361 }
1362 }
1363 }
1aa99e6b 1364 }
cdd87c1d
KW
1365
1366 ssc_union(ssc,
1367 ored_cp_list,
1368 FALSE /* Already has been inverted */
1369 );
653099ff
GS
1370}
1371
b423522f
KW
1372PERL_STATIC_INLINE void
1373S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1374{
1375 PERL_ARGS_ASSERT_SSC_UNION;
1376
71068078 1377 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1378
1379 _invlist_union_maybe_complement_2nd(ssc->invlist,
1380 invlist,
1381 invert2nd,
1382 &ssc->invlist);
1383}
1384
1385PERL_STATIC_INLINE void
1386S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1387 SV* const invlist,
1388 const bool invert2nd)
1389{
1390 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1391
71068078 1392 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1393
1394 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1395 invlist,
1396 invert2nd,
1397 &ssc->invlist);
1398}
1399
1400PERL_STATIC_INLINE void
1401S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1402{
1403 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1404
71068078 1405 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1406
1407 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1408}
1409
1410PERL_STATIC_INLINE void
1411S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1412{
1413 /* AND just the single code point 'cp' into the SSC 'ssc' */
1414
1415 SV* cp_list = _new_invlist(2);
1416
1417 PERL_ARGS_ASSERT_SSC_CP_AND;
1418
71068078 1419 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1420
1421 cp_list = add_cp_to_invlist(cp_list, cp);
1422 ssc_intersection(ssc, cp_list,
1423 FALSE /* Not inverted */
1424 );
1425 SvREFCNT_dec_NN(cp_list);
1426}
1427
1428PERL_STATIC_INLINE void
1429S_ssc_clear_locale(pTHX_ regnode_ssc *ssc)
1430{
1431 /* Set the SSC 'ssc' to not match any locale things */
1432
1433 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1434
71068078 1435 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1436
1437 ANYOF_POSIXL_ZERO(ssc);
1438 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1439}
1440
1441STATIC void
1442S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1443{
1444 /* The inversion list in the SSC is marked mortal; now we need a more
1445 * permanent copy, which is stored the same way that is done in a regular
1446 * ANYOF node, with the first 256 code points in a bit map */
1447
1448 SV* invlist = invlist_clone(ssc->invlist);
1449
1450 PERL_ARGS_ASSERT_SSC_FINALIZE;
1451
71068078 1452 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f 1453
a0dd4231
KW
1454 /* The code in this file assumes that all but these flags aren't relevant
1455 * to the SSC, except ANYOF_EMPTY_STRING, which should be cleared by the
1456 * time we reach here */
eff8b7dc 1457 assert(! (ANYOF_FLAGS(ssc) & ~ANYOF_COMMON_FLAGS));
a0dd4231 1458
b423522f
KW
1459 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1460
1461 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL, FALSE);
1462
31f05a37
KW
1463 /* The code points that could match under /li are already incorporated into
1464 * the inversion list and bit map */
1465 ANYOF_FLAGS(ssc) &= ~ANYOF_LOC_FOLD;
1466
b423522f
KW
1467 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE) || RExC_contains_locale);
1468}
1469
a3621e74
YO
1470#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1471#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
1472#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
538e84ed
KW
1473#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
1474 ? (TRIE_LIST_CUR( idx ) - 1) \
1475 : 0 )
a3621e74 1476
3dab1dad
YO
1477
1478#ifdef DEBUGGING
07be1b83 1479/*
2b8b4781
NC
1480 dump_trie(trie,widecharmap,revcharmap)
1481 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1482 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
3dab1dad
YO
1483
1484 These routines dump out a trie in a somewhat readable format.
07be1b83
YO
1485 The _interim_ variants are used for debugging the interim
1486 tables that are used to generate the final compressed
1487 representation which is what dump_trie expects.
1488
486ec47a 1489 Part of the reason for their existence is to provide a form
3dab1dad 1490 of documentation as to how the different representations function.
07be1b83
YO
1491
1492*/
3dab1dad
YO
1493
1494/*
3dab1dad
YO
1495 Dumps the final compressed table form of the trie to Perl_debug_log.
1496 Used for debugging make_trie().
1497*/
b9a59e08 1498
3dab1dad 1499STATIC void
2b8b4781
NC
1500S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1501 AV *revcharmap, U32 depth)
3dab1dad
YO
1502{
1503 U32 state;
ab3bbdeb 1504 SV *sv=sv_newmortal();
55eed653 1505 int colwidth= widecharmap ? 6 : 4;
2e64971a 1506 U16 word;
3dab1dad
YO
1507 GET_RE_DEBUG_FLAGS_DECL;
1508
7918f24d 1509 PERL_ARGS_ASSERT_DUMP_TRIE;
ab3bbdeb 1510
3dab1dad
YO
1511 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1512 (int)depth * 2 + 2,"",
1513 "Match","Base","Ofs" );
1514
1515 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2b8b4781 1516 SV ** const tmp = av_fetch( revcharmap, state, 0);
3dab1dad 1517 if ( tmp ) {
538e84ed 1518 PerlIO_printf( Perl_debug_log, "%*s",
ab3bbdeb 1519 colwidth,
538e84ed 1520 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1521 PL_colors[0], PL_colors[1],
1522 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed
KW
1523 PERL_PV_ESCAPE_FIRSTCHAR
1524 )
ab3bbdeb 1525 );
3dab1dad
YO
1526 }
1527 }
1528 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1529 (int)depth * 2 + 2,"");
1530
1531 for( state = 0 ; state < trie->uniquecharcount ; state++ )
ab3bbdeb 1532 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
3dab1dad
YO
1533 PerlIO_printf( Perl_debug_log, "\n");
1534
1e2e3d02 1535 for( state = 1 ; state < trie->statecount ; state++ ) {
be8e71aa 1536 const U32 base = trie->states[ state ].trans.base;
3dab1dad 1537
538e84ed
KW
1538 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1539 (int)depth * 2 + 2,"", (UV)state);
3dab1dad
YO
1540
1541 if ( trie->states[ state ].wordnum ) {
538e84ed
KW
1542 PerlIO_printf( Perl_debug_log, " W%4X",
1543 trie->states[ state ].wordnum );
3dab1dad
YO
1544 } else {
1545 PerlIO_printf( Perl_debug_log, "%6s", "" );
1546 }
1547
1548 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1549
1550 if ( base ) {
1551 U32 ofs = 0;
1552
1553 while( ( base + ofs < trie->uniquecharcount ) ||
1554 ( base + ofs - trie->uniquecharcount < trie->lasttrans
538e84ed
KW
1555 && trie->trans[ base + ofs - trie->uniquecharcount ].check
1556 != state))
3dab1dad
YO
1557 ofs++;
1558
1559 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1560
1561 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
538e84ed
KW
1562 if ( ( base + ofs >= trie->uniquecharcount )
1563 && ( base + ofs - trie->uniquecharcount
1564 < trie->lasttrans )
1565 && trie->trans[ base + ofs
1566 - trie->uniquecharcount ].check == state )
3dab1dad 1567 {
ab3bbdeb
YO
1568 PerlIO_printf( Perl_debug_log, "%*"UVXf,
1569 colwidth,
538e84ed
KW
1570 (UV)trie->trans[ base + ofs
1571 - trie->uniquecharcount ].next );
3dab1dad 1572 } else {
ab3bbdeb 1573 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
3dab1dad
YO
1574 }
1575 }
1576
1577 PerlIO_printf( Perl_debug_log, "]");
1578
1579 }
1580 PerlIO_printf( Perl_debug_log, "\n" );
1581 }
538e84ed
KW
1582 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
1583 (int)depth*2, "");
2e64971a
DM
1584 for (word=1; word <= trie->wordcount; word++) {
1585 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1586 (int)word, (int)(trie->wordinfo[word].prev),
1587 (int)(trie->wordinfo[word].len));
1588 }
1589 PerlIO_printf(Perl_debug_log, "\n" );
538e84ed 1590}
3dab1dad 1591/*
3dab1dad 1592 Dumps a fully constructed but uncompressed trie in list form.
538e84ed 1593 List tries normally only are used for construction when the number of
3dab1dad
YO
1594 possible chars (trie->uniquecharcount) is very high.
1595 Used for debugging make_trie().
1596*/
1597STATIC void
55eed653 1598S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
1599 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1600 U32 depth)
3dab1dad
YO
1601{
1602 U32 state;
ab3bbdeb 1603 SV *sv=sv_newmortal();
55eed653 1604 int colwidth= widecharmap ? 6 : 4;
3dab1dad 1605 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1606
1607 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1608
3dab1dad 1609 /* print out the table precompression. */
ab3bbdeb
YO
1610 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1611 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1612 "------:-----+-----------------\n" );
538e84ed 1613
3dab1dad
YO
1614 for( state=1 ; state < next_alloc ; state ++ ) {
1615 U16 charid;
538e84ed 1616
ab3bbdeb 1617 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
3dab1dad
YO
1618 (int)depth * 2 + 2,"", (UV)state );
1619 if ( ! trie->states[ state ].wordnum ) {
1620 PerlIO_printf( Perl_debug_log, "%5s| ","");
1621 } else {
1622 PerlIO_printf( Perl_debug_log, "W%4x| ",
1623 trie->states[ state ].wordnum
1624 );
1625 }
1626 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
538e84ed
KW
1627 SV ** const tmp = av_fetch( revcharmap,
1628 TRIE_LIST_ITEM(state,charid).forid, 0);
ab3bbdeb
YO
1629 if ( tmp ) {
1630 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1631 colwidth,
538e84ed
KW
1632 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
1633 colwidth,
1634 PL_colors[0], PL_colors[1],
1635 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
1636 | PERL_PV_ESCAPE_FIRSTCHAR
ab3bbdeb 1637 ) ,
1e2e3d02
YO
1638 TRIE_LIST_ITEM(state,charid).forid,
1639 (UV)TRIE_LIST_ITEM(state,charid).newstate
1640 );
538e84ed 1641 if (!(charid % 10))
664e119d
RGS
1642 PerlIO_printf(Perl_debug_log, "\n%*s| ",
1643 (int)((depth * 2) + 14), "");
1e2e3d02 1644 }
ab3bbdeb
YO
1645 }
1646 PerlIO_printf( Perl_debug_log, "\n");
3dab1dad 1647 }
538e84ed 1648}
3dab1dad
YO
1649
1650/*
3dab1dad 1651 Dumps a fully constructed but uncompressed trie in table form.
538e84ed
KW
1652 This is the normal DFA style state transition table, with a few
1653 twists to facilitate compression later.
3dab1dad
YO
1654 Used for debugging make_trie().
1655*/
1656STATIC void
55eed653 1657S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
1658 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1659 U32 depth)
3dab1dad
YO
1660{
1661 U32 state;
1662 U16 charid;
ab3bbdeb 1663 SV *sv=sv_newmortal();
55eed653 1664 int colwidth= widecharmap ? 6 : 4;
3dab1dad 1665 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1666
1667 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
538e84ed 1668
3dab1dad
YO
1669 /*
1670 print out the table precompression so that we can do a visual check
1671 that they are identical.
1672 */
538e84ed 1673
3dab1dad
YO
1674 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1675
1676 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2b8b4781 1677 SV ** const tmp = av_fetch( revcharmap, charid, 0);
3dab1dad 1678 if ( tmp ) {
538e84ed 1679 PerlIO_printf( Perl_debug_log, "%*s",
ab3bbdeb 1680 colwidth,
538e84ed 1681 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1682 PL_colors[0], PL_colors[1],
1683 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed
KW
1684 PERL_PV_ESCAPE_FIRSTCHAR
1685 )
ab3bbdeb 1686 );
3dab1dad
YO
1687 }
1688 }
1689
1690 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1691
1692 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb 1693 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
3dab1dad
YO
1694 }
1695
1696 PerlIO_printf( Perl_debug_log, "\n" );
1697
1698 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1699
538e84ed 1700 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
3dab1dad
YO
1701 (int)depth * 2 + 2,"",
1702 (UV)TRIE_NODENUM( state ) );
1703
1704 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb
YO
1705 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1706 if (v)
1707 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1708 else
1709 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
3dab1dad
YO
1710 }
1711 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
538e84ed
KW
1712 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
1713 (UV)trie->trans[ state ].check );
3dab1dad 1714 } else {
538e84ed
KW
1715 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
1716 (UV)trie->trans[ state ].check,
3dab1dad
YO
1717 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1718 }
1719 }
07be1b83 1720}
3dab1dad
YO
1721
1722#endif
1723
2e64971a 1724
786e8c11
YO
1725/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1726 startbranch: the first branch in the whole branch sequence
1727 first : start branch of sequence of branch-exact nodes.
1728 May be the same as startbranch
1729 last : Thing following the last branch.
1730 May be the same as tail.
1731 tail : item following the branch sequence
1732 count : words in the sequence
1733 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1734 depth : indent depth
3dab1dad 1735
786e8c11 1736Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
07be1b83 1737
786e8c11
YO
1738A trie is an N'ary tree where the branches are determined by digital
1739decomposition of the key. IE, at the root node you look up the 1st character and
1740follow that branch repeat until you find the end of the branches. Nodes can be
1741marked as "accepting" meaning they represent a complete word. Eg:
07be1b83 1742
786e8c11 1743 /he|she|his|hers/
72f13be8 1744
786e8c11
YO
1745would convert into the following structure. Numbers represent states, letters
1746following numbers represent valid transitions on the letter from that state, if
1747the number is in square brackets it represents an accepting state, otherwise it
1748will be in parenthesis.
07be1b83 1749
786e8c11
YO
1750 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1751 | |
1752 | (2)
1753 | |
1754 (1) +-i->(6)-+-s->[7]
1755 |
1756 +-s->(3)-+-h->(4)-+-e->[5]
07be1b83 1757
786e8c11
YO
1758 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1759
1760This shows that when matching against the string 'hers' we will begin at state 1
1761read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1762then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1763is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1764single traverse. We store a mapping from accepting to state to which word was
1765matched, and then when we have multiple possibilities we try to complete the
1766rest of the regex in the order in which they occured in the alternation.
1767
1768The only prior NFA like behaviour that would be changed by the TRIE support is
1769the silent ignoring of duplicate alternations which are of the form:
1770
1771 / (DUPE|DUPE) X? (?{ ... }) Y /x
1772
4b714af6 1773Thus EVAL blocks following a trie may be called a different number of times with
786e8c11 1774and without the optimisation. With the optimisations dupes will be silently
486ec47a 1775ignored. This inconsistent behaviour of EVAL type nodes is well established as
786e8c11
YO
1776the following demonstrates:
1777
1778 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1779
1780which prints out 'word' three times, but
1781
1782 'words'=~/(word|word|word)(?{ print $1 })S/
1783
1784which doesnt print it out at all. This is due to other optimisations kicking in.
1785
1786Example of what happens on a structural level:
1787
486ec47a 1788The regexp /(ac|ad|ab)+/ will produce the following debug output:
786e8c11
YO
1789
1790 1: CURLYM[1] {1,32767}(18)
1791 5: BRANCH(8)
1792 6: EXACT <ac>(16)
1793 8: BRANCH(11)
1794 9: EXACT <ad>(16)
1795 11: BRANCH(14)
1796 12: EXACT <ab>(16)
1797 16: SUCCEED(0)
1798 17: NOTHING(18)
1799 18: END(0)
1800
1801This would be optimizable with startbranch=5, first=5, last=16, tail=16
1802and should turn into:
1803
1804 1: CURLYM[1] {1,32767}(18)
1805 5: TRIE(16)
1806 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1807 <ac>
1808 <ad>
1809 <ab>
1810 16: SUCCEED(0)
1811 17: NOTHING(18)
1812 18: END(0)
1813
1814Cases where tail != last would be like /(?foo|bar)baz/:
1815
1816 1: BRANCH(4)
1817 2: EXACT <foo>(8)
1818 4: BRANCH(7)
1819 5: EXACT <bar>(8)
1820 7: TAIL(8)
1821 8: EXACT <baz>(10)
1822 10: END(0)
1823
1824which would be optimizable with startbranch=1, first=1, last=7, tail=8
1825and would end up looking like:
1826
1827 1: TRIE(8)
1828 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1829 <foo>
1830 <bar>
1831 7: TAIL(8)
1832 8: EXACT <baz>(10)
1833 10: END(0)
1834
c80e42f3 1835 d = uvchr_to_utf8_flags(d, uv, 0);
786e8c11
YO
1836
1837is the recommended Unicode-aware way of saying
1838
1839 *(d++) = uv;
1840*/
1841
fab2782b 1842#define TRIE_STORE_REVCHAR(val) \
786e8c11 1843 STMT_START { \
73031816 1844 if (UTF) { \
fab2782b 1845 SV *zlopp = newSV(7); /* XXX: optimize me */ \
88c9ea1e 1846 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
c80e42f3 1847 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
73031816
NC
1848 SvCUR_set(zlopp, kapow - flrbbbbb); \
1849 SvPOK_on(zlopp); \
1850 SvUTF8_on(zlopp); \
1851 av_push(revcharmap, zlopp); \
1852 } else { \
fab2782b 1853 char ooooff = (char)val; \
73031816
NC
1854 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
1855 } \
1856 } STMT_END
786e8c11 1857
914a25d5
KW
1858/* This gets the next character from the input, folding it if not already
1859 * folded. */
1860#define TRIE_READ_CHAR STMT_START { \
1861 wordlen++; \
1862 if ( UTF ) { \
1863 /* if it is UTF then it is either already folded, or does not need \
1864 * folding */ \
1c1d615a 1865 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
914a25d5
KW
1866 } \
1867 else if (folder == PL_fold_latin1) { \
7d006b13
KW
1868 /* This folder implies Unicode rules, which in the range expressible \
1869 * by not UTF is the lower case, with the two exceptions, one of \
1870 * which should have been taken care of before calling this */ \
1871 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
1872 uvc = toLOWER_L1(*uc); \
1873 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
1874 len = 1; \
914a25d5
KW
1875 } else { \
1876 /* raw data, will be folded later if needed */ \
1877 uvc = (U32)*uc; \
1878 len = 1; \
1879 } \
786e8c11
YO
1880} STMT_END
1881
1882
1883
1884#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1885 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
f9003953
NC
1886 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1887 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
786e8c11
YO
1888 } \
1889 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1890 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1891 TRIE_LIST_CUR( state )++; \
1892} STMT_END
07be1b83 1893
786e8c11
YO
1894#define TRIE_LIST_NEW(state) STMT_START { \
1895 Newxz( trie->states[ state ].trans.list, \
1896 4, reg_trie_trans_le ); \
1897 TRIE_LIST_CUR( state ) = 1; \
1898 TRIE_LIST_LEN( state ) = 4; \
1899} STMT_END
07be1b83 1900
786e8c11
YO
1901#define TRIE_HANDLE_WORD(state) STMT_START { \
1902 U16 dupe= trie->states[ state ].wordnum; \
1903 regnode * const noper_next = regnext( noper ); \
1904 \
786e8c11
YO
1905 DEBUG_r({ \
1906 /* store the word for dumping */ \
1907 SV* tmp; \
1908 if (OP(noper) != NOTHING) \
740cce10 1909 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
786e8c11 1910 else \
740cce10 1911 tmp = newSVpvn_utf8( "", 0, UTF ); \
2b8b4781 1912 av_push( trie_words, tmp ); \
786e8c11
YO
1913 }); \
1914 \
1915 curword++; \
2e64971a
DM
1916 trie->wordinfo[curword].prev = 0; \
1917 trie->wordinfo[curword].len = wordlen; \
1918 trie->wordinfo[curword].accept = state; \
786e8c11
YO
1919 \
1920 if ( noper_next < tail ) { \
1921 if (!trie->jump) \
538e84ed
KW
1922 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
1923 sizeof(U16) ); \
7f69552c 1924 trie->jump[curword] = (U16)(noper_next - convert); \
786e8c11
YO
1925 if (!jumper) \
1926 jumper = noper_next; \
1927 if (!nextbranch) \
1928 nextbranch= regnext(cur); \
1929 } \
1930 \
1931 if ( dupe ) { \
2e64971a
DM
1932 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
1933 /* chain, so that when the bits of chain are later */\
1934 /* linked together, the dups appear in the chain */\
1935 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1936 trie->wordinfo[dupe].prev = curword; \
786e8c11
YO
1937 } else { \
1938 /* we haven't inserted this word yet. */ \
1939 trie->states[ state ].wordnum = curword; \
1940 } \
1941} STMT_END
07be1b83 1942
3dab1dad 1943
786e8c11
YO
1944#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1945 ( ( base + charid >= ucharcount \
1946 && base + charid < ubound \
1947 && state == trie->trans[ base - ucharcount + charid ].check \
1948 && trie->trans[ base - ucharcount + charid ].next ) \
1949 ? trie->trans[ base - ucharcount + charid ].next \
1950 : ( state==1 ? special : 0 ) \
1951 )
3dab1dad 1952
786e8c11
YO
1953#define MADE_TRIE 1
1954#define MADE_JUMP_TRIE 2
1955#define MADE_EXACT_TRIE 4
3dab1dad 1956
a3621e74 1957STATIC I32
538e84ed
KW
1958S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
1959 regnode *first, regnode *last, regnode *tail,
1960 U32 word_count, U32 flags, U32 depth)
a3621e74 1961{
27da23d5 1962 dVAR;
a3621e74
YO
1963 /* first pass, loop through and scan words */
1964 reg_trie_data *trie;
55eed653 1965 HV *widecharmap = NULL;
2b8b4781 1966 AV *revcharmap = newAV();
a3621e74 1967 regnode *cur;
a3621e74
YO
1968 STRLEN len = 0;
1969 UV uvc = 0;
1970 U16 curword = 0;
1971 U32 next_alloc = 0;
786e8c11
YO
1972 regnode *jumper = NULL;
1973 regnode *nextbranch = NULL;
7f69552c 1974 regnode *convert = NULL;
2e64971a 1975 U32 *prev_states; /* temp array mapping each state to previous one */
a3621e74 1976 /* we just use folder as a flag in utf8 */
1e696034 1977 const U8 * folder = NULL;
a3621e74 1978
2b8b4781 1979#ifdef DEBUGGING
cf78de0b 1980 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2b8b4781
NC
1981 AV *trie_words = NULL;
1982 /* along with revcharmap, this only used during construction but both are
1983 * useful during debugging so we store them in the struct when debugging.
8e11feef 1984 */
2b8b4781 1985#else
cf78de0b 1986 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
3dab1dad 1987 STRLEN trie_charcount=0;
3dab1dad 1988#endif
2b8b4781 1989 SV *re_trie_maxbuff;
a3621e74 1990 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1991
1992 PERL_ARGS_ASSERT_MAKE_TRIE;
72f13be8
YO
1993#ifndef DEBUGGING
1994 PERL_UNUSED_ARG(depth);
1995#endif
a3621e74 1996
1e696034 1997 switch (flags) {
79a81a6e 1998 case EXACT: break;
2f7f8cb1 1999 case EXACTFA:
fab2782b 2000 case EXACTFU_SS:
1e696034
KW
2001 case EXACTFU: folder = PL_fold_latin1; break;
2002 case EXACTF: folder = PL_fold; break;
fab2782b 2003 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1e696034
KW
2004 }
2005
c944940b 2006 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
a3621e74 2007 trie->refcount = 1;
3dab1dad 2008 trie->startstate = 1;
786e8c11 2009 trie->wordcount = word_count;
f8fc2ecf 2010 RExC_rxi->data->data[ data_slot ] = (void*)trie;
c944940b 2011 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
fab2782b 2012 if (flags == EXACT)
c944940b 2013 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2e64971a
DM
2014 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2015 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2016
a3621e74 2017 DEBUG_r({
2b8b4781 2018 trie_words = newAV();
a3621e74 2019 });
a3621e74 2020
0111c4fd 2021 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
a3621e74 2022 if (!SvIOK(re_trie_maxbuff)) {
0111c4fd 2023 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
a3621e74 2024 }
df826430 2025 DEBUG_TRIE_COMPILE_r({
538e84ed
KW
2026 PerlIO_printf( Perl_debug_log,
2027 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2028 (int)depth * 2 + 2, "",
2029 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2030 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
3dab1dad 2031 });
538e84ed 2032
7f69552c
YO
2033 /* Find the node we are going to overwrite */
2034 if ( first == startbranch && OP( last ) != BRANCH ) {
2035 /* whole branch chain */
2036 convert = first;
2037 } else {
2038 /* branch sub-chain */
2039 convert = NEXTOPER( first );
2040 }
538e84ed 2041
a3621e74
YO
2042 /* -- First loop and Setup --
2043
2044 We first traverse the branches and scan each word to determine if it
2045 contains widechars, and how many unique chars there are, this is
2046 important as we have to build a table with at least as many columns as we
2047 have unique chars.
2048
2049 We use an array of integers to represent the character codes 0..255
538e84ed
KW
2050 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2051 the native representation of the character value as the key and IV's for
2052 the coded index.
a3621e74
YO
2053
2054 *TODO* If we keep track of how many times each character is used we can
2055 remap the columns so that the table compression later on is more
3b753521 2056 efficient in terms of memory by ensuring the most common value is in the
a3621e74
YO
2057 middle and the least common are on the outside. IMO this would be better
2058 than a most to least common mapping as theres a decent chance the most
2059 common letter will share a node with the least common, meaning the node
486ec47a 2060 will not be compressible. With a middle is most common approach the worst
a3621e74
YO
2061 case is when we have the least common nodes twice.
2062
2063 */
2064
a3621e74 2065 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
df826430 2066 regnode *noper = NEXTOPER( cur );
e1ec3a88 2067 const U8 *uc = (U8*)STRING( noper );
df826430 2068 const U8 *e = uc + STR_LEN( noper );
a3621e74 2069 STRLEN foldlen = 0;
07be1b83 2070 U32 wordlen = 0; /* required init */
afa96d92
KW
2071 STRLEN minbytes = 0;
2072 STRLEN maxbytes = 0;
538e84ed
KW
2073 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2074 bitmap?*/
a3621e74 2075
3dab1dad 2076 if (OP(noper) == NOTHING) {
df826430
YO
2077 regnode *noper_next= regnext(noper);
2078 if (noper_next != tail && OP(noper_next) == flags) {
2079 noper = noper_next;
2080 uc= (U8*)STRING(noper);
2081 e= uc + STR_LEN(noper);
2082 trie->minlen= STR_LEN(noper);
2083 } else {
2084 trie->minlen= 0;
2085 continue;
2086 }
3dab1dad 2087 }
df826430 2088
fab2782b 2089 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
02daf0ab
YO
2090 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2091 regardless of encoding */
fab2782b
YO
2092 if (OP( noper ) == EXACTFU_SS) {
2093 /* false positives are ok, so just set this */
0dc4a61d 2094 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
fab2782b
YO
2095 }
2096 }
a3621e74 2097 for ( ; uc < e ; uc += len ) {
3dab1dad 2098 TRIE_CHARCOUNT(trie)++;
a3621e74 2099 TRIE_READ_CHAR;
645de4ce
KW
2100
2101 /* Acummulate to the current values, the range in the number of
2102 * bytes that this character could match. The max is presumed to
2103 * be the same as the folded input (which TRIE_READ_CHAR returns),
2104 * except that when this is not in UTF-8, it could be matched
2105 * against a string which is UTF-8, and the variant characters
2106 * could be 2 bytes instead of the 1 here. Likewise, for the
2107 * minimum number of bytes when not folded. When folding, the min
2108 * is assumed to be 1 byte could fold to match the single character
2109 * here, or in the case of a multi-char fold, 1 byte can fold to
2110 * the whole sequence. 'foldlen' is used to denote whether we are
2111 * in such a sequence, skipping the min setting if so. XXX TODO
2112 * Use the exact list of what folds to each character, from
2113 * PL_utf8_foldclosures */
2114 if (UTF) {
2115 maxbytes += UTF8SKIP(uc);
2116 if (! folder) {
2117 /* A non-UTF-8 string could be 1 byte to match our 2 */
2118 minbytes += (UTF8_IS_DOWNGRADEABLE_START(*uc))
2119 ? 1
2120 : UTF8SKIP(uc);
2121 }
2122 else {
2123 if (foldlen) {
2124 foldlen -= UTF8SKIP(uc);
2125 }
2126 else {
3a8bbffb 2127 foldlen = is_MULTI_CHAR_FOLD_utf8(uc);
645de4ce
KW
2128 minbytes++;
2129 }
2130 }
2131 }
2132 else {
2133 maxbytes += (UNI_IS_INVARIANT(*uc))
2134 ? 1
2135 : 2;
2136 if (! folder) {
2137 minbytes++;
2138 }
2139 else {
2140 if (foldlen) {
2141 foldlen--;
2142 }
2143 else {
3a8bbffb 2144 foldlen = is_MULTI_CHAR_FOLD_latin1(uc);
645de4ce
KW
2145 minbytes++;
2146 }
2147 }
2148 }
a3621e74 2149 if ( uvc < 256 ) {
fab2782b
YO
2150 if ( folder ) {
2151 U8 folded= folder[ (U8) uvc ];
2152 if ( !trie->charmap[ folded ] ) {
2153 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2154 TRIE_STORE_REVCHAR( folded );
2155 }
2156 }
a3621e74
YO
2157 if ( !trie->charmap[ uvc ] ) {
2158 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
fab2782b 2159 TRIE_STORE_REVCHAR( uvc );
a3621e74 2160 }
02daf0ab 2161 if ( set_bit ) {
62012aee
KW
2162 /* store the codepoint in the bitmap, and its folded
2163 * equivalent. */
fab2782b 2164 TRIE_BITMAP_SET(trie, uvc);
0921ee73
T
2165
2166 /* store the folded codepoint */
fab2782b 2167 if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
0921ee73
T
2168
2169 if ( !UTF ) {
2170 /* store first byte of utf8 representation of
acdf4139 2171 variant codepoints */
6f2d5cbc 2172 if (! UVCHR_IS_INVARIANT(uvc)) {
acdf4139 2173 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
0921ee73
T
2174 }
2175 }
02daf0ab
YO
2176 set_bit = 0; /* We've done our bit :-) */
2177 }
a3621e74
YO
2178 } else {
2179 SV** svpp;
55eed653
NC
2180 if ( !widecharmap )
2181 widecharmap = newHV();
a3621e74 2182
55eed653 2183 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
a3621e74
YO
2184
2185 if ( !svpp )
e4584336 2186 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
a3621e74
YO
2187
2188 if ( !SvTRUE( *svpp ) ) {
2189 sv_setiv( *svpp, ++trie->uniquecharcount );
fab2782b 2190 TRIE_STORE_REVCHAR(uvc);
a3621e74
YO
2191 }
2192 }
2193 }
3dab1dad 2194 if( cur == first ) {
afa96d92
KW
2195 trie->minlen = minbytes;
2196 trie->maxlen = maxbytes;
2197 } else if (minbytes < trie->minlen) {
2198 trie->minlen = minbytes;
2199 } else if (maxbytes > trie->maxlen) {
2200 trie->maxlen = maxbytes;
fab2782b 2201 }
a3621e74
YO
2202 } /* end first pass */
2203 DEBUG_TRIE_COMPILE_r(
538e84ed
KW
2204 PerlIO_printf( Perl_debug_log,
2205 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
3dab1dad 2206 (int)depth * 2 + 2,"",
55eed653 2207 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
be8e71aa
YO
2208 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2209 (int)trie->minlen, (int)trie->maxlen )
a3621e74 2210 );
a3621e74
YO
2211
2212 /*
2213 We now know what we are dealing with in terms of unique chars and
2214 string sizes so we can calculate how much memory a naive
0111c4fd
RGS
2215 representation using a flat table will take. If it's over a reasonable
2216 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
a3621e74
YO
2217 conservative but potentially much slower representation using an array
2218 of lists.
2219
2220 At the end we convert both representations into the same compressed
2221 form that will be used in regexec.c for matching with. The latter
2222 is a form that cannot be used to construct with but has memory
2223 properties similar to the list form and access properties similar
2224 to the table form making it both suitable for fast searches and
2225 small enough that its feasable to store for the duration of a program.
2226
2227 See the comment in the code where the compressed table is produced
2228 inplace from the flat tabe representation for an explanation of how
2229 the compression works.
2230
2231 */
2232
2233
2e64971a
DM
2234 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2235 prev_states[1] = 0;
2236
538e84ed
KW
2237 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2238 > SvIV(re_trie_maxbuff) )
2239 {
a3621e74
YO
2240 /*
2241 Second Pass -- Array Of Lists Representation
2242
2243 Each state will be represented by a list of charid:state records
2244 (reg_trie_trans_le) the first such element holds the CUR and LEN
2245 points of the allocated array. (See defines above).
2246
2247 We build the initial structure using the lists, and then convert
2248 it into the compressed table form which allows faster lookups
2249 (but cant be modified once converted).
a3621e74
YO
2250 */
2251
a3621e74
YO
2252 STRLEN transcount = 1;
2253
538e84ed 2254 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1e2e3d02
YO
2255 "%*sCompiling trie using list compiler\n",
2256 (int)depth * 2 + 2, ""));
686b73d4 2257
c944940b
JH
2258 trie->states = (reg_trie_state *)
2259 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2260 sizeof(reg_trie_state) );
a3621e74
YO
2261 TRIE_LIST_NEW(1);
2262 next_alloc = 2;
2263
2264 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2265
df826430 2266 regnode *noper = NEXTOPER( cur );
c445ea15 2267 U8 *uc = (U8*)STRING( noper );
df826430 2268 const U8 *e = uc + STR_LEN( noper );
c445ea15
AL
2269 U32 state = 1; /* required init */
2270 U16 charid = 0; /* sanity init */
07be1b83 2271 U32 wordlen = 0; /* required init */
c445ea15 2272
df826430
YO
2273 if (OP(noper) == NOTHING) {
2274 regnode *noper_next= regnext(noper);
2275 if (noper_next != tail && OP(noper_next) == flags) {
2276 noper = noper_next;
2277 uc= (U8*)STRING(noper);
2278 e= uc + STR_LEN(noper);
2279 }
2280 }
2281
3dab1dad 2282 if (OP(noper) != NOTHING) {
786e8c11 2283 for ( ; uc < e ; uc += len ) {
c445ea15 2284
786e8c11 2285 TRIE_READ_CHAR;
c445ea15 2286
786e8c11
YO
2287 if ( uvc < 256 ) {
2288 charid = trie->charmap[ uvc ];
c445ea15 2289 } else {
538e84ed
KW
2290 SV** const svpp = hv_fetch( widecharmap,
2291 (char*)&uvc,
2292 sizeof( UV ),
2293 0);
786e8c11
YO
2294 if ( !svpp ) {
2295 charid = 0;
2296 } else {
2297 charid=(U16)SvIV( *svpp );
2298 }
c445ea15 2299 }
538e84ed
KW
2300 /* charid is now 0 if we dont know the char read, or
2301 * nonzero if we do */
786e8c11 2302 if ( charid ) {
a3621e74 2303
786e8c11
YO
2304 U16 check;
2305 U32 newstate = 0;
a3621e74 2306
786e8c11
YO
2307 charid--;
2308 if ( !trie->states[ state ].trans.list ) {
2309 TRIE_LIST_NEW( state );
c445ea15 2310 }
538e84ed
KW
2311 for ( check = 1;
2312 check <= TRIE_LIST_USED( state );
2313 check++ )
2314 {
2315 if ( TRIE_LIST_ITEM( state, check ).forid
2316 == charid )
2317 {
786e8c11
YO
2318 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2319 break;
2320 }
2321 }
2322 if ( ! newstate ) {
2323 newstate = next_alloc++;
2e64971a 2324 prev_states[newstate] = state;
786e8c11
YO
2325 TRIE_LIST_PUSH( state, charid, newstate );
2326 transcount++;
2327 }
2328 state = newstate;
2329 } else {
2330 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
c445ea15 2331 }
a28509cc 2332 }
c445ea15 2333 }
3dab1dad 2334 TRIE_HANDLE_WORD(state);
a3621e74
YO
2335
2336 } /* end second pass */
2337
1e2e3d02 2338 /* next alloc is the NEXT state to be allocated */
538e84ed 2339 trie->statecount = next_alloc;
c944940b
JH
2340 trie->states = (reg_trie_state *)
2341 PerlMemShared_realloc( trie->states,
2342 next_alloc
2343 * sizeof(reg_trie_state) );
a3621e74 2344
3dab1dad 2345 /* and now dump it out before we compress it */
2b8b4781
NC
2346 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2347 revcharmap, next_alloc,
2348 depth+1)
1e2e3d02 2349 );
a3621e74 2350
c944940b
JH
2351 trie->trans = (reg_trie_trans *)
2352 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
a3621e74
YO
2353 {
2354 U32 state;
a3621e74
YO
2355 U32 tp = 0;
2356 U32 zp = 0;
2357
2358
2359 for( state=1 ; state < next_alloc ; state ++ ) {
2360 U32 base=0;
2361
2362 /*
2363 DEBUG_TRIE_COMPILE_MORE_r(
2364 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2365 );
2366 */
2367
2368 if (trie->states[state].trans.list) {
2369 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2370 U16 maxid=minid;
a28509cc 2371 U16 idx;
a3621e74
YO
2372
2373 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15
AL
2374 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2375 if ( forid < minid ) {
2376 minid=forid;
2377 } else if ( forid > maxid ) {
2378 maxid=forid;
2379 }
a3621e74
YO
2380 }
2381 if ( transcount < tp + maxid - minid + 1) {
2382 transcount *= 2;
c944940b
JH
2383 trie->trans = (reg_trie_trans *)
2384 PerlMemShared_realloc( trie->trans,
446bd890
NC
2385 transcount
2386 * sizeof(reg_trie_trans) );
538e84ed
KW
2387 Zero( trie->trans + (transcount / 2),
2388 transcount / 2,
2389 reg_trie_trans );
a3621e74
YO
2390 }
2391 base = trie->uniquecharcount + tp - minid;
2392 if ( maxid == minid ) {
2393 U32 set = 0;
2394 for ( ; zp < tp ; zp++ ) {
2395 if ( ! trie->trans[ zp ].next ) {
2396 base = trie->uniquecharcount + zp - minid;
538e84ed
KW
2397 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2398 1).newstate;
a3621e74
YO
2399 trie->trans[ zp ].check = state;
2400 set = 1;
2401 break;
2402 }
2403 }
2404 if ( !set ) {
538e84ed
KW
2405 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2406 1).newstate;
a3621e74
YO
2407 trie->trans[ tp ].check = state;
2408 tp++;
2409 zp = tp;
2410 }
2411 } else {
2412 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
538e84ed
KW
2413 const U32 tid = base
2414 - trie->uniquecharcount
2415 + TRIE_LIST_ITEM( state, idx ).forid;
2416 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2417 idx ).newstate;
a3621e74
YO
2418 trie->trans[ tid ].check = state;
2419 }
2420 tp += ( maxid - minid + 1 );
2421 }
2422 Safefree(trie->states[ state ].trans.list);
2423 }
2424 /*
2425 DEBUG_TRIE_COMPILE_MORE_r(
2426 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2427 );
2428 */
2429 trie->states[ state ].trans.base=base;
2430 }
cc601c31 2431 trie->lasttrans = tp + 1;
a3621e74
YO
2432 }
2433 } else {
2434 /*
2435 Second Pass -- Flat Table Representation.
2436
b423522f
KW
2437 we dont use the 0 slot of either trans[] or states[] so we add 1 to
2438 each. We know that we will need Charcount+1 trans at most to store
2439 the data (one row per char at worst case) So we preallocate both
2440 structures assuming worst case.
a3621e74
YO
2441
2442 We then construct the trie using only the .next slots of the entry
2443 structs.
2444
b423522f
KW
2445 We use the .check field of the first entry of the node temporarily
2446 to make compression both faster and easier by keeping track of how
2447 many non zero fields are in the node.
a3621e74
YO
2448
2449 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2450 transition.
2451
b423522f
KW
2452 There are two terms at use here: state as a TRIE_NODEIDX() which is
2453 a number representing the first entry of the node, and state as a
2454 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2455 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2456 if there are 2 entrys per node. eg:
a3621e74
YO
2457
2458 A B A B
2459 1. 2 4 1. 3 7
2460 2. 0 3 3. 0 5
2461 3. 0 0 5. 0 0
2462 4. 0 0 7. 0 0
2463
b423522f
KW
2464 The table is internally in the right hand, idx form. However as we
2465 also have to deal with the states array which is indexed by nodenum
2466 we have to use TRIE_NODENUM() to convert.
a3621e74
YO
2467
2468 */
538e84ed 2469 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1e2e3d02
YO
2470 "%*sCompiling trie using table compiler\n",
2471 (int)depth * 2 + 2, ""));
3dab1dad 2472
c944940b
JH
2473 trie->trans = (reg_trie_trans *)
2474 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2475 * trie->uniquecharcount + 1,
2476 sizeof(reg_trie_trans) );
2477 trie->states = (reg_trie_state *)
2478 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2479 sizeof(reg_trie_state) );
a3621e74
YO
2480 next_alloc = trie->uniquecharcount + 1;
2481
3dab1dad 2482
a3621e74
YO
2483 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2484
df826430 2485 regnode *noper = NEXTOPER( cur );
a28509cc 2486 const U8 *uc = (U8*)STRING( noper );
df826430 2487 const U8 *e = uc + STR_LEN( noper );
a3621e74
YO
2488
2489 U32 state = 1; /* required init */
2490
2491 U16 charid = 0; /* sanity init */
2492 U32 accept_state = 0; /* sanity init */
a3621e74 2493
07be1b83 2494 U32 wordlen = 0; /* required init */
a3621e74 2495
df826430
YO
2496 if (OP(noper) == NOTHING) {
2497 regnode *noper_next= regnext(noper);
2498 if (noper_next != tail && OP(noper_next) == flags) {
2499 noper = noper_next;
2500 uc= (U8*)STRING(noper);
2501 e= uc + STR_LEN(noper);
2502 }
2503 }
fab2782b 2504
3dab1dad 2505 if ( OP(noper) != NOTHING ) {
786e8c11 2506 for ( ; uc < e ; uc += len ) {
a3621e74 2507
786e8c11 2508 TRIE_READ_CHAR;
a3621e74 2509
786e8c11
YO
2510 if ( uvc < 256 ) {
2511 charid = trie->charmap[ uvc ];
2512 } else {
538e84ed
KW
2513 SV* const * const svpp = hv_fetch( widecharmap,
2514 (char*)&uvc,
2515 sizeof( UV ),
2516 0);
786e8c11 2517 charid = svpp ? (U16)SvIV(*svpp) : 0;
a3621e74 2518 }
786e8c11
YO
2519 if ( charid ) {
2520 charid--;
2521 if ( !trie->trans[ state + charid ].next ) {
2522 trie->trans[ state + charid ].next = next_alloc;
2523 trie->trans[ state ].check++;
2e64971a
DM
2524 prev_states[TRIE_NODENUM(next_alloc)]
2525 = TRIE_NODENUM(state);
786e8c11
YO
2526 next_alloc += trie->uniquecharcount;
2527 }
2528 state = trie->trans[ state + charid ].next;
2529 } else {
2530 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2531 }
538e84ed
KW
2532 /* charid is now 0 if we dont know the char read, or
2533 * nonzero if we do */
a3621e74 2534 }
a3621e74 2535 }
3dab1dad
YO
2536 accept_state = TRIE_NODENUM( state );
2537 TRIE_HANDLE_WORD(accept_state);
a3621e74
YO
2538
2539 } /* end second pass */
2540
3dab1dad 2541 /* and now dump it out before we compress it */
2b8b4781
NC
2542 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
2543 revcharmap,
2544 next_alloc, depth+1));
a3621e74 2545
a3621e74
YO
2546 {
2547 /*
2548 * Inplace compress the table.*
2549
2550 For sparse data sets the table constructed by the trie algorithm will
2551 be mostly 0/FAIL transitions or to put it another way mostly empty.
2552 (Note that leaf nodes will not contain any transitions.)
2553
2554 This algorithm compresses the tables by eliminating most such
2555 transitions, at the cost of a modest bit of extra work during lookup:
2556
2557 - Each states[] entry contains a .base field which indicates the
2558 index in the state[] array wheres its transition data is stored.
2559
3b753521 2560 - If .base is 0 there are no valid transitions from that node.
a3621e74
YO
2561
2562 - If .base is nonzero then charid is added to it to find an entry in
2563 the trans array.
2564
2565 -If trans[states[state].base+charid].check!=state then the
2566 transition is taken to be a 0/Fail transition. Thus if there are fail
2567 transitions at the front of the node then the .base offset will point
2568 somewhere inside the previous nodes data (or maybe even into a node
2569 even earlier), but the .check field determines if the transition is
2570 valid.
2571
786e8c11 2572 XXX - wrong maybe?
a3621e74 2573 The following process inplace converts the table to the compressed
3b753521 2574 table: We first do not compress the root node 1,and mark all its
a3621e74 2575 .check pointers as 1 and set its .base pointer as 1 as well. This
3b753521
FN
2576 allows us to do a DFA construction from the compressed table later,
2577 and ensures that any .base pointers we calculate later are greater
2578 than 0.
a3621e74
YO
2579
2580 - We set 'pos' to indicate the first entry of the second node.
2581
2582 - We then iterate over the columns of the node, finding the first and
2583 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2584 and set the .check pointers accordingly, and advance pos
2585 appropriately and repreat for the next node. Note that when we copy
2586 the next pointers we have to convert them from the original
2587 NODEIDX form to NODENUM form as the former is not valid post
2588 compression.
2589
2590 - If a node has no transitions used we mark its base as 0 and do not
2591 advance the pos pointer.
2592
2593 - If a node only has one transition we use a second pointer into the
2594 structure to fill in allocated fail transitions from other states.
2595 This pointer is independent of the main pointer and scans forward
2596 looking for null transitions that are allocated to a state. When it
2597 finds one it writes the single transition into the "hole". If the
786e8c11 2598 pointer doesnt find one the single transition is appended as normal.
a3621e74
YO
2599
2600 - Once compressed we can Renew/realloc the structures to release the
2601 excess space.
2602
2603 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2604 specifically Fig 3.47 and the associated pseudocode.
2605
2606 demq
2607 */
a3b680e6 2608 const U32 laststate = TRIE_NODENUM( next_alloc );
a28509cc 2609 U32 state, charid;
a3621e74 2610 U32 pos = 0, zp=0;
1e2e3d02 2611 trie->statecount = laststate;
a3621e74
YO
2612
2613 for ( state = 1 ; state < laststate ; state++ ) {
2614 U8 flag = 0;
a28509cc
AL
2615 const U32 stateidx = TRIE_NODEIDX( state );
2616 const U32 o_used = trie->trans[ stateidx ].check;
2617 U32 used = trie->trans[ stateidx ].check;
a3621e74
YO
2618 trie->trans[ stateidx ].check = 0;
2619
538e84ed
KW
2620 for ( charid = 0;
2621 used && charid < trie->uniquecharcount;
2622 charid++ )
2623 {
a3621e74
YO
2624 if ( flag || trie->trans[ stateidx + charid ].next ) {
2625 if ( trie->trans[ stateidx + charid ].next ) {
2626 if (o_used == 1) {
2627 for ( ; zp < pos ; zp++ ) {
2628 if ( ! trie->trans[ zp ].next ) {
2629 break;
2630 }
2631 }
538e84ed
KW
2632 trie->states[ state ].trans.base
2633 = zp
2634 + trie->uniquecharcount
2635 - charid ;
2636 trie->trans[ zp ].next
2637 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
2638 + charid ].next );
a3621e74
YO
2639 trie->trans[ zp ].check = state;
2640 if ( ++zp > pos ) pos = zp;
2641 break;
2642 }
2643 used--;
2644 }
2645 if ( !flag ) {
2646 flag = 1;
538e84ed
KW
2647 trie->states[ state ].trans.base
2648 = pos + trie->uniquecharcount - charid ;
a3621e74 2649 }
538e84ed
KW
2650 trie->trans[ pos ].next
2651 = SAFE_TRIE_NODENUM(
2652 trie->trans[ stateidx + charid ].next );
a3621e74
YO
2653 trie->trans[ pos ].check = state;
2654 pos++;
2655 }
2656 }
2657 }
cc601c31 2658 trie->lasttrans = pos + 1;
c944940b
JH
2659 trie->states = (reg_trie_state *)
2660 PerlMemShared_realloc( trie->states, laststate
2661 * sizeof(reg_trie_state) );
a3621e74 2662 DEBUG_TRIE_COMPILE_MORE_r(
538e84ed
KW
2663 PerlIO_printf( Perl_debug_log,
2664 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2665 (int)depth * 2 + 2,"",
2666 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
2667 + 1 ),
2668 (IV)next_alloc,
2669 (IV)pos,
2670 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
a3621e74
YO
2671 );
2672
2673 } /* end table compress */
2674 }
1e2e3d02 2675 DEBUG_TRIE_COMPILE_MORE_r(
538e84ed
KW
2676 PerlIO_printf(Perl_debug_log,
2677 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1e2e3d02
YO
2678 (int)depth * 2 + 2, "",
2679 (UV)trie->statecount,
2680 (UV)trie->lasttrans)
2681 );
cc601c31 2682 /* resize the trans array to remove unused space */
c944940b
JH
2683 trie->trans = (reg_trie_trans *)
2684 PerlMemShared_realloc( trie->trans, trie->lasttrans
2685 * sizeof(reg_trie_trans) );
a3621e74 2686
538e84ed 2687 { /* Modify the program and insert the new TRIE node */
3dab1dad
YO
2688 U8 nodetype =(U8)(flags & 0xFF);
2689 char *str=NULL;
538e84ed 2690
07be1b83 2691#ifdef DEBUGGING
e62cc96a 2692 regnode *optimize = NULL;
7122b237
YO
2693#ifdef RE_TRACK_PATTERN_OFFSETS
2694
b57a0404
JH
2695 U32 mjd_offset = 0;
2696 U32 mjd_nodelen = 0;
7122b237
YO
2697#endif /* RE_TRACK_PATTERN_OFFSETS */
2698#endif /* DEBUGGING */
a3621e74 2699 /*
3dab1dad
YO
2700 This means we convert either the first branch or the first Exact,
2701 depending on whether the thing following (in 'last') is a branch
2702 or not and whther first is the startbranch (ie is it a sub part of
2703 the alternation or is it the whole thing.)
3b753521 2704 Assuming its a sub part we convert the EXACT otherwise we convert
3dab1dad 2705 the whole branch sequence, including the first.
a3621e74 2706 */
3dab1dad 2707 /* Find the node we are going to overwrite */
7f69552c 2708 if ( first != startbranch || OP( last ) == BRANCH ) {
07be1b83 2709 /* branch sub-chain */
3dab1dad 2710 NEXT_OFF( first ) = (U16)(last - first);
7122b237 2711#ifdef RE_TRACK_PATTERN_OFFSETS
07be1b83
YO
2712 DEBUG_r({
2713 mjd_offset= Node_Offset((convert));
2714 mjd_nodelen= Node_Length((convert));
2715 });
7122b237 2716#endif
7f69552c 2717 /* whole branch chain */
7122b237
YO
2718 }
2719#ifdef RE_TRACK_PATTERN_OFFSETS
2720 else {
7f69552c
YO
2721 DEBUG_r({
2722 const regnode *nop = NEXTOPER( convert );
2723 mjd_offset= Node_Offset((nop));
2724 mjd_nodelen= Node_Length((nop));
2725 });
07be1b83
YO
2726 }
2727 DEBUG_OPTIMISE_r(
538e84ed
KW
2728 PerlIO_printf(Perl_debug_log,
2729 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
07be1b83 2730 (int)depth * 2 + 2, "",
786e8c11 2731 (UV)mjd_offset, (UV)mjd_nodelen)
07be1b83 2732 );
7122b237 2733#endif
538e84ed 2734 /* But first we check to see if there is a common prefix we can
3dab1dad
YO
2735 split out as an EXACT and put in front of the TRIE node. */
2736 trie->startstate= 1;
55eed653 2737 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3dab1dad 2738 U32 state;
1e2e3d02 2739 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
a3621e74 2740 U32 ofs = 0;
8e11feef
RGS
2741 I32 idx = -1;
2742 U32 count = 0;
2743 const U32 base = trie->states[ state ].trans.base;
a3621e74 2744
3dab1dad 2745 if ( trie->states[state].wordnum )
8e11feef 2746 count = 1;
a3621e74 2747
8e11feef 2748 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
cc601c31
YO
2749 if ( ( base + ofs >= trie->uniquecharcount ) &&
2750 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
a3621e74
YO
2751 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2752 {
3dab1dad 2753 if ( ++count > 1 ) {
2b8b4781 2754 SV **tmp = av_fetch( revcharmap, ofs, 0);
07be1b83 2755 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2756 if ( state == 1 ) break;
3dab1dad
YO
2757 if ( count == 2 ) {
2758 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2759 DEBUG_OPTIMISE_r(
8e11feef
RGS
2760 PerlIO_printf(Perl_debug_log,
2761 "%*sNew Start State=%"UVuf" Class: [",
2762 (int)depth * 2 + 2, "",
786e8c11 2763 (UV)state));
be8e71aa 2764 if (idx >= 0) {
2b8b4781 2765 SV ** const tmp = av_fetch( revcharmap, idx, 0);
be8e71aa 2766 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2767
3dab1dad 2768 TRIE_BITMAP_SET(trie,*ch);
8e11feef
RGS
2769 if ( folder )
2770 TRIE_BITMAP_SET(trie, folder[ *ch ]);
3dab1dad 2771 DEBUG_OPTIMISE_r(
f1f66076 2772 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3dab1dad 2773 );
8e11feef
RGS
2774 }
2775 }
2776 TRIE_BITMAP_SET(trie,*ch);
2777 if ( folder )
2778 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2779 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2780 }
2781 idx = ofs;
2782 }
3dab1dad
YO
2783 }
2784 if ( count == 1 ) {
2b8b4781 2785 SV **tmp = av_fetch( revcharmap, idx, 0);
c490c714
YO
2786 STRLEN len;
2787 char *ch = SvPV( *tmp, len );
de734bd5
A
2788 DEBUG_OPTIMISE_r({
2789 SV *sv=sv_newmortal();
8e11feef
RGS
2790 PerlIO_printf( Perl_debug_log,
2791 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2792 (int)depth * 2 + 2, "",
538e84ed
KW
2793 (UV)state, (UV)idx,
2794 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
de734bd5
A
2795 PL_colors[0], PL_colors[1],
2796 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed 2797 PERL_PV_ESCAPE_FIRSTCHAR
de734bd5
A
2798 )
2799 );
2800 });
3dab1dad
YO
2801 if ( state==1 ) {
2802 OP( convert ) = nodetype;
2803 str=STRING(convert);
2804 STR_LEN(convert)=0;
2805 }
c490c714
YO
2806 STR_LEN(convert) += len;
2807 while (len--)
de734bd5 2808 *str++ = *ch++;
8e11feef 2809 } else {
538e84ed 2810#ifdef DEBUGGING
8e11feef
RGS
2811 if (state>1)
2812 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
f9049ba1 2813#endif
8e11feef
RGS
2814 break;
2815 }
2816 }
2e64971a 2817 trie->prefixlen = (state-1);
3dab1dad 2818 if (str) {
8e11feef 2819 regnode *n = convert+NODE_SZ_STR(convert);
07be1b83 2820 NEXT_OFF(convert) = NODE_SZ_STR(convert);
8e11feef 2821 trie->startstate = state;
07be1b83
YO
2822 trie->minlen -= (state - 1);
2823 trie->maxlen -= (state - 1);
33809eae
JH
2824#ifdef DEBUGGING
2825 /* At least the UNICOS C compiler choked on this
2826 * being argument to DEBUG_r(), so let's just have
2827 * it right here. */
2828 if (
2829#ifdef PERL_EXT_RE_BUILD
2830 1
2831#else
2832 DEBUG_r_TEST
2833#endif
2834 ) {
2835 regnode *fix = convert;
2836 U32 word = trie->wordcount;
2837 mjd_nodelen++;
2838 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2839 while( ++fix < n ) {
2840 Set_Node_Offset_Length(fix, 0, 0);
2841 }
2842 while (word--) {
2843 SV ** const tmp = av_fetch( trie_words, word, 0 );
2844 if (tmp) {
2845 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2846 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2847 else
2848 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2849 }
2850 }
2851 }
2852#endif
8e11feef
RGS
2853 if (trie->maxlen) {
2854 convert = n;
2855 } else {
3dab1dad 2856 NEXT_OFF(convert) = (U16)(tail - convert);
a5ca303d 2857 DEBUG_r(optimize= n);
3dab1dad
YO
2858 }
2859 }
2860 }
538e84ed
KW
2861 if (!jumper)
2862 jumper = last;
3dab1dad 2863 if ( trie->maxlen ) {
8e11feef
RGS
2864 NEXT_OFF( convert ) = (U16)(tail - convert);
2865 ARG_SET( convert, data_slot );
538e84ed
KW
2866 /* Store the offset to the first unabsorbed branch in
2867 jump[0], which is otherwise unused by the jump logic.
786e8c11 2868 We use this when dumping a trie and during optimisation. */
538e84ed 2869 if (trie->jump)
7f69552c 2870 trie->jump[0] = (U16)(nextbranch - convert);
538e84ed 2871
6c48061a
YO
2872 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2873 * and there is a bitmap
2874 * and the first "jump target" node we found leaves enough room
2875 * then convert the TRIE node into a TRIEC node, with the bitmap
2876 * embedded inline in the opcode - this is hypothetically faster.
2877 */
2878 if ( !trie->states[trie->startstate].wordnum
2879 && trie->bitmap
2880 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
786e8c11
YO
2881 {
2882 OP( convert ) = TRIEC;
2883 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
446bd890 2884 PerlMemShared_free(trie->bitmap);
786e8c11 2885 trie->bitmap= NULL;
538e84ed 2886 } else
786e8c11 2887 OP( convert ) = TRIE;
a3621e74 2888
3dab1dad
YO
2889 /* store the type in the flags */
2890 convert->flags = nodetype;
a5ca303d 2891 DEBUG_r({
538e84ed
KW
2892 optimize = convert
2893 + NODE_STEP_REGNODE
a5ca303d
YO
2894 + regarglen[ OP( convert ) ];
2895 });
538e84ed 2896 /* XXX We really should free up the resource in trie now,
a5ca303d 2897 as we won't use them - (which resources?) dmq */
3dab1dad 2898 }
a3621e74 2899 /* needed for dumping*/
e62cc96a 2900 DEBUG_r(if (optimize) {
07be1b83 2901 regnode *opt = convert;
bcdf7404 2902
e62cc96a 2903 while ( ++opt < optimize) {
07be1b83
YO
2904 Set_Node_Offset_Length(opt,0,0);
2905 }
538e84ed
KW
2906 /*
2907 Try to clean up some of the debris left after the
786e8c11 2908 optimisation.
a3621e74 2909 */
786e8c11 2910 while( optimize < jumper ) {
07be1b83 2911 mjd_nodelen += Node_Length((optimize));
a3621e74 2912 OP( optimize ) = OPTIMIZED;
07be1b83 2913 Set_Node_Offset_Length(optimize,0,0);
a3621e74
YO
2914 optimize++;
2915 }
07be1b83 2916 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
a3621e74
YO
2917 });
2918 } /* end node insert */
2e64971a
DM
2919
2920 /* Finish populating the prev field of the wordinfo array. Walk back
2921 * from each accept state until we find another accept state, and if
2922 * so, point the first word's .prev field at the second word. If the
2923 * second already has a .prev field set, stop now. This will be the
2924 * case either if we've already processed that word's accept state,
3b753521
FN
2925 * or that state had multiple words, and the overspill words were
2926 * already linked up earlier.
2e64971a
DM
2927 */
2928 {
2929 U16 word;
2930 U32 state;
2931 U16 prev;
2932
2933 for (word=1; word <= trie->wordcount; word++) {
2934 prev = 0;
2935 if (trie->wordinfo[word].prev)
2936 continue;
2937 state = trie->wordinfo[word].accept;
2938 while (state) {
2939 state = prev_states[state];
2940 if (!state)
2941 break;
2942 prev = trie->states[state].wordnum;
2943 if (prev)
2944 break;
2945 }
2946 trie->wordinfo[word].prev = prev;
2947 }
2948 Safefree(prev_states);
2949 }
2950
2951
2952 /* and now dump out the compressed format */
2953 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2954
55eed653 2955 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2b8b4781
NC
2956#ifdef DEBUGGING
2957 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2958 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2959#else
03e70be4 2960 SvREFCNT_dec_NN(revcharmap);
07be1b83 2961#endif
538e84ed
KW
2962 return trie->jump
2963 ? MADE_JUMP_TRIE
2964 : trie->startstate>1
2965 ? MADE_EXACT_TRIE
786e8c11
YO
2966 : MADE_TRIE;
2967}
2968
2969STATIC void
2970S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2971{
b423522f
KW
2972/* The Trie is constructed and compressed now so we can build a fail array if
2973 * it's needed
786e8c11 2974
b423522f
KW
2975 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
2976 3.32 in the
2977 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
2978 Ullman 1985/88
786e8c11
YO
2979 ISBN 0-201-10088-6
2980
b423522f
KW
2981 We find the fail state for each state in the trie, this state is the longest
2982 proper suffix of the current state's 'word' that is also a proper prefix of
2983 another word in our trie. State 1 represents the word '' and is thus the
2984 default fail state. This allows the DFA not to have to restart after its
2985 tried and failed a word at a given point, it simply continues as though it
2986 had been matching the other word in the first place.
786e8c11
YO
2987 Consider
2988 'abcdgu'=~/abcdefg|cdgu/
b423522f
KW
2989 When we get to 'd' we are still matching the first word, we would encounter
2990 'g' which would fail, which would bring us to the state representing 'd' in
2991 the second word where we would try 'g' and succeed, proceeding to match
2992 'cdgu'.
786e8c11
YO
2993 */
2994 /* add a fail transition */
3251b653
NC
2995 const U32 trie_offset = ARG(source);
2996 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
786e8c11
YO
2997 U32 *q;
2998 const U32 ucharcount = trie->uniquecharcount;
1e2e3d02 2999 const U32 numstates = trie->statecount;
786e8c11
YO
3000 const U32 ubound = trie->lasttrans + ucharcount;
3001 U32 q_read = 0;
3002 U32 q_write = 0;
3003 U32 charid;
3004 U32 base = trie->states[ 1 ].trans.base;
3005 U32 *fail;
3006 reg_ac_data *aho;
cf78de0b 3007 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
786e8c11 3008 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
3009
3010 PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
786e8c11
YO
3011#ifndef DEBUGGING
3012 PERL_UNUSED_ARG(depth);
3013#endif
3014
3015
3016 ARG_SET( stclass, data_slot );
c944940b 3017 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
f8fc2ecf 3018 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3251b653 3019 aho->trie=trie_offset;
446bd890
NC
3020 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3021 Copy( trie->states, aho->states, numstates, reg_trie_state );
786e8c11 3022 Newxz( q, numstates, U32);
c944940b 3023 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
786e8c11
YO
3024 aho->refcount = 1;
3025 fail = aho->fail;
3026 /* initialize fail[0..1] to be 1 so that we always have
3027 a valid final fail state */
3028 fail[ 0 ] = fail[ 1 ] = 1;
3029
3030 for ( charid = 0; charid < ucharcount ; charid++ ) {
3031 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3032 if ( newstate ) {
3033 q[ q_write ] = newstate;
3034 /* set to point at the root */
3035 fail[ q[ q_write++ ] ]=1;
3036 }
3037 }
3038 while ( q_read < q_write) {
3039 const U32 cur = q[ q_read++ % numstates ];
3040 base = trie->states[ cur ].trans.base;
3041
3042 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3043 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3044 if (ch_state) {
3045 U32 fail_state = cur;
3046 U32 fail_base;
3047 do {
3048 fail_state = fail[ fail_state ];
3049 fail_base = aho->states[ fail_state ].trans.base;
3050 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3051
3052 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3053 fail[ ch_state ] = fail_state;
3054 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3055 {
3056 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3057 }
3058 q[ q_write++ % numstates] = ch_state;
3059 }
3060 }
3061 }
3062 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3063 when we fail in state 1, this allows us to use the
3064 charclass scan to find a valid start char. This is based on the principle
3065 that theres a good chance the string being searched contains lots of stuff
3066 that cant be a start char.
3067 */
3068 fail[ 0 ] = fail[ 1 ] = 0;
3069 DEBUG_TRIE_COMPILE_r({
6d99fb9b 3070 PerlIO_printf(Perl_debug_log,
538e84ed 3071 "%*sStclass Failtable (%"UVuf" states): 0",
6d99fb9b 3072 (int)(depth * 2), "", (UV)numstates
1e2e3d02 3073 );
786e8c11
YO
3074 for( q_read=1; q_read<numstates; q_read++ ) {
3075 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3076 }
3077 PerlIO_printf(Perl_debug_log, "\n");
3078 });
3079 Safefree(q);
e384d5c1 3080 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
a3621e74
YO
3081}
3082
786e8c11 3083
07be1b83 3084#define DEBUG_PEEP(str,scan,depth) \
b515a41d 3085 DEBUG_OPTIMISE_r({if (scan){ \
07be1b83
YO
3086 SV * const mysv=sv_newmortal(); \
3087 regnode *Next = regnext(scan); \
3088 regprop(RExC_rx, mysv, scan); \
7f69552c 3089 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
07be1b83
YO
3090 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
3091 Next ? (REG_NODE_NUM(Next)) : 0 ); \
b515a41d 3092 }});
07be1b83 3093
1de06328 3094
bb914485 3095/* The below joins as many adjacent EXACTish nodes as possible into a single
0a982f06
KW
3096 * one. The regop may be changed if the node(s) contain certain sequences that
3097 * require special handling. The joining is only done if:
bb914485
KW
3098 * 1) there is room in the current conglomerated node to entirely contain the
3099 * next one.
3100 * 2) they are the exact same node type
3101 *
87b8b349 3102 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
bb914485
KW
3103 * these get optimized out
3104 *
0a982f06
KW
3105 * If a node is to match under /i (folded), the number of characters it matches
3106 * can be different than its character length if it contains a multi-character
31f05a37
KW
3107 * fold. *min_subtract is set to the total delta number of characters of the
3108 * input nodes.
bb914485 3109 *
fb29cc72 3110 * And *unfolded_multi_char is set to indicate whether or not the node contains
31f05a37
KW
3111 * an unfolded multi-char fold. This happens when whether the fold is valid or
3112 * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3113 * SMALL LETTER SHARP S, as only if the target string being matched against
3114 * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3115 * folding rules depend on the locale in force at runtime. (Multi-char folds
3116 * whose components are all above the Latin1 range are not run-time locale
3117 * dependent, and have already been folded by the time this function is
3118 * called.)
f758bddf 3119 *
bb914485 3120 * This is as good a place as any to discuss the design of handling these
0a982f06
KW
3121 * multi-character fold sequences. It's been wrong in Perl for a very long
3122 * time. There are three code points in Unicode whose multi-character folds
3123 * were long ago discovered to mess things up. The previous designs for
3124 * dealing with these involved assigning a special node for them. This
538e84ed 3125 * approach doesn't always work, as evidenced by this example:
a0c4c608 3126 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
538e84ed 3127 * Both sides fold to "sss", but if the pattern is parsed to create a node that
0a982f06 3128 * would match just the \xDF, it won't be able to handle the case where a
bb914485
KW
3129 * successful match would have to cross the node's boundary. The new approach
3130 * that hopefully generally solves the problem generates an EXACTFU_SS node
538e84ed 3131 * that is "sss" in this case.
bb914485 3132 *
0a982f06 3133 * It turns out that there are problems with all multi-character folds, and not
cb117658
KW
3134 * just these three. Now the code is general, for all such cases. The
3135 * approach taken is:
0a982f06 3136 * 1) This routine examines each EXACTFish node that could contain multi-
538e84ed
KW
3137 * character folded sequences. Since a single character can fold into
3138 * such a sequence, the minimum match length for this node is less than
3139 * the number of characters in the node. This routine returns in
31f05a37
KW
3140 * *min_subtract how many characters to subtract from the the actual
3141 * length of the string to get a real minimum match length; it is 0 if
3142 * there are no multi-char foldeds. This delta is used by the caller to
3143 * adjust the min length of the match, and the delta between min and max,
3144 * so that the optimizer doesn't reject these possibilities based on size
3145 * constraints.
cb117658 3146 * 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
0a982f06
KW
3147 * is used for an EXACTFU node that contains at least one "ss" sequence in
3148 * it. For non-UTF-8 patterns and strings, this is the only case where
3149 * there is a possible fold length change. That means that a regular
3150 * EXACTFU node without UTF-8 involvement doesn't have to concern itself
3151 * with length changes, and so can be processed faster. regexec.c takes
3152 * advantage of this. Generally, an EXACTFish node that is in UTF-8 is
31f05a37
KW
3153 * pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3154 * known until runtime). This saves effort in regex matching. However,
3155 * the pre-folding isn't done for non-UTF8 patterns because the fold of
3156 * the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3157 * forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
3158 * again, EXACTFL) nodes fold to isn't known until runtime. The fold
0a982f06
KW
3159 * possibilities for the non-UTF8 patterns are quite simple, except for
3160 * the sharp s. All the ones that don't involve a UTF-8 target string are
3161 * members of a fold-pair, and arrays are set up for all of them so that
3162 * the other member of the pair can be found quickly. Code elsewhere in
3163 * this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3164 * 'ss', even if the pattern isn't UTF-8. This avoids the issues
3165 * described in the next item.
31f05a37
KW
3166 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3167 * validity of the fold won't be known until runtime, and so must remain
3168 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFA
3169 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3170 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3171 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3172 * The reason this is a problem is that the optimizer part of regexec.c
3173 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3174 * that a character in the pattern corresponds to at most a single
3175 * character in the target string. (And I do mean character, and not byte
3176 * here, unlike other parts of the documentation that have never been
3177 * updated to account for multibyte Unicode.) sharp s in EXACTF and
3178 * EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3179 * it can match "\x{17F}\x{17F}". These, along with other ones in EXACTFL
3180 * nodes, violate the assumption, and they are the only instances where it
3181 * is violated. I'm reluctant to try to change the assumption, as the
3182 * code involved is impenetrable to me (khw), so instead the code here
3183 * punts. This routine examines EXACTFL nodes, and (when the pattern
3184 * isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3185 * boolean indicating whether or not the node contains such a fold. When
3186 * it is true, the caller sets a flag that later causes the optimizer in
3187 * this file to not set values for the floating and fixed string lengths,
3188 * and thus avoids the optimizer code in regexec.c that makes the invalid
1ca267a5 3189 * assumption. Thus, there is no optimization based on string lengths for
31f05a37
KW
3190 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3191 * EXACTF and EXACTFA nodes that contain the sharp s. (The reason the
3192 * assumption is wrong only in these cases is that all other non-UTF-8
3193 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3194 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3195 * EXACTF nodes because we don't know at compile time if it actually
3196 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3197 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3198 * always matches; and EXACTFA where it never does. In an EXACTFA node in
3199 * a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3200 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3201 * string would require the pattern to be forced into UTF-8, the overhead
3202 * of which we want to avoid. Similarly the unfolded multi-char folds in
3203 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3204 * locale.)
098b07d5
KW
3205 *
3206 * Similarly, the code that generates tries doesn't currently handle
3207 * not-already-folded multi-char folds, and it looks like a pain to change
3208 * that. Therefore, trie generation of EXACTFA nodes with the sharp s
3209 * doesn't work. Instead, such an EXACTFA is turned into a new regnode,
3210 * EXACTFA_NO_TRIE, which the trie code knows not to handle. Most people
3211 * using /iaa matching will be doing so almost entirely with ASCII
3212 * strings, so this should rarely be encountered in practice */
1de06328 3213
fb29cc72 3214#define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
07be1b83 3215 if (PL_regkind[OP(scan)] == EXACT) \
fb29cc72 3216 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
07be1b83 3217
be8e71aa 3218STATIC U32
538e84ed 3219S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
fb29cc72 3220 UV *min_subtract, bool *unfolded_multi_char,
538e84ed
KW
3221 U32 flags,regnode *val, U32 depth)
3222{
07be1b83
YO
3223 /* Merge several consecutive EXACTish nodes into one. */
3224 regnode *n = regnext(scan);
3225 U32 stringok = 1;
3226 regnode *next = scan + NODE_SZ_STR(scan);
3227 U32 merged = 0;
3228 U32 stopnow = 0;
3229#ifdef DEBUGGING
3230 regnode *stop = scan;
72f13be8 3231 GET_RE_DEBUG_FLAGS_DECL;
f9049ba1 3232#else
d47053eb
RGS
3233 PERL_UNUSED_ARG(depth);
3234#endif
7918f24d
NC
3235
3236 PERL_ARGS_ASSERT_JOIN_EXACT;
d47053eb 3237#ifndef EXPERIMENTAL_INPLACESCAN
f9049ba1
SP
3238 PERL_UNUSED_ARG(flags);
3239 PERL_UNUSED_ARG(val);
07be1b83 3240#endif
07be1b83 3241 DEBUG_PEEP("join",scan,depth);
bb914485 3242
3f410cf6
KW
3243 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3244 * EXACT ones that are mergeable to the current one. */
3245 while (n
3246 && (PL_regkind[OP(n)] == NOTHING
3247 || (stringok && OP(n) == OP(scan)))
07be1b83 3248 && NEXT_OFF(n)
3f410cf6
KW
3249 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3250 {
538e84ed 3251
07be1b83
YO
3252 if (OP(n) == TAIL || n > next)
3253 stringok = 0;
3254 if (PL_regkind[OP(n)] == NOTHING) {
07be1b83
YO
3255 DEBUG_PEEP("skip:",n,depth);
3256 NEXT_OFF(scan) += NEXT_OFF(n);
3257 next = n + NODE_STEP_REGNODE;
3258#ifdef DEBUGGING
3259 if (stringok)
3260 stop = n;
3261#endif
3262 n = regnext(n);
3263 }
3264 else if (stringok) {
786e8c11 3265 const unsigned int oldl = STR_LEN(scan);
07be1b83 3266 regnode * const nnext = regnext(n);
b2230d39 3267
baa60164
KW
3268 /* XXX I (khw) kind of doubt that this works on platforms (should
3269 * Perl ever run on one) where U8_MAX is above 255 because of lots
3270 * of other assumptions */
79a81a6e 3271 /* Don't join if the sum can't fit into a single node */
b2230d39
KW
3272 if (oldl + STR_LEN(n) > U8_MAX)
3273 break;
538e84ed 3274
07be1b83 3275 DEBUG_PEEP("merg",n,depth);
07be1b83 3276 merged++;
b2230d39 3277
07be1b83
YO
3278 NEXT_OFF(scan) += NEXT_OFF(n);
3279 STR_LEN(scan) += STR_LEN(n);
3280 next = n + NODE_SZ_STR(n);
3281 /* Now we can overwrite *n : */
3282 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3283#ifdef DEBUGGING
3284 stop = next - 1;
3285#endif
3286 n = nnext;
3287 if (stopnow) break;
3288 }
3289
d47053eb
RGS
3290#ifdef EXPERIMENTAL_INPLACESCAN
3291 if (flags && !NEXT_OFF(n)) {
3292 DEBUG_PEEP("atch", val, depth);
3293 if (reg_off_by_arg[OP(n)]) {
3294 ARG_SET(n, val - n);
3295 }
3296 else {
3297 NEXT_OFF(n) = val - n;
3298 }
3299 stopnow = 1;
3300 }
07be1b83
YO
3301#endif
3302 }
2c2b7f86 3303
9d071ca8 3304 *min_subtract = 0;
fb29cc72 3305 *unfolded_multi_char = FALSE;
f646642f 3306
3f410cf6
KW
3307 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
3308 * can now analyze for sequences of problematic code points. (Prior to
3309 * this final joining, sequences could have been split over boundaries, and
a0c4c608
KW
3310 * hence missed). The sequences only happen in folding, hence for any
3311 * non-EXACT EXACTish node */
86d6fcad 3312 if (OP(scan) != EXACT) {
31f05a37
KW
3313 U8* s0 = (U8*) STRING(scan);
3314 U8* s = s0;
3315 U8* s_end = s0 + STR_LEN(scan);
3316
3317 int total_count_delta = 0; /* Total delta number of characters that
3318 multi-char folds expand to */
f758bddf
KW
3319
3320 /* One pass is made over the node's string looking for all the
baa60164 3321 * possibilities. To avoid some tests in the loop, there are two main
f758bddf
KW
3322 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
3323 * non-UTF-8 */
3324 if (UTF) {
31f05a37
KW
3325 U8* folded = NULL;
3326
3327 if (OP(scan) == EXACTFL) {
3328 U8 *d;
3329
3330 /* An EXACTFL node would already have been changed to another
3331 * node type unless there is at least one character in it that
3332 * is problematic; likely a character whose fold definition
3333 * won't be known until runtime, and so has yet to be folded.
3334 * For all but the UTF-8 locale, folds are 1-1 in length, but
3335 * to handle the UTF-8 case, we need to create a temporary
3336 * folded copy using UTF-8 locale rules in order to analyze it.
3337 * This is because our macros that look to see if a sequence is
3338 * a multi-char fold assume everything is folded (otherwise the
3339 * tests in those macros would be too complicated and slow).
3340 * Note that here, the non-problematic folds will have already
3341 * been done, so we can just copy such characters. We actually
3342 * don't completely fold the EXACTFL string. We skip the
3343 * unfolded multi-char folds, as that would just create work
3344 * below to figure out the size they already are */
3345
3346 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
3347 d = folded;
3348 while (s < s_end) {
3349 STRLEN s_len = UTF8SKIP(s);
3350 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
3351 Copy(s, d, s_len, U8);
3352 d += s_len;
3353 }
3354 else if (is_FOLDS_TO_MULTI_utf8(s)) {
fb29cc72 3355 *unfolded_multi_char = TRUE;
31f05a37
KW
3356 Copy(s, d, s_len, U8);
3357 d += s_len;
3358 }
3359 else if (isASCII(*s)) {
3360 *(d++) = toFOLD(*s);
3361 }
3362 else {
3363 STRLEN len;
3364 _to_utf8_fold_flags(s, d, &len, FOLD_FLAGS_FULL);
3365 d += len;
3366 }
3367 s += s_len;
3368 }
3369
3370 /* Point the remainder of the routine to look at our temporary
3371 * folded copy */
3372 s = folded;
3373 s_end = d;
3374 } /* End of creating folded copy of EXACTFL string */
86d6fcad 3375
0a982f06
KW
3376 /* Examine the string for a multi-character fold sequence. UTF-8
3377 * patterns have all characters pre-folded by the time this code is
3378 * executed */
3379 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
3380 length sequence we are looking for is 2 */
86d6fcad 3381 {
538e84ed 3382 int count = 0; /* How many characters in a multi-char fold */
3a8bbffb 3383 int len = is_MULTI_CHAR_FOLD_utf8(s);
0a982f06
KW
3384 if (! len) { /* Not a multi-char fold: get next char */
3385 s += UTF8SKIP(s);
3386 continue;
3387 }
bb914485 3388
31f05a37
KW
3389 /* Nodes with 'ss' require special handling, except for
3390 * EXACTFA-ish for which there is no multi-char fold to this */
0a982f06 3391 if (len == 2 && *s == 's' && *(s+1) == 's'
098b07d5
KW
3392 && OP(scan) != EXACTFA
3393 && OP(scan) != EXACTFA_NO_TRIE)
0a982f06
KW
3394 {
3395 count = 2;
31f05a37
KW
3396 if (OP(scan) != EXACTFL) {
3397 OP(scan) = EXACTFU_SS;
3398 }
0a982f06
KW
3399 s += 2;
3400 }
0a982f06 3401 else { /* Here is a generic multi-char fold. */
31f05a37
KW
3402 U8* multi_end = s + len;
3403
3404 /* Count how many characters in it. In the case of /aa, no
3405 * folds which contain ASCII code points are allowed, so
3406 * check for those, and skip if found. */
3407 if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
0a982f06
KW
3408 count = utf8_length(s, multi_end);
3409 s = multi_end;
3410 }
3411 else {
3412 while (s < multi_end) {
3413 if (isASCII(*s)) {
3414 s++;
3415 goto next_iteration;
3416 }
3417 else {
3418 s += UTF8SKIP(s);
3419 }
3420 count++;
3421 }
3422 }
3423 }
f758bddf 3424
0a982f06
KW
3425 /* The delta is how long the sequence is minus 1 (1 is how long
3426 * the character that folds to the sequence is) */
31f05a37
KW
3427 total_count_delta += count - 1;
3428 next_iteration: ;
bb914485 3429 }
31f05a37
KW
3430
3431 /* We created a temporary folded copy of the string in EXACTFL
3432 * nodes. Therefore we need to be sure it doesn't go below zero,
3433 * as the real string could be shorter */
3434 if (OP(scan) == EXACTFL) {
3435 int total_chars = utf8_length((U8*) STRING(scan),
3436 (U8*) STRING(scan) + STR_LEN(scan));
3437 if (total_count_delta > total_chars) {
3438 total_count_delta = total_chars;
3439 }
3440 }
3441
3442 *min_subtract += total_count_delta;
3443 Safefree(folded);
bb914485 3444 }
1ca267a5
KW
3445 else if (OP(scan) == EXACTFA) {
3446
3447 /* Non-UTF-8 pattern, EXACTFA node. There can't be a multi-char
3448 * fold to the ASCII range (and there are no existing ones in the
3449 * upper latin1 range). But, as outlined in the comments preceding
098b07d5
KW
3450 * this function, we need to flag any occurrences of the sharp s.
3451 * This character forbids trie formation (because of added
3452 * complexity) */
1ca267a5
KW
3453 while (s < s_end) {
3454 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
098b07d5 3455 OP(scan) = EXACTFA_NO_TRIE;
fb29cc72 3456 *unfolded_multi_char = TRUE;
1ca267a5
KW
3457 break;
3458 }
3459 s++;
3460 continue;
3461 }
3462 }
31f05a37
KW
3463 else {
3464
3465 /* Non-UTF-8 pattern, not EXACTFA node. Look for the multi-char
3466 * folds that are all Latin1. As explained in the comments
3467 * preceding this function, we look also for the sharp s in EXACTF
3468 * and EXACTFL nodes; it can be in the final position. Otherwise
3469 * we can stop looking 1 byte earlier because have to find at least
3470 * two characters for a multi-fold */
3471 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
3472 ? s_end
3473 : s_end -1;
f758bddf 3474
0a982f06 3475 while (s < upper) {
3a8bbffb 3476 int len = is_MULTI_CHAR_FOLD_latin1(s);
0a982f06 3477 if (! len) { /* Not a multi-char fold. */
31f05a37
KW
3478 if (*s == LATIN_SMALL_LETTER_SHARP_S
3479 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
0a982f06 3480 {
fb29cc72 3481 *unfolded_multi_char = TRUE;
0a982f06
KW
3482 }
3483 s++;
3484 continue;
3485 }
3486
3487 if (len == 2
c02c3054
KW
3488 && isARG2_lower_or_UPPER_ARG1('s', *s)
3489 && isARG2_lower_or_UPPER_ARG1('s', *(s+1)))
0a982f06
KW
3490 {
3491
3492 /* EXACTF nodes need to know that the minimum length
3493 * changed so that a sharp s in the string can match this
3494 * ss in the pattern, but they remain EXACTF nodes, as they
3495 * won't match this unless the target string is is UTF-8,
31f05a37
KW
3496 * which we don't know until runtime. EXACTFL nodes can't
3497 * transform into EXACTFU nodes */