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