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