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