This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regcomp.c: Replace invalid assertion
[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;
67cdf558 198 U32 strict;
dc6d7f5c 199#ifdef ADD_TO_REGEXEC
830247a4
IZ
200 char *starttry; /* -Dr: where regtry was called. */
201#define RExC_starttry (pRExC_state->starttry)
202#endif
d24ca0c5 203 SV *runtime_code_qr; /* qr with the runtime code blocks */
3dab1dad 204#ifdef DEBUGGING
be8e71aa 205 const char *lastparse;
3dab1dad 206 I32 lastnum;
1f1031fe 207 AV *paren_name_list; /* idx -> name */
d9a72fcc 208 U32 study_chunk_recursed_count;
c9f0d54c
YO
209 SV *mysv1;
210 SV *mysv2;
3dab1dad
YO
211#define RExC_lastparse (pRExC_state->lastparse)
212#define RExC_lastnum (pRExC_state->lastnum)
1f1031fe 213#define RExC_paren_name_list (pRExC_state->paren_name_list)
d9a72fcc 214#define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
c9f0d54c
YO
215#define RExC_mysv (pRExC_state->mysv1)
216#define RExC_mysv1 (pRExC_state->mysv1)
217#define RExC_mysv2 (pRExC_state->mysv2)
218
3dab1dad 219#endif
512c0f5a 220 bool seen_unfolded_sharp_s;
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
1423 * as well */
f240c685
KW
1424 if (OP(node) == ANYOFD
1425 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1426 {
b423522f
KW
1427 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1428 }
1429
1430 /* Similarly for these */
93e92956 1431 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
e0a1ff7a 1432 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
b423522f
KW
1433 }
1434
1435 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1436 _invlist_invert(invlist);
1437 }
037715a6 1438 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
31f05a37
KW
1439
1440 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1441 * locale. We can skip this if there are no 0-255 at all. */
1442 _invlist_union(invlist, PL_Latin1, &invlist);
1443 }
1444
1ee208c4
KW
1445 /* Similarly add the UTF-8 locale possible matches. These have to be
1446 * deferred until after the non-UTF-8 locale ones are taken care of just
1447 * above, or it leads to wrong results under ANYOF_INVERT */
1448 if (only_utf8_locale_invlist) {
31f05a37 1449 _invlist_union_maybe_complement_2nd(invlist,
1ee208c4 1450 only_utf8_locale_invlist,
31f05a37
KW
1451 ANYOF_FLAGS(node) & ANYOF_INVERT,
1452 &invlist);
1453 }
b423522f
KW
1454
1455 return invlist;
1456}
1457
1051e1c4 1458/* These two functions currently do the exact same thing */
557bd3fb 1459#define ssc_init_zero ssc_init
653099ff 1460
cdd87c1d
KW
1461#define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1462#define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1463
557bd3fb 1464/* 'AND' a given class with another one. Can create false positives. 'ssc'
93e92956
KW
1465 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1466 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
cdd87c1d 1467
653099ff 1468STATIC void
b423522f 1469S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
7dcac5f6 1470 const regnode_charclass *and_with)
653099ff 1471{
cdd87c1d
KW
1472 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1473 * another SSC or a regular ANYOF class. Can create false positives. */
40d049e4 1474
a0dd4231
KW
1475 SV* anded_cp_list;
1476 U8 anded_flags;
1e6ade67 1477
cdd87c1d 1478 PERL_ARGS_ASSERT_SSC_AND;
653099ff 1479
71068078 1480 assert(is_ANYOF_SYNTHETIC(ssc));
a0dd4231
KW
1481
1482 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1483 * the code point inversion list and just the relevant flags */
71068078 1484 if (is_ANYOF_SYNTHETIC(and_with)) {
7dcac5f6 1485 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
a0dd4231 1486 anded_flags = ANYOF_FLAGS(and_with);
e9b08962
KW
1487
1488 /* XXX This is a kludge around what appears to be deficiencies in the
1489 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1490 * there are paths through the optimizer where it doesn't get weeded
1491 * out when it should. And if we don't make some extra provision for
1492 * it like the code just below, it doesn't get added when it should.
1493 * This solution is to add it only when AND'ing, which is here, and
1494 * only when what is being AND'ed is the pristine, original node
1495 * matching anything. Thus it is like adding it to ssc_anything() but
1496 * only when the result is to be AND'ed. Probably the same solution
1497 * could be adopted for the same problem we have with /l matching,
1498 * which is solved differently in S_ssc_init(), and that would lead to
1499 * fewer false positives than that solution has. But if this solution
1500 * creates bugs, the consequences are only that a warning isn't raised
1501 * that should be; while the consequences for having /l bugs is
1502 * incorrect matches */
7dcac5f6 1503 if (ssc_is_anything((regnode_ssc *)and_with)) {
f240c685 1504 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
e9b08962 1505 }
a0dd4231
KW
1506 }
1507 else {
5c0f85ef 1508 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
f240c685
KW
1509 if (OP(and_with) == ANYOFD) {
1510 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1511 }
1512 else {
1513 anded_flags = ANYOF_FLAGS(and_with)
1514 &( ANYOF_COMMON_FLAGS
108316fb
KW
1515 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1516 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
d1c40ef5
KW
1517 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1518 anded_flags &=
1519 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1520 }
f240c685 1521 }
a0dd4231
KW
1522 }
1523
1524 ANYOF_FLAGS(ssc) &= anded_flags;
cdd87c1d
KW
1525
1526 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1527 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1528 * 'and_with' may be inverted. When not inverted, we have the situation of
1529 * computing:
1530 * (C1 | P1) & (C2 | P2)
1531 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1532 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1533 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1534 * <= ((C1 & C2) | P1 | P2)
1535 * Alternatively, the last few steps could be:
1536 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1537 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1538 * <= (C1 | C2 | (P1 & P2))
1539 * We favor the second approach if either P1 or P2 is non-empty. This is
1540 * because these components are a barrier to doing optimizations, as what
1541 * they match cannot be known until the moment of matching as they are
1542 * dependent on the current locale, 'AND"ing them likely will reduce or
1543 * eliminate them.
1544 * But we can do better if we know that C1,P1 are in their initial state (a
1545 * frequent occurrence), each matching everything:
1546 * (<everything>) & (C2 | P2) = C2 | P2
1547 * Similarly, if C2,P2 are in their initial state (again a frequent
1548 * occurrence), the result is a no-op
1549 * (C1 | P1) & (<everything>) = C1 | P1
1550 *
1551 * Inverted, we have
1552 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1553 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1554 * <= (C1 & ~C2) | (P1 & ~P2)
1555 * */
1aa99e6b 1556
a0dd4231 1557 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
71068078 1558 && ! is_ANYOF_SYNTHETIC(and_with))
a0dd4231 1559 {
cdd87c1d 1560 unsigned int i;
8951c461 1561
cdd87c1d
KW
1562 ssc_intersection(ssc,
1563 anded_cp_list,
1564 FALSE /* Has already been inverted */
1565 );
c6b76537 1566
cdd87c1d
KW
1567 /* If either P1 or P2 is empty, the intersection will be also; can skip
1568 * the loop */
93e92956 1569 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
cdd87c1d
KW
1570 ANYOF_POSIXL_ZERO(ssc);
1571 }
e0e1be5f 1572 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
cdd87c1d
KW
1573
1574 /* Note that the Posix class component P from 'and_with' actually
1575 * looks like:
1576 * P = Pa | Pb | ... | Pn
1577 * where each component is one posix class, such as in [\w\s].
1578 * Thus
1579 * ~P = ~(Pa | Pb | ... | Pn)
1580 * = ~Pa & ~Pb & ... & ~Pn
1581 * <= ~Pa | ~Pb | ... | ~Pn
1582 * The last is something we can easily calculate, but unfortunately
1583 * is likely to have many false positives. We could do better
1584 * in some (but certainly not all) instances if two classes in
1585 * P have known relationships. For example
1586 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1587 * So
1588 * :lower: & :print: = :lower:
1589 * And similarly for classes that must be disjoint. For example,
1590 * since \s and \w can have no elements in common based on rules in
1591 * the POSIX standard,
1592 * \w & ^\S = nothing
1593 * Unfortunately, some vendor locales do not meet the Posix
1594 * standard, in particular almost everything by Microsoft.
1595 * The loop below just changes e.g., \w into \W and vice versa */
1596
1ee208c4 1597 regnode_charclass_posixl temp;
cdd87c1d
KW
1598 int add = 1; /* To calculate the index of the complement */
1599
1600 ANYOF_POSIXL_ZERO(&temp);
1601 for (i = 0; i < ANYOF_MAX; i++) {
1602 assert(i % 2 != 0
7dcac5f6
KW
1603 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1604 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
cdd87c1d 1605
7dcac5f6 1606 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
cdd87c1d
KW
1607 ANYOF_POSIXL_SET(&temp, i + add);
1608 }
1609 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1610 }
1611 ANYOF_POSIXL_AND(&temp, ssc);
c6b76537 1612
cdd87c1d
KW
1613 } /* else ssc already has no posixes */
1614 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1615 in its initial state */
71068078 1616 else if (! is_ANYOF_SYNTHETIC(and_with)
7dcac5f6 1617 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
cdd87c1d
KW
1618 {
1619 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1620 * copy it over 'ssc' */
1621 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
71068078 1622 if (is_ANYOF_SYNTHETIC(and_with)) {
cdd87c1d
KW
1623 StructCopy(and_with, ssc, regnode_ssc);
1624 }
1625 else {
1626 ssc->invlist = anded_cp_list;
1627 ANYOF_POSIXL_ZERO(ssc);
93e92956 1628 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
7dcac5f6 1629 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
cdd87c1d
KW
1630 }
1631 }
1632 }
e0e1be5f 1633 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
93e92956 1634 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
cdd87c1d
KW
1635 {
1636 /* One or the other of P1, P2 is non-empty. */
93e92956 1637 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1ea8b7fe
KW
1638 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1639 }
cdd87c1d
KW
1640 ssc_union(ssc, anded_cp_list, FALSE);
1641 }
1642 else { /* P1 = P2 = empty */
1643 ssc_intersection(ssc, anded_cp_list, FALSE);
1644 }
137165a6 1645 }
653099ff
GS
1646}
1647
653099ff 1648STATIC void
cdd87c1d 1649S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
7dcac5f6 1650 const regnode_charclass *or_with)
653099ff 1651{
cdd87c1d
KW
1652 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1653 * another SSC or a regular ANYOF class. Can create false positives if
1654 * 'or_with' is to be inverted. */
7918f24d 1655
a0dd4231
KW
1656 SV* ored_cp_list;
1657 U8 ored_flags;
c6b76537 1658
cdd87c1d 1659 PERL_ARGS_ASSERT_SSC_OR;
c6b76537 1660
71068078 1661 assert(is_ANYOF_SYNTHETIC(ssc));
a0dd4231
KW
1662
1663 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1664 * the code point inversion list and just the relevant flags */
71068078 1665 if (is_ANYOF_SYNTHETIC(or_with)) {
7dcac5f6 1666 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
a0dd4231
KW
1667 ored_flags = ANYOF_FLAGS(or_with);
1668 }
1669 else {
5c0f85ef 1670 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
eff8b7dc 1671 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
f240c685
KW
1672 if (OP(or_with) != ANYOFD) {
1673 ored_flags
1674 |= ANYOF_FLAGS(or_with)
108316fb
KW
1675 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1676 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
d1c40ef5
KW
1677 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1678 ored_flags |=
1679 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1680 }
f240c685 1681 }
a0dd4231
KW
1682 }
1683
1684 ANYOF_FLAGS(ssc) |= ored_flags;
cdd87c1d
KW
1685
1686 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1687 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1688 * 'or_with' may be inverted. When not inverted, we have the simple
1689 * situation of computing:
1690 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1691 * If P1|P2 yields a situation with both a class and its complement are
1692 * set, like having both \w and \W, this matches all code points, and we
1693 * can delete these from the P component of the ssc going forward. XXX We
1694 * might be able to delete all the P components, but I (khw) am not certain
1695 * about this, and it is better to be safe.
1696 *
1697 * Inverted, we have
1698 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1699 * <= (C1 | P1) | ~C2
1700 * <= (C1 | ~C2) | P1
1701 * (which results in actually simpler code than the non-inverted case)
1702 * */
9826f543 1703
a0dd4231 1704 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
71068078 1705 && ! is_ANYOF_SYNTHETIC(or_with))
a0dd4231 1706 {
cdd87c1d 1707 /* We ignore P2, leaving P1 going forward */
1ea8b7fe 1708 } /* else Not inverted */
93e92956 1709 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
7dcac5f6 1710 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
e0e1be5f 1711 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
cdd87c1d
KW
1712 unsigned int i;
1713 for (i = 0; i < ANYOF_MAX; i += 2) {
1714 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1715 {
1716 ssc_match_all_cp(ssc);
1717 ANYOF_POSIXL_CLEAR(ssc, i);
1718 ANYOF_POSIXL_CLEAR(ssc, i+1);
cdd87c1d
KW
1719 }
1720 }
1721 }
1aa99e6b 1722 }
cdd87c1d
KW
1723
1724 ssc_union(ssc,
1725 ored_cp_list,
1726 FALSE /* Already has been inverted */
1727 );
653099ff
GS
1728}
1729
b423522f
KW
1730PERL_STATIC_INLINE void
1731S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1732{
1733 PERL_ARGS_ASSERT_SSC_UNION;
1734
71068078 1735 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1736
1737 _invlist_union_maybe_complement_2nd(ssc->invlist,
1738 invlist,
1739 invert2nd,
1740 &ssc->invlist);
1741}
1742
1743PERL_STATIC_INLINE void
1744S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1745 SV* const invlist,
1746 const bool invert2nd)
1747{
1748 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1749
71068078 1750 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1751
1752 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1753 invlist,
1754 invert2nd,
1755 &ssc->invlist);
1756}
1757
1758PERL_STATIC_INLINE void
1759S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1760{
1761 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1762
71068078 1763 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1764
1765 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1766}
1767
1768PERL_STATIC_INLINE void
1769S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1770{
1771 /* AND just the single code point 'cp' into the SSC 'ssc' */
1772
1773 SV* cp_list = _new_invlist(2);
1774
1775 PERL_ARGS_ASSERT_SSC_CP_AND;
1776
71068078 1777 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1778
1779 cp_list = add_cp_to_invlist(cp_list, cp);
1780 ssc_intersection(ssc, cp_list,
1781 FALSE /* Not inverted */
1782 );
1783 SvREFCNT_dec_NN(cp_list);
1784}
1785
1786PERL_STATIC_INLINE void
dc3bf405 1787S_ssc_clear_locale(regnode_ssc *ssc)
b423522f
KW
1788{
1789 /* Set the SSC 'ssc' to not match any locale things */
b423522f
KW
1790 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1791
71068078 1792 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1793
1794 ANYOF_POSIXL_ZERO(ssc);
1795 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1796}
1797
b35552de
KW
1798#define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
1799
1800STATIC bool
1801S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
1802{
1803 /* The synthetic start class is used to hopefully quickly winnow down
1804 * places where a pattern could start a match in the target string. If it
1805 * doesn't really narrow things down that much, there isn't much point to
1806 * having the overhead of using it. This function uses some very crude
1807 * heuristics to decide if to use the ssc or not.
1808 *
1809 * It returns TRUE if 'ssc' rules out more than half what it considers to
1810 * be the "likely" possible matches, but of course it doesn't know what the
1811 * actual things being matched are going to be; these are only guesses
1812 *
1813 * For /l matches, it assumes that the only likely matches are going to be
1814 * in the 0-255 range, uniformly distributed, so half of that is 127
1815 * For /a and /d matches, it assumes that the likely matches will be just
1816 * the ASCII range, so half of that is 63
1817 * For /u and there isn't anything matching above the Latin1 range, it
1818 * assumes that that is the only range likely to be matched, and uses
1819 * half that as the cut-off: 127. If anything matches above Latin1,
1820 * it assumes that all of Unicode could match (uniformly), except for
1821 * non-Unicode code points and things in the General Category "Other"
1822 * (unassigned, private use, surrogates, controls and formats). This
1823 * is a much large number. */
1824
1825 const U32 max_match = (LOC)
1826 ? 127
1827 : (! UNI_SEMANTICS)
1828 ? 63
1829 : (invlist_highest(ssc->invlist) < 256)
1830 ? 127
1831 : ((NON_OTHER_COUNT + 1) / 2) - 1;
1832 U32 count = 0; /* Running total of number of code points matched by
1833 'ssc' */
1834 UV start, end; /* Start and end points of current range in inversion
1835 list */
1836
1837 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
1838
1839 invlist_iterinit(ssc->invlist);
1840 while (invlist_iternext(ssc->invlist, &start, &end)) {
1841
1842 /* /u is the only thing that we expect to match above 255; so if not /u
1843 * and even if there are matches above 255, ignore them. This catches
1844 * things like \d under /d which does match the digits above 255, but
1845 * since the pattern is /d, it is not likely to be expecting them */
1846 if (! UNI_SEMANTICS) {
1847 if (start > 255) {
1848 break;
1849 }
1850 end = MIN(end, 255);
1851 }
1852 count += end - start + 1;
1853 if (count > max_match) {
1854 invlist_iterfinish(ssc->invlist);
1855 return FALSE;
1856 }
1857 }
1858
1859 return TRUE;
1860}
1861
1862
b423522f
KW
1863STATIC void
1864S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1865{
1866 /* The inversion list in the SSC is marked mortal; now we need a more
1867 * permanent copy, which is stored the same way that is done in a regular
dcb20b36
KW
1868 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
1869 * map */
b423522f
KW
1870
1871 SV* invlist = invlist_clone(ssc->invlist);
1872
1873 PERL_ARGS_ASSERT_SSC_FINALIZE;
1874
71068078 1875 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f 1876
a0dd4231 1877 /* The code in this file assumes that all but these flags aren't relevant
93e92956
KW
1878 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
1879 * by the time we reach here */
f240c685
KW
1880 assert(! (ANYOF_FLAGS(ssc)
1881 & ~( ANYOF_COMMON_FLAGS
108316fb
KW
1882 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1883 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
a0dd4231 1884
b423522f
KW
1885 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1886
1ee208c4
KW
1887 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
1888 NULL, NULL, NULL, FALSE);
b423522f 1889
85c8e306
KW
1890 /* Make sure is clone-safe */
1891 ssc->invlist = NULL;
1892
e0e1be5f 1893 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
93e92956 1894 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
e0e1be5f 1895 }
1462525b 1896
b2e90ddf
KW
1897 if (RExC_contains_locale) {
1898 OP(ssc) = ANYOFL;
1899 }
1900
1462525b 1901 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
b423522f
KW
1902}
1903
a3621e74
YO
1904#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1905#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
1906#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
538e84ed
KW
1907#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
1908 ? (TRIE_LIST_CUR( idx ) - 1) \
1909 : 0 )
a3621e74 1910
3dab1dad
YO
1911
1912#ifdef DEBUGGING
07be1b83 1913/*
2b8b4781
NC
1914 dump_trie(trie,widecharmap,revcharmap)
1915 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1916 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
3dab1dad
YO
1917
1918 These routines dump out a trie in a somewhat readable format.
07be1b83
YO
1919 The _interim_ variants are used for debugging the interim
1920 tables that are used to generate the final compressed
1921 representation which is what dump_trie expects.
1922
486ec47a 1923 Part of the reason for their existence is to provide a form
3dab1dad 1924 of documentation as to how the different representations function.
07be1b83
YO
1925
1926*/
3dab1dad
YO
1927
1928/*
3dab1dad
YO
1929 Dumps the final compressed table form of the trie to Perl_debug_log.
1930 Used for debugging make_trie().
1931*/
b9a59e08 1932
3dab1dad 1933STATIC void
2b8b4781
NC
1934S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1935 AV *revcharmap, U32 depth)
3dab1dad
YO
1936{
1937 U32 state;
ab3bbdeb 1938 SV *sv=sv_newmortal();
55eed653 1939 int colwidth= widecharmap ? 6 : 4;
2e64971a 1940 U16 word;
3dab1dad
YO
1941 GET_RE_DEBUG_FLAGS_DECL;
1942
7918f24d 1943 PERL_ARGS_ASSERT_DUMP_TRIE;
ab3bbdeb 1944
3dab1dad
YO
1945 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1946 (int)depth * 2 + 2,"",
1947 "Match","Base","Ofs" );
1948
1949 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2b8b4781 1950 SV ** const tmp = av_fetch( revcharmap, state, 0);
3dab1dad 1951 if ( tmp ) {
538e84ed 1952 PerlIO_printf( Perl_debug_log, "%*s",
ab3bbdeb 1953 colwidth,
538e84ed 1954 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1955 PL_colors[0], PL_colors[1],
1956 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed
KW
1957 PERL_PV_ESCAPE_FIRSTCHAR
1958 )
ab3bbdeb 1959 );
3dab1dad
YO
1960 }
1961 }
1962 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1963 (int)depth * 2 + 2,"");
1964
1965 for( state = 0 ; state < trie->uniquecharcount ; state++ )
ab3bbdeb 1966 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
3dab1dad
YO
1967 PerlIO_printf( Perl_debug_log, "\n");
1968
1e2e3d02 1969 for( state = 1 ; state < trie->statecount ; state++ ) {
be8e71aa 1970 const U32 base = trie->states[ state ].trans.base;
3dab1dad 1971
538e84ed
KW
1972 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1973 (int)depth * 2 + 2,"", (UV)state);
3dab1dad
YO
1974
1975 if ( trie->states[ state ].wordnum ) {
538e84ed
KW
1976 PerlIO_printf( Perl_debug_log, " W%4X",
1977 trie->states[ state ].wordnum );
3dab1dad
YO
1978 } else {
1979 PerlIO_printf( Perl_debug_log, "%6s", "" );
1980 }
1981
1982 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1983
1984 if ( base ) {
1985 U32 ofs = 0;
1986
1987 while( ( base + ofs < trie->uniquecharcount ) ||
1988 ( base + ofs - trie->uniquecharcount < trie->lasttrans
538e84ed
KW
1989 && trie->trans[ base + ofs - trie->uniquecharcount ].check
1990 != state))
3dab1dad
YO
1991 ofs++;
1992
1993 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1994
1995 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
538e84ed
KW
1996 if ( ( base + ofs >= trie->uniquecharcount )
1997 && ( base + ofs - trie->uniquecharcount
1998 < trie->lasttrans )
1999 && trie->trans[ base + ofs
2000 - trie->uniquecharcount ].check == state )
3dab1dad 2001 {
ab3bbdeb
YO
2002 PerlIO_printf( Perl_debug_log, "%*"UVXf,
2003 colwidth,
538e84ed
KW
2004 (UV)trie->trans[ base + ofs
2005 - trie->uniquecharcount ].next );
3dab1dad 2006 } else {
ab3bbdeb 2007 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
3dab1dad
YO
2008 }
2009 }
2010
2011 PerlIO_printf( Perl_debug_log, "]");
2012
2013 }
2014 PerlIO_printf( Perl_debug_log, "\n" );
2015 }
538e84ed
KW
2016 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
2017 (int)depth*2, "");
2e64971a
DM
2018 for (word=1; word <= trie->wordcount; word++) {
2019 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
2020 (int)word, (int)(trie->wordinfo[word].prev),
2021 (int)(trie->wordinfo[word].len));
2022 }
2023 PerlIO_printf(Perl_debug_log, "\n" );
538e84ed 2024}
3dab1dad 2025/*
3dab1dad 2026 Dumps a fully constructed but uncompressed trie in list form.
538e84ed 2027 List tries normally only are used for construction when the number of
3dab1dad
YO
2028 possible chars (trie->uniquecharcount) is very high.
2029 Used for debugging make_trie().
2030*/
2031STATIC void
55eed653 2032S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
2033 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2034 U32 depth)
3dab1dad
YO
2035{
2036 U32 state;
ab3bbdeb 2037 SV *sv=sv_newmortal();
55eed653 2038 int colwidth= widecharmap ? 6 : 4;
3dab1dad 2039 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2040
2041 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2042
3dab1dad 2043 /* print out the table precompression. */
ab3bbdeb
YO
2044 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
2045 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
2046 "------:-----+-----------------\n" );
538e84ed 2047
3dab1dad
YO
2048 for( state=1 ; state < next_alloc ; state ++ ) {
2049 U16 charid;
538e84ed 2050
ab3bbdeb 2051 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
3dab1dad
YO
2052 (int)depth * 2 + 2,"", (UV)state );
2053 if ( ! trie->states[ state ].wordnum ) {
2054 PerlIO_printf( Perl_debug_log, "%5s| ","");
2055 } else {
2056 PerlIO_printf( Perl_debug_log, "W%4x| ",
2057 trie->states[ state ].wordnum
2058 );
2059 }
2060 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
538e84ed
KW
2061 SV ** const tmp = av_fetch( revcharmap,
2062 TRIE_LIST_ITEM(state,charid).forid, 0);
ab3bbdeb
YO
2063 if ( tmp ) {
2064 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
2065 colwidth,
538e84ed
KW
2066 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2067 colwidth,
2068 PL_colors[0], PL_colors[1],
2069 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2070 | PERL_PV_ESCAPE_FIRSTCHAR
ab3bbdeb 2071 ) ,
1e2e3d02
YO
2072 TRIE_LIST_ITEM(state,charid).forid,
2073 (UV)TRIE_LIST_ITEM(state,charid).newstate
2074 );
538e84ed 2075 if (!(charid % 10))
664e119d
RGS
2076 PerlIO_printf(Perl_debug_log, "\n%*s| ",
2077 (int)((depth * 2) + 14), "");
1e2e3d02 2078 }
ab3bbdeb
YO
2079 }
2080 PerlIO_printf( Perl_debug_log, "\n");
3dab1dad 2081 }
538e84ed 2082}
3dab1dad
YO
2083
2084/*
3dab1dad 2085 Dumps a fully constructed but uncompressed trie in table form.
538e84ed
KW
2086 This is the normal DFA style state transition table, with a few
2087 twists to facilitate compression later.
3dab1dad
YO
2088 Used for debugging make_trie().
2089*/
2090STATIC void
55eed653 2091S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
2092 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2093 U32 depth)
3dab1dad
YO
2094{
2095 U32 state;
2096 U16 charid;
ab3bbdeb 2097 SV *sv=sv_newmortal();
55eed653 2098 int colwidth= widecharmap ? 6 : 4;
3dab1dad 2099 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2100
2101 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
538e84ed 2102
3dab1dad
YO
2103 /*
2104 print out the table precompression so that we can do a visual check
2105 that they are identical.
2106 */
538e84ed 2107
3dab1dad
YO
2108 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
2109
2110 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2b8b4781 2111 SV ** const tmp = av_fetch( revcharmap, charid, 0);
3dab1dad 2112 if ( tmp ) {
538e84ed 2113 PerlIO_printf( Perl_debug_log, "%*s",
ab3bbdeb 2114 colwidth,
538e84ed 2115 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
2116 PL_colors[0], PL_colors[1],
2117 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed
KW
2118 PERL_PV_ESCAPE_FIRSTCHAR
2119 )
ab3bbdeb 2120 );
3dab1dad
YO
2121 }
2122 }
2123
2124 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
2125
2126 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb 2127 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
3dab1dad
YO
2128 }
2129
2130 PerlIO_printf( Perl_debug_log, "\n" );
2131
2132 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2133
538e84ed 2134 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
3dab1dad
YO
2135 (int)depth * 2 + 2,"",
2136 (UV)TRIE_NODENUM( state ) );
2137
2138 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb
YO
2139 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2140 if (v)
2141 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
2142 else
2143 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
3dab1dad
YO
2144 }
2145 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
538e84ed
KW
2146 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
2147 (UV)trie->trans[ state ].check );
3dab1dad 2148 } else {
538e84ed
KW
2149 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
2150 (UV)trie->trans[ state ].check,
3dab1dad
YO
2151 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2152 }
2153 }
07be1b83 2154}
3dab1dad
YO
2155
2156#endif
2157
2e64971a 2158
786e8c11
YO
2159/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2160 startbranch: the first branch in the whole branch sequence
2161 first : start branch of sequence of branch-exact nodes.
2162 May be the same as startbranch
2163 last : Thing following the last branch.
2164 May be the same as tail.
2165 tail : item following the branch sequence
2166 count : words in the sequence
a4525e78 2167 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
786e8c11 2168 depth : indent depth
3dab1dad 2169
786e8c11 2170Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
07be1b83 2171
786e8c11
YO
2172A trie is an N'ary tree where the branches are determined by digital
2173decomposition of the key. IE, at the root node you look up the 1st character and
2174follow that branch repeat until you find the end of the branches. Nodes can be
2175marked as "accepting" meaning they represent a complete word. Eg:
07be1b83 2176
786e8c11 2177 /he|she|his|hers/
72f13be8 2178
786e8c11
YO
2179would convert into the following structure. Numbers represent states, letters
2180following numbers represent valid transitions on the letter from that state, if
2181the number is in square brackets it represents an accepting state, otherwise it
2182will be in parenthesis.
07be1b83 2183
786e8c11
YO
2184 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2185 | |
2186 | (2)
2187 | |
2188 (1) +-i->(6)-+-s->[7]
2189 |
2190 +-s->(3)-+-h->(4)-+-e->[5]
07be1b83 2191
786e8c11
YO
2192 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2193
2194This shows that when matching against the string 'hers' we will begin at state 1
2195read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2196then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2197is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2198single traverse. We store a mapping from accepting to state to which word was
2199matched, and then when we have multiple possibilities we try to complete the
b8fda935 2200rest of the regex in the order in which they occurred in the alternation.
786e8c11
YO
2201
2202The only prior NFA like behaviour that would be changed by the TRIE support is
2203the silent ignoring of duplicate alternations which are of the form:
2204
2205 / (DUPE|DUPE) X? (?{ ... }) Y /x
2206
4b714af6 2207Thus EVAL blocks following a trie may be called a different number of times with
786e8c11 2208and without the optimisation. With the optimisations dupes will be silently
486ec47a 2209ignored. This inconsistent behaviour of EVAL type nodes is well established as
786e8c11
YO
2210the following demonstrates:
2211
2212 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2213
2214which prints out 'word' three times, but
2215
2216 'words'=~/(word|word|word)(?{ print $1 })S/
2217
2218which doesnt print it out at all. This is due to other optimisations kicking in.
2219
2220Example of what happens on a structural level:
2221
486ec47a 2222The regexp /(ac|ad|ab)+/ will produce the following debug output:
786e8c11
YO
2223
2224 1: CURLYM[1] {1,32767}(18)
2225 5: BRANCH(8)
2226 6: EXACT <ac>(16)
2227 8: BRANCH(11)
2228 9: EXACT <ad>(16)
2229 11: BRANCH(14)
2230 12: EXACT <ab>(16)
2231 16: SUCCEED(0)
2232 17: NOTHING(18)
2233 18: END(0)
2234
2235This would be optimizable with startbranch=5, first=5, last=16, tail=16
2236and should turn into:
2237
2238 1: CURLYM[1] {1,32767}(18)
2239 5: TRIE(16)
2240 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2241 <ac>
2242 <ad>
2243 <ab>
2244 16: SUCCEED(0)
2245 17: NOTHING(18)
2246 18: END(0)
2247
2248Cases where tail != last would be like /(?foo|bar)baz/:
2249
2250 1: BRANCH(4)
2251 2: EXACT <foo>(8)
2252 4: BRANCH(7)
2253 5: EXACT <bar>(8)
2254 7: TAIL(8)
2255 8: EXACT <baz>(10)
2256 10: END(0)
2257
2258which would be optimizable with startbranch=1, first=1, last=7, tail=8
2259and would end up looking like:
2260
2261 1: TRIE(8)
2262 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2263 <foo>
2264 <bar>
2265 7: TAIL(8)
2266 8: EXACT <baz>(10)
2267 10: END(0)
2268
c80e42f3 2269 d = uvchr_to_utf8_flags(d, uv, 0);
786e8c11
YO
2270
2271is the recommended Unicode-aware way of saying
2272
2273 *(d++) = uv;
2274*/
2275
fab2782b 2276#define TRIE_STORE_REVCHAR(val) \
786e8c11 2277 STMT_START { \
73031816 2278 if (UTF) { \
668fcfea 2279 SV *zlopp = newSV(UTF8_MAXBYTES); \
88c9ea1e 2280 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
c80e42f3 2281 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
73031816
NC
2282 SvCUR_set(zlopp, kapow - flrbbbbb); \
2283 SvPOK_on(zlopp); \
2284 SvUTF8_on(zlopp); \
2285 av_push(revcharmap, zlopp); \
2286 } else { \
fab2782b 2287 char ooooff = (char)val; \
73031816
NC
2288 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2289 } \
2290 } STMT_END
786e8c11 2291
914a25d5
KW
2292/* This gets the next character from the input, folding it if not already
2293 * folded. */
2294#define TRIE_READ_CHAR STMT_START { \
2295 wordlen++; \
2296 if ( UTF ) { \
2297 /* if it is UTF then it is either already folded, or does not need \
2298 * folding */ \
1c1d615a 2299 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
914a25d5
KW
2300 } \
2301 else if (folder == PL_fold_latin1) { \
7d006b13
KW
2302 /* This folder implies Unicode rules, which in the range expressible \
2303 * by not UTF is the lower case, with the two exceptions, one of \
2304 * which should have been taken care of before calling this */ \
2305 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2306 uvc = toLOWER_L1(*uc); \
2307 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2308 len = 1; \
914a25d5
KW
2309 } else { \
2310 /* raw data, will be folded later if needed */ \
2311 uvc = (U32)*uc; \
2312 len = 1; \
2313 } \
786e8c11
YO
2314} STMT_END
2315
2316
2317
2318#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2319 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
f9003953
NC
2320 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
2321 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
786e8c11
YO
2322 } \
2323 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2324 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2325 TRIE_LIST_CUR( state )++; \
2326} STMT_END
07be1b83 2327
786e8c11
YO
2328#define TRIE_LIST_NEW(state) STMT_START { \
2329 Newxz( trie->states[ state ].trans.list, \
2330 4, reg_trie_trans_le ); \
2331 TRIE_LIST_CUR( state ) = 1; \
2332 TRIE_LIST_LEN( state ) = 4; \
2333} STMT_END
07be1b83 2334
786e8c11
YO
2335#define TRIE_HANDLE_WORD(state) STMT_START { \
2336 U16 dupe= trie->states[ state ].wordnum; \
2337 regnode * const noper_next = regnext( noper ); \
2338 \
786e8c11
YO
2339 DEBUG_r({ \
2340 /* store the word for dumping */ \
2341 SV* tmp; \
2342 if (OP(noper) != NOTHING) \
740cce10 2343 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
786e8c11 2344 else \
740cce10 2345 tmp = newSVpvn_utf8( "", 0, UTF ); \
2b8b4781 2346 av_push( trie_words, tmp ); \
786e8c11
YO
2347 }); \
2348 \
2349 curword++; \
2e64971a
DM
2350 trie->wordinfo[curword].prev = 0; \
2351 trie->wordinfo[curword].len = wordlen; \
2352 trie->wordinfo[curword].accept = state; \
786e8c11
YO
2353 \
2354 if ( noper_next < tail ) { \
2355 if (!trie->jump) \
538e84ed
KW
2356 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2357 sizeof(U16) ); \
7f69552c 2358 trie->jump[curword] = (U16)(noper_next - convert); \
786e8c11
YO
2359 if (!jumper) \
2360 jumper = noper_next; \
2361 if (!nextbranch) \
2362 nextbranch= regnext(cur); \
2363 } \
2364 \
2365 if ( dupe ) { \
2e64971a
DM
2366 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2367 /* chain, so that when the bits of chain are later */\
2368 /* linked together, the dups appear in the chain */\
2369 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2370 trie->wordinfo[dupe].prev = curword; \
786e8c11
YO
2371 } else { \
2372 /* we haven't inserted this word yet. */ \
2373 trie->states[ state ].wordnum = curword; \
2374 } \
2375} STMT_END
07be1b83 2376
3dab1dad 2377
786e8c11
YO
2378#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2379 ( ( base + charid >= ucharcount \
2380 && base + charid < ubound \
2381 && state == trie->trans[ base - ucharcount + charid ].check \
2382 && trie->trans[ base - ucharcount + charid ].next ) \
2383 ? trie->trans[ base - ucharcount + charid ].next \
2384 : ( state==1 ? special : 0 ) \
2385 )
3dab1dad 2386
786e8c11
YO
2387#define MADE_TRIE 1
2388#define MADE_JUMP_TRIE 2
2389#define MADE_EXACT_TRIE 4
3dab1dad 2390
a3621e74 2391STATIC I32
538e84ed
KW
2392S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2393 regnode *first, regnode *last, regnode *tail,
2394 U32 word_count, U32 flags, U32 depth)
a3621e74
YO
2395{
2396 /* first pass, loop through and scan words */
2397 reg_trie_data *trie;
55eed653 2398 HV *widecharmap = NULL;
2b8b4781 2399 AV *revcharmap = newAV();
a3621e74 2400 regnode *cur;
a3621e74
YO
2401 STRLEN len = 0;
2402 UV uvc = 0;
2403 U16 curword = 0;
2404 U32 next_alloc = 0;
786e8c11
YO
2405 regnode *jumper = NULL;
2406 regnode *nextbranch = NULL;
7f69552c 2407 regnode *convert = NULL;
2e64971a 2408 U32 *prev_states; /* temp array mapping each state to previous one */
a3621e74 2409 /* we just use folder as a flag in utf8 */
1e696034 2410 const U8 * folder = NULL;
a3621e74 2411
2b8b4781 2412#ifdef DEBUGGING
cf78de0b 2413 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2b8b4781
NC
2414 AV *trie_words = NULL;
2415 /* along with revcharmap, this only used during construction but both are
2416 * useful during debugging so we store them in the struct when debugging.
8e11feef 2417 */
2b8b4781 2418#else
cf78de0b 2419 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
3dab1dad 2420 STRLEN trie_charcount=0;
3dab1dad 2421#endif
2b8b4781 2422 SV *re_trie_maxbuff;
a3621e74 2423 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2424
2425 PERL_ARGS_ASSERT_MAKE_TRIE;
72f13be8
YO
2426#ifndef DEBUGGING
2427 PERL_UNUSED_ARG(depth);
2428#endif
a3621e74 2429
1e696034 2430 switch (flags) {
a4525e78 2431 case EXACT: case EXACTL: break;
2f7f8cb1 2432 case EXACTFA:
fab2782b 2433 case EXACTFU_SS:
a4525e78
KW
2434 case EXACTFU:
2435 case EXACTFLU8: folder = PL_fold_latin1; break;
1e696034 2436 case EXACTF: folder = PL_fold; break;
fab2782b 2437 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1e696034
KW
2438 }
2439
c944940b 2440 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
a3621e74 2441 trie->refcount = 1;
3dab1dad 2442 trie->startstate = 1;
786e8c11 2443 trie->wordcount = word_count;
f8fc2ecf 2444 RExC_rxi->data->data[ data_slot ] = (void*)trie;
c944940b 2445 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
a4525e78 2446 if (flags == EXACT || flags == EXACTL)
c944940b 2447 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2e64971a
DM
2448 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2449 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2450
a3621e74 2451 DEBUG_r({
2b8b4781 2452 trie_words = newAV();
a3621e74 2453 });
a3621e74 2454
0111c4fd 2455 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
316ebaf2 2456 assert(re_trie_maxbuff);
a3621e74 2457 if (!SvIOK(re_trie_maxbuff)) {
0111c4fd 2458 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
a3621e74 2459 }
df826430 2460 DEBUG_TRIE_COMPILE_r({
538e84ed
KW
2461 PerlIO_printf( Perl_debug_log,
2462 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2463 (int)depth * 2 + 2, "",
2464 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2465 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
3dab1dad 2466 });
538e84ed 2467
7f69552c
YO
2468 /* Find the node we are going to overwrite */
2469 if ( first == startbranch && OP( last ) != BRANCH ) {
2470 /* whole branch chain */
2471 convert = first;
2472 } else {
2473 /* branch sub-chain */
2474 convert = NEXTOPER( first );
2475 }
538e84ed 2476
a3621e74
YO
2477 /* -- First loop and Setup --
2478
2479 We first traverse the branches and scan each word to determine if it
2480 contains widechars, and how many unique chars there are, this is
2481 important as we have to build a table with at least as many columns as we
2482 have unique chars.
2483
2484 We use an array of integers to represent the character codes 0..255
538e84ed
KW
2485 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2486 the native representation of the character value as the key and IV's for
2487 the coded index.
a3621e74
YO
2488
2489 *TODO* If we keep track of how many times each character is used we can
2490 remap the columns so that the table compression later on is more
3b753521 2491 efficient in terms of memory by ensuring the most common value is in the
a3621e74
YO
2492 middle and the least common are on the outside. IMO this would be better
2493 than a most to least common mapping as theres a decent chance the most
2494 common letter will share a node with the least common, meaning the node
486ec47a 2495 will not be compressible. With a middle is most common approach the worst
a3621e74
YO
2496 case is when we have the least common nodes twice.
2497
2498 */
2499
a3621e74 2500 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
df826430 2501 regnode *noper = NEXTOPER( cur );
e1ec3a88 2502 const U8 *uc = (U8*)STRING( noper );
df826430 2503 const U8 *e = uc + STR_LEN( noper );
bc031a7d 2504 int foldlen = 0;
07be1b83 2505 U32 wordlen = 0; /* required init */
bc031a7d
KW
2506 STRLEN minchars = 0;
2507 STRLEN maxchars = 0;
538e84ed
KW
2508 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2509 bitmap?*/
a3621e74 2510
3dab1dad 2511 if (OP(noper) == NOTHING) {
df826430
YO
2512 regnode *noper_next= regnext(noper);
2513 if (noper_next != tail && OP(noper_next) == flags) {
2514 noper = noper_next;
2515 uc= (U8*)STRING(noper);
2516 e= uc + STR_LEN(noper);
2517 trie->minlen= STR_LEN(noper);
2518 } else {
2519 trie->minlen= 0;
2520 continue;
2521 }
3dab1dad 2522 }
df826430 2523
fab2782b 2524 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
02daf0ab
YO
2525 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2526 regardless of encoding */
fab2782b
YO
2527 if (OP( noper ) == EXACTFU_SS) {
2528 /* false positives are ok, so just set this */
0dc4a61d 2529 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
fab2782b
YO
2530 }
2531 }
bc031a7d
KW
2532 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2533 branch */
3dab1dad 2534 TRIE_CHARCOUNT(trie)++;
a3621e74 2535 TRIE_READ_CHAR;
645de4ce 2536
bc031a7d
KW
2537 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2538 * is in effect. Under /i, this character can match itself, or
2539 * anything that folds to it. If not under /i, it can match just
2540 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2541 * all fold to k, and all are single characters. But some folds
2542 * expand to more than one character, so for example LATIN SMALL
2543 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2544 * the string beginning at 'uc' is 'ffi', it could be matched by
2545 * three characters, or just by the one ligature character. (It
2546 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2547 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2548 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2549 * match.) The trie needs to know the minimum and maximum number
2550 * of characters that could match so that it can use size alone to
2551 * quickly reject many match attempts. The max is simple: it is
2552 * the number of folded characters in this branch (since a fold is
2553 * never shorter than what folds to it. */
2554
2555 maxchars++;
2556
2557 /* And the min is equal to the max if not under /i (indicated by
2558 * 'folder' being NULL), or there are no multi-character folds. If
2559 * there is a multi-character fold, the min is incremented just
2560 * once, for the character that folds to the sequence. Each
2561 * character in the sequence needs to be added to the list below of
2562 * characters in the trie, but we count only the first towards the
2563 * min number of characters needed. This is done through the
2564 * variable 'foldlen', which is returned by the macros that look
2565 * for these sequences as the number of bytes the sequence
2566 * occupies. Each time through the loop, we decrement 'foldlen' by
2567 * how many bytes the current char occupies. Only when it reaches
2568 * 0 do we increment 'minchars' or look for another multi-character
2569 * sequence. */
2570 if (folder == NULL) {
2571 minchars++;
2572 }
2573 else if (foldlen > 0) {
2574 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
645de4ce
KW
2575 }
2576 else {
bc031a7d
KW
2577 minchars++;
2578
2579 /* See if *uc is the beginning of a multi-character fold. If
2580 * so, we decrement the length remaining to look at, to account
2581 * for the current character this iteration. (We can use 'uc'
2582 * instead of the fold returned by TRIE_READ_CHAR because for
2583 * non-UTF, the latin1_safe macro is smart enough to account
2584 * for all the unfolded characters, and because for UTF, the
2585 * string will already have been folded earlier in the
2586 * compilation process */
2587 if (UTF) {
2588 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2589 foldlen -= UTF8SKIP(uc);
645de4ce
KW
2590 }
2591 }
bc031a7d
KW
2592 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2593 foldlen--;
2594 }
645de4ce 2595 }
bc031a7d
KW
2596
2597 /* The current character (and any potential folds) should be added
2598 * to the possible matching characters for this position in this
2599 * branch */
a3621e74 2600 if ( uvc < 256 ) {
fab2782b
YO
2601 if ( folder ) {
2602 U8 folded= folder[ (U8) uvc ];
2603 if ( !trie->charmap[ folded ] ) {
2604 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2605 TRIE_STORE_REVCHAR( folded );
2606 }
2607 }
a3621e74
YO
2608 if ( !trie->charmap[ uvc ] ) {
2609 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
fab2782b 2610 TRIE_STORE_REVCHAR( uvc );
a3621e74 2611 }
02daf0ab 2612 if ( set_bit ) {
62012aee
KW
2613 /* store the codepoint in the bitmap, and its folded
2614 * equivalent. */
fab2782b 2615 TRIE_BITMAP_SET(trie, uvc);
0921ee73
T
2616
2617 /* store the folded codepoint */
fab2782b 2618 if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
0921ee73
T
2619
2620 if ( !UTF ) {
2621 /* store first byte of utf8 representation of
acdf4139 2622 variant codepoints */
6f2d5cbc 2623 if (! UVCHR_IS_INVARIANT(uvc)) {
acdf4139 2624 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
0921ee73
T
2625 }
2626 }
02daf0ab
YO
2627 set_bit = 0; /* We've done our bit :-) */
2628 }
a3621e74 2629 } else {
bc031a7d
KW
2630
2631 /* XXX We could come up with the list of code points that fold
2632 * to this using PL_utf8_foldclosures, except not for
2633 * multi-char folds, as there may be multiple combinations
2634 * there that could work, which needs to wait until runtime to
2635 * resolve (The comment about LIGATURE FFI above is such an
2636 * example */
2637
a3621e74 2638 SV** svpp;
55eed653
NC
2639 if ( !widecharmap )
2640 widecharmap = newHV();
a3621e74 2641
55eed653 2642 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
a3621e74
YO
2643
2644 if ( !svpp )
e4584336 2645 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
a3621e74
YO
2646
2647 if ( !SvTRUE( *svpp ) ) {
2648 sv_setiv( *svpp, ++trie->uniquecharcount );
fab2782b 2649 TRIE_STORE_REVCHAR(uvc);
a3621e74
YO
2650 }
2651 }
bc031a7d
KW
2652 } /* end loop through characters in this branch of the trie */
2653
2654 /* We take the min and max for this branch and combine to find the min
2655 * and max for all branches processed so far */
3dab1dad 2656 if( cur == first ) {
bc031a7d
KW
2657 trie->minlen = minchars;
2658 trie->maxlen = maxchars;
2659 } else if (minchars < trie->minlen) {
2660 trie->minlen = minchars;
2661 } else if (maxchars > trie->maxlen) {
2662 trie->maxlen = maxchars;
fab2782b 2663 }
a3621e74
YO
2664 } /* end first pass */
2665 DEBUG_TRIE_COMPILE_r(
538e84ed
KW
2666 PerlIO_printf( Perl_debug_log,
2667 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
3dab1dad 2668 (int)depth * 2 + 2,"",
55eed653 2669 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
be8e71aa
YO
2670 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2671 (int)trie->minlen, (int)trie->maxlen )
a3621e74 2672 );
a3621e74
YO
2673
2674 /*
2675 We now know what we are dealing with in terms of unique chars and
2676 string sizes so we can calculate how much memory a naive
0111c4fd
RGS
2677 representation using a flat table will take. If it's over a reasonable
2678 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
a3621e74
YO
2679 conservative but potentially much slower representation using an array
2680 of lists.
2681
2682 At the end we convert both representations into the same compressed
2683 form that will be used in regexec.c for matching with. The latter
2684 is a form that cannot be used to construct with but has memory
2685 properties similar to the list form and access properties similar
2686 to the table form making it both suitable for fast searches and
2687 small enough that its feasable to store for the duration of a program.
2688
2689 See the comment in the code where the compressed table is produced
2690 inplace from the flat tabe representation for an explanation of how
2691 the compression works.
2692
2693 */
2694
2695
2e64971a
DM
2696 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2697 prev_states[1] = 0;
2698
538e84ed
KW
2699 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2700 > SvIV(re_trie_maxbuff) )
2701 {
a3621e74
YO
2702 /*
2703 Second Pass -- Array Of Lists Representation
2704
2705 Each state will be represented by a list of charid:state records
2706 (reg_trie_trans_le) the first such element holds the CUR and LEN
2707 points of the allocated array. (See defines above).
2708
2709 We build the initial structure using the lists, and then convert
2710 it into the compressed table form which allows faster lookups
2711 (but cant be modified once converted).
a3621e74
YO
2712 */
2713
a3621e74
YO
2714 STRLEN transcount = 1;
2715
538e84ed 2716 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1e2e3d02
YO
2717 "%*sCompiling trie using list compiler\n",
2718 (int)depth * 2 + 2, ""));
686b73d4 2719
c944940b
JH
2720 trie->states = (reg_trie_state *)
2721 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2722 sizeof(reg_trie_state) );
a3621e74
YO
2723 TRIE_LIST_NEW(1);
2724 next_alloc = 2;
2725
2726 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2727
df826430 2728 regnode *noper = NEXTOPER( cur );
c445ea15 2729 U8 *uc = (U8*)STRING( noper );
df826430 2730 const U8 *e = uc + STR_LEN( noper );
c445ea15
AL
2731 U32 state = 1; /* required init */
2732 U16 charid = 0; /* sanity init */
07be1b83 2733 U32 wordlen = 0; /* required init */
c445ea15 2734
df826430
YO
2735 if (OP(noper) == NOTHING) {
2736 regnode *noper_next= regnext(noper);
2737 if (noper_next != tail && OP(noper_next) == flags) {
2738 noper = noper_next;
2739 uc= (U8*)STRING(noper);
2740 e= uc + STR_LEN(noper);
2741 }
2742 }
2743
3dab1dad 2744 if (OP(noper) != NOTHING) {
786e8c11 2745 for ( ; uc < e ; uc += len ) {
c445ea15 2746
786e8c11 2747 TRIE_READ_CHAR;
c445ea15 2748
786e8c11
YO
2749 if ( uvc < 256 ) {
2750 charid = trie->charmap[ uvc ];
c445ea15 2751 } else {
538e84ed
KW
2752 SV** const svpp = hv_fetch( widecharmap,
2753 (char*)&uvc,
2754 sizeof( UV ),
2755 0);
786e8c11
YO
2756 if ( !svpp ) {
2757 charid = 0;
2758 } else {
2759 charid=(U16)SvIV( *svpp );
2760 }
c445ea15 2761 }
538e84ed
KW
2762 /* charid is now 0 if we dont know the char read, or
2763 * nonzero if we do */
786e8c11 2764 if ( charid ) {
a3621e74 2765
786e8c11
YO
2766 U16 check;
2767 U32 newstate = 0;
a3621e74 2768
786e8c11
YO
2769 charid--;
2770 if ( !trie->states[ state ].trans.list ) {
2771 TRIE_LIST_NEW( state );
c445ea15 2772 }
538e84ed
KW
2773 for ( check = 1;
2774 check <= TRIE_LIST_USED( state );
2775 check++ )
2776 {
2777 if ( TRIE_LIST_ITEM( state, check ).forid
2778 == charid )
2779 {
786e8c11
YO
2780 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2781 break;
2782 }
2783 }
2784 if ( ! newstate ) {
2785 newstate = next_alloc++;
2e64971a 2786 prev_states[newstate] = state;
786e8c11
YO
2787 TRIE_LIST_PUSH( state, charid, newstate );
2788 transcount++;
2789 }
2790 state = newstate;
2791 } else {
2792 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
c445ea15 2793 }
a28509cc 2794 }
c445ea15 2795 }
3dab1dad 2796 TRIE_HANDLE_WORD(state);
a3621e74
YO
2797
2798 } /* end second pass */
2799
1e2e3d02 2800 /* next alloc is the NEXT state to be allocated */
538e84ed 2801 trie->statecount = next_alloc;
c944940b
JH
2802 trie->states = (reg_trie_state *)
2803 PerlMemShared_realloc( trie->states,
2804 next_alloc
2805 * sizeof(reg_trie_state) );
a3621e74 2806
3dab1dad 2807 /* and now dump it out before we compress it */
2b8b4781
NC
2808 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2809 revcharmap, next_alloc,
2810 depth+1)
1e2e3d02 2811 );
a3621e74 2812
c944940b
JH
2813 trie->trans = (reg_trie_trans *)
2814 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
a3621e74
YO
2815 {
2816 U32 state;
a3621e74
YO
2817 U32 tp = 0;
2818 U32 zp = 0;
2819
2820
2821 for( state=1 ; state < next_alloc ; state ++ ) {
2822 U32 base=0;
2823
2824 /*
2825 DEBUG_TRIE_COMPILE_MORE_r(
2826 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2827 );
2828 */
2829
2830 if (trie->states[state].trans.list) {
2831 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2832 U16 maxid=minid;
a28509cc 2833 U16 idx;
a3621e74
YO
2834
2835 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15
AL
2836 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2837 if ( forid < minid ) {
2838 minid=forid;
2839 } else if ( forid > maxid ) {
2840 maxid=forid;
2841 }
a3621e74
YO
2842 }
2843 if ( transcount < tp + maxid - minid + 1) {
2844 transcount *= 2;
c944940b
JH
2845 trie->trans = (reg_trie_trans *)
2846 PerlMemShared_realloc( trie->trans,
446bd890
NC
2847 transcount
2848 * sizeof(reg_trie_trans) );
538e84ed
KW
2849 Zero( trie->trans + (transcount / 2),
2850 transcount / 2,
2851 reg_trie_trans );
a3621e74
YO
2852 }
2853 base = trie->uniquecharcount + tp - minid;
2854 if ( maxid == minid ) {
2855 U32 set = 0;
2856 for ( ; zp < tp ; zp++ ) {
2857 if ( ! trie->trans[ zp ].next ) {
2858 base = trie->uniquecharcount + zp - minid;
538e84ed
KW
2859 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2860 1).newstate;
a3621e74
YO
2861 trie->trans[ zp ].check = state;
2862 set = 1;
2863 break;
2864 }
2865 }
2866 if ( !set ) {
538e84ed
KW
2867 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2868 1).newstate;
a3621e74
YO
2869 trie->trans[ tp ].check = state;
2870 tp++;
2871 zp = tp;
2872 }
2873 } else {
2874 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
538e84ed
KW
2875 const U32 tid = base
2876 - trie->uniquecharcount
2877 + TRIE_LIST_ITEM( state, idx ).forid;
2878 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2879 idx ).newstate;
a3621e74
YO
2880 trie->trans[ tid ].check = state;
2881 }
2882 tp += ( maxid - minid + 1 );
2883 }
2884 Safefree(trie->states[ state ].trans.list);
2885 }
2886 /*
2887 DEBUG_TRIE_COMPILE_MORE_r(
2888 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2889 );
2890 */
2891 trie->states[ state ].trans.base=base;
2892 }
cc601c31 2893 trie->lasttrans = tp + 1;
a3621e74
YO
2894 }
2895 } else {
2896 /*
2897 Second Pass -- Flat Table Representation.
2898
b423522f
KW
2899 we dont use the 0 slot of either trans[] or states[] so we add 1 to
2900 each. We know that we will need Charcount+1 trans at most to store
2901 the data (one row per char at worst case) So we preallocate both
2902 structures assuming worst case.
a3621e74
YO
2903
2904 We then construct the trie using only the .next slots of the entry
2905 structs.
2906
b423522f
KW
2907 We use the .check field of the first entry of the node temporarily
2908 to make compression both faster and easier by keeping track of how
2909 many non zero fields are in the node.
a3621e74
YO
2910
2911 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2912 transition.
2913
b423522f
KW
2914 There are two terms at use here: state as a TRIE_NODEIDX() which is
2915 a number representing the first entry of the node, and state as a
2916 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2917 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2918 if there are 2 entrys per node. eg:
a3621e74
YO
2919
2920 A B A B
2921 1. 2 4 1. 3 7
2922 2. 0 3 3. 0 5
2923 3. 0 0 5. 0 0
2924 4. 0 0 7. 0 0
2925
b423522f
KW
2926 The table is internally in the right hand, idx form. However as we
2927 also have to deal with the states array which is indexed by nodenum
2928 we have to use TRIE_NODENUM() to convert.
a3621e74
YO
2929
2930 */
538e84ed 2931 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1e2e3d02
YO
2932 "%*sCompiling trie using table compiler\n",
2933 (int)depth * 2 + 2, ""));
3dab1dad 2934
c944940b
JH
2935 trie->trans = (reg_trie_trans *)
2936 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2937 * trie->uniquecharcount + 1,
2938 sizeof(reg_trie_trans) );
2939 trie->states = (reg_trie_state *)
2940 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2941 sizeof(reg_trie_state) );
a3621e74
YO
2942 next_alloc = trie->uniquecharcount + 1;
2943
3dab1dad 2944
a3621e74
YO
2945 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2946
df826430 2947 regnode *noper = NEXTOPER( cur );
a28509cc 2948 const U8 *uc = (U8*)STRING( noper );
df826430 2949 const U8 *e = uc + STR_LEN( noper );
a3621e74
YO
2950
2951 U32 state = 1; /* required init */
2952
2953 U16 charid = 0; /* sanity init */
2954 U32 accept_state = 0; /* sanity init */
a3621e74 2955
07be1b83 2956 U32 wordlen = 0; /* required init */
a3621e74 2957
df826430
YO
2958 if (OP(noper) == NOTHING) {
2959 regnode *noper_next= regnext(noper);
2960 if (noper_next != tail && OP(noper_next) == flags) {
2961 noper = noper_next;
2962 uc= (U8*)STRING(noper);
2963 e= uc + STR_LEN(noper);
2964 }
2965 }
fab2782b 2966
3dab1dad 2967 if ( OP(noper) != NOTHING ) {
786e8c11 2968 for ( ; uc < e ; uc += len ) {
a3621e74 2969
786e8c11 2970 TRIE_READ_CHAR;
a3621e74 2971
786e8c11
YO
2972 if ( uvc < 256 ) {
2973 charid = trie->charmap[ uvc ];
2974 } else {
538e84ed
KW
2975 SV* const * const svpp = hv_fetch( widecharmap,
2976 (char*)&uvc,
2977 sizeof( UV ),
2978 0);
786e8c11 2979 charid = svpp ? (U16)SvIV(*svpp) : 0;
a3621e74 2980 }
786e8c11
YO
2981 if ( charid ) {
2982 charid--;
2983 if ( !trie->trans[ state + charid ].next ) {
2984 trie->trans[ state + charid ].next = next_alloc;
2985 trie->trans[ state ].check++;
2e64971a
DM
2986 prev_states[TRIE_NODENUM(next_alloc)]
2987 = TRIE_NODENUM(state);
786e8c11
YO
2988 next_alloc += trie->uniquecharcount;
2989 }
2990 state = trie->trans[ state + charid ].next;
2991 } else {
2992 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2993 }
538e84ed
KW
2994 /* charid is now 0 if we dont know the char read, or
2995 * nonzero if we do */
a3621e74 2996 }
a3621e74 2997 }
3dab1dad
YO
2998 accept_state = TRIE_NODENUM( state );
2999 TRIE_HANDLE_WORD(accept_state);
a3621e74
YO
3000
3001 } /* end second pass */
3002
3dab1dad 3003 /* and now dump it out before we compress it */
2b8b4781
NC
3004 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3005 revcharmap,
3006 next_alloc, depth+1));
a3621e74 3007
a3621e74
YO
3008 {
3009 /*
3010 * Inplace compress the table.*
3011
3012 For sparse data sets the table constructed by the trie algorithm will
3013 be mostly 0/FAIL transitions or to put it another way mostly empty.
3014 (Note that leaf nodes will not contain any transitions.)
3015
3016 This algorithm compresses the tables by eliminating most such
3017 transitions, at the cost of a modest bit of extra work during lookup:
3018
3019 - Each states[] entry contains a .base field which indicates the
3020 index in the state[] array wheres its transition data is stored.
3021
3b753521 3022 - If .base is 0 there are no valid transitions from that node.
a3621e74
YO
3023
3024 - If .base is nonzero then charid is added to it to find an entry in
3025 the trans array.
3026
3027 -If trans[states[state].base+charid].check!=state then the
3028 transition is taken to be a 0/Fail transition. Thus if there are fail
3029 transitions at the front of the node then the .base offset will point
3030 somewhere inside the previous nodes data (or maybe even into a node
3031 even earlier), but the .check field determines if the transition is
3032 valid.
3033
786e8c11 3034 XXX - wrong maybe?
a3621e74 3035 The following process inplace converts the table to the compressed
3b753521 3036 table: We first do not compress the root node 1,and mark all its
a3621e74 3037 .check pointers as 1 and set its .base pointer as 1 as well. This
3b753521
FN
3038 allows us to do a DFA construction from the compressed table later,
3039 and ensures that any .base pointers we calculate later are greater
3040 than 0.
a3621e74
YO
3041
3042 - We set 'pos' to indicate the first entry of the second node.
3043
3044 - We then iterate over the columns of the node, finding the first and
3045 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3046 and set the .check pointers accordingly, and advance pos
3047 appropriately and repreat for the next node. Note that when we copy
3048 the next pointers we have to convert them from the original
3049 NODEIDX form to NODENUM form as the former is not valid post
3050 compression.
3051
3052 - If a node has no transitions used we mark its base as 0 and do not
3053 advance the pos pointer.
3054
3055 - If a node only has one transition we use a second pointer into the
3056 structure to fill in allocated fail transitions from other states.
3057 This pointer is independent of the main pointer and scans forward
3058 looking for null transitions that are allocated to a state. When it
3059 finds one it writes the single transition into the "hole". If the
786e8c11 3060 pointer doesnt find one the single transition is appended as normal.
a3621e74
YO
3061
3062 - Once compressed we can Renew/realloc the structures to release the
3063 excess space.
3064
3065 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3066 specifically Fig 3.47 and the associated pseudocode.
3067
3068 demq
3069 */
a3b680e6 3070 const U32 laststate = TRIE_NODENUM( next_alloc );
a28509cc 3071 U32 state, charid;
a3621e74 3072 U32 pos = 0, zp=0;
1e2e3d02 3073 trie->statecount = laststate;
a3621e74
YO
3074
3075 for ( state = 1 ; state < laststate ; state++ ) {
3076 U8 flag = 0;
a28509cc
AL
3077 const U32 stateidx = TRIE_NODEIDX( state );
3078 const U32 o_used = trie->trans[ stateidx ].check;
3079 U32 used = trie->trans[ stateidx ].check;
a3621e74
YO
3080 trie->trans[ stateidx ].check = 0;
3081
538e84ed
KW
3082 for ( charid = 0;
3083 used && charid < trie->uniquecharcount;
3084 charid++ )
3085 {
a3621e74
YO
3086 if ( flag || trie->trans[ stateidx + charid ].next ) {
3087 if ( trie->trans[ stateidx + charid ].next ) {
3088 if (o_used == 1) {
3089 for ( ; zp < pos ; zp++ ) {
3090 if ( ! trie->trans[ zp ].next ) {
3091 break;
3092 }
3093 }
538e84ed
KW
3094 trie->states[ state ].trans.base
3095 = zp
3096 + trie->uniquecharcount
3097 - charid ;
3098 trie->trans[ zp ].next
3099 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3100 + charid ].next );
a3621e74
YO
3101 trie->trans[ zp ].check = state;
3102 if ( ++zp > pos ) pos = zp;
3103 break;
3104 }
3105 used--;
3106 }
3107 if ( !flag ) {
3108 flag = 1;
538e84ed
KW
3109 trie->states[ state ].trans.base
3110 = pos + trie->uniquecharcount - charid ;
a3621e74 3111 }
538e84ed
KW
3112 trie->trans[ pos ].next
3113 = SAFE_TRIE_NODENUM(
3114 trie->trans[ stateidx + charid ].next );
a3621e74
YO
3115 trie->trans[ pos ].check = state;
3116 pos++;
3117 }
3118 }
3119 }
cc601c31 3120 trie->lasttrans = pos + 1;
c944940b
JH
3121 trie->states = (reg_trie_state *)
3122 PerlMemShared_realloc( trie->states, laststate
3123 * sizeof(reg_trie_state) );
a3621e74 3124 DEBUG_TRIE_COMPILE_MORE_r(
538e84ed
KW
3125 PerlIO_printf( Perl_debug_log,
3126 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
3127 (int)depth * 2 + 2,"",
3128 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3129 + 1 ),
3130 (IV)next_alloc,
3131 (IV)pos,
3132 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
a3621e74
YO
3133 );
3134
3135 } /* end table compress */
3136 }
1e2e3d02 3137 DEBUG_TRIE_COMPILE_MORE_r(
538e84ed
KW
3138 PerlIO_printf(Perl_debug_log,
3139 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1e2e3d02
YO
3140 (int)depth * 2 + 2, "",
3141 (UV)trie->statecount,
3142 (UV)trie->lasttrans)
3143 );
cc601c31 3144 /* resize the trans array to remove unused space */
c944940b
JH
3145 trie->trans = (reg_trie_trans *)
3146 PerlMemShared_realloc( trie->trans, trie->lasttrans
3147 * sizeof(reg_trie_trans) );
a3621e74 3148
538e84ed 3149 { /* Modify the program and insert the new TRIE node */
3dab1dad
YO
3150 U8 nodetype =(U8)(flags & 0xFF);
3151 char *str=NULL;
538e84ed 3152
07be1b83 3153#ifdef DEBUGGING
e62cc96a 3154 regnode *optimize = NULL;
7122b237
YO
3155#ifdef RE_TRACK_PATTERN_OFFSETS
3156
b57a0404
JH
3157 U32 mjd_offset = 0;
3158 U32 mjd_nodelen = 0;
7122b237
YO
3159#endif /* RE_TRACK_PATTERN_OFFSETS */
3160#endif /* DEBUGGING */
a3621e74 3161 /*
3dab1dad
YO
3162 This means we convert either the first branch or the first Exact,
3163 depending on whether the thing following (in 'last') is a branch
3164 or not and whther first is the startbranch (ie is it a sub part of
3165 the alternation or is it the whole thing.)
3b753521 3166 Assuming its a sub part we convert the EXACT otherwise we convert
3dab1dad 3167 the whole branch sequence, including the first.
a3621e74 3168 */
3dab1dad 3169 /* Find the node we are going to overwrite */
7f69552c 3170 if ( first != startbranch || OP( last ) == BRANCH ) {
07be1b83 3171 /* branch sub-chain */
3dab1dad 3172 NEXT_OFF( first ) = (U16)(last - first);
7122b237 3173#ifdef RE_TRACK_PATTERN_OFFSETS
07be1b83
YO
3174 DEBUG_r({
3175 mjd_offset= Node_Offset((convert));
3176 mjd_nodelen= Node_Length((convert));
3177 });
7122b237 3178#endif
7f69552c 3179 /* whole branch chain */
7122b237
YO
3180 }
3181#ifdef RE_TRACK_PATTERN_OFFSETS
3182 else {
7f69552c
YO
3183 DEBUG_r({
3184 const regnode *nop = NEXTOPER( convert );
3185 mjd_offset= Node_Offset((nop));
3186 mjd_nodelen= Node_Length((nop));
3187 });
07be1b83
YO
3188 }
3189 DEBUG_OPTIMISE_r(
538e84ed
KW
3190 PerlIO_printf(Perl_debug_log,
3191 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
07be1b83 3192 (int)depth * 2 + 2, "",
786e8c11 3193 (UV)mjd_offset, (UV)mjd_nodelen)
07be1b83 3194 );
7122b237 3195#endif
538e84ed 3196 /* But first we check to see if there is a common prefix we can
3dab1dad
YO
3197 split out as an EXACT and put in front of the TRIE node. */
3198 trie->startstate= 1;
55eed653 3199 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3dab1dad 3200 U32 state;
1e2e3d02 3201 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
a3621e74 3202 U32 ofs = 0;
8e11feef
RGS
3203 I32 idx = -1;
3204 U32 count = 0;
3205 const U32 base = trie->states[ state ].trans.base;
a3621e74 3206
3dab1dad 3207 if ( trie->states[state].wordnum )
8e11feef 3208 count = 1;
a3621e74 3209
8e11feef 3210 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
cc601c31
YO
3211 if ( ( base + ofs >= trie->uniquecharcount ) &&
3212 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
a3621e74
YO
3213 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3214 {
3dab1dad 3215 if ( ++count > 1 ) {
2b8b4781 3216 SV **tmp = av_fetch( revcharmap, ofs, 0);
07be1b83 3217 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 3218 if ( state == 1 ) break;
3dab1dad
YO
3219 if ( count == 2 ) {
3220 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3221 DEBUG_OPTIMISE_r(
8e11feef
RGS
3222 PerlIO_printf(Perl_debug_log,
3223 "%*sNew Start State=%"UVuf" Class: [",
3224 (int)depth * 2 + 2, "",
786e8c11 3225 (UV)state));
be8e71aa 3226 if (idx >= 0) {
2b8b4781 3227 SV ** const tmp = av_fetch( revcharmap, idx, 0);
be8e71aa 3228 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 3229
3dab1dad 3230 TRIE_BITMAP_SET(trie,*ch);
8e11feef
RGS
3231 if ( folder )
3232 TRIE_BITMAP_SET(trie, folder[ *ch ]);
3dab1dad 3233 DEBUG_OPTIMISE_r(
f1f66076 3234 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3dab1dad 3235 );
8e11feef
RGS
3236 }
3237 }
3238 TRIE_BITMAP_SET(trie,*ch);
3239 if ( folder )
3240 TRIE_BITMAP_SET(trie,folder[ *ch ]);
3241 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
3242 }
3243 idx = ofs;
3244 }
3dab1dad
YO
3245 }
3246 if ( count == 1 ) {
2b8b4781 3247 SV **tmp = av_fetch( revcharmap, idx, 0);
c490c714
YO
3248 STRLEN len;
3249 char *ch = SvPV( *tmp, len );
de734bd5
A
3250 DEBUG_OPTIMISE_r({
3251 SV *sv=sv_newmortal();
8e11feef
RGS
3252 PerlIO_printf( Perl_debug_log,
3253 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
3254 (int)depth * 2 + 2, "",
538e84ed
KW
3255 (UV)state, (UV)idx,
3256 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
de734bd5
A
3257 PL_colors[0], PL_colors[1],
3258 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed 3259 PERL_PV_ESCAPE_FIRSTCHAR
de734bd5
A
3260 )
3261 );
3262 });
3dab1dad
YO
3263 if ( state==1 ) {
3264 OP( convert ) = nodetype;
3265 str=STRING(convert);
3266 STR_LEN(convert)=0;
3267 }
c490c714
YO
3268 STR_LEN(convert) += len;
3269 while (len--)
de734bd5 3270 *str++ = *ch++;
8e11feef 3271 } else {
538e84ed 3272#ifdef DEBUGGING
8e11feef
RGS
3273 if (state>1)
3274 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
f9049ba1 3275#endif
8e11feef
RGS
3276 break;
3277 }
3278 }
2e64971a 3279 trie->prefixlen = (state-1);
3dab1dad 3280 if (str) {
8e11feef 3281 regnode *n = convert+NODE_SZ_STR(convert);
07be1b83 3282 NEXT_OFF(convert) = NODE_SZ_STR(convert);
8e11feef 3283 trie->startstate = state;
07be1b83
YO
3284 trie->minlen -= (state - 1);
3285 trie->maxlen -= (state - 1);
33809eae
JH
3286#ifdef DEBUGGING
3287 /* At least the UNICOS C compiler choked on this
3288 * being argument to DEBUG_r(), so let's just have
3289 * it right here. */
3290 if (
3291#ifdef PERL_EXT_RE_BUILD
3292 1
3293#else
3294 DEBUG_r_TEST
3295#endif
3296 ) {
3297 regnode *fix = convert;
3298 U32 word = trie->wordcount;
3299 mjd_nodelen++;
3300 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3301 while( ++fix < n ) {
3302 Set_Node_Offset_Length(fix, 0, 0);
3303 }
3304 while (word--) {
3305 SV ** const tmp = av_fetch( trie_words, word, 0 );
3306 if (tmp) {
3307 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3308 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3309 else
3310 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3311 }
3312 }
3313 }
3314#endif
8e11feef
RGS
3315 if (trie->maxlen) {
3316 convert = n;
3317 } else {
3dab1dad 3318 NEXT_OFF(convert) = (U16)(tail - convert);
a5ca303d 3319 DEBUG_r(optimize= n);
3dab1dad
YO
3320 }
3321 }
3322 }
538e84ed
KW
3323 if (!jumper)
3324 jumper = last;
3dab1dad 3325 if ( trie->maxlen ) {
8e11feef
RGS
3326 NEXT_OFF( convert ) = (U16)(tail - convert);
3327 ARG_SET( convert, data_slot );
538e84ed
KW
3328 /* Store the offset to the first unabsorbed branch in
3329 jump[0], which is otherwise unused by the jump logic.
786e8c11 3330 We use this when dumping a trie and during optimisation. */
538e84ed 3331 if (trie->jump)
7f69552c 3332 trie->jump[0] = (U16)(nextbranch - convert);
538e84ed 3333
6c48061a
YO
3334 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3335 * and there is a bitmap
3336 * and the first "jump target" node we found leaves enough room
3337 * then convert the TRIE node into a TRIEC node, with the bitmap
3338 * embedded inline in the opcode - this is hypothetically faster.
3339 */
3340 if ( !trie->states[trie->startstate].wordnum
3341 && trie->bitmap
3342 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
786e8c11
YO
3343 {
3344 OP( convert ) = TRIEC;
3345 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
446bd890 3346 PerlMemShared_free(trie->bitmap);
786e8c11 3347 trie->bitmap= NULL;
538e84ed 3348 } else
786e8c11 3349 OP( convert ) = TRIE;
a3621e74 3350
3dab1dad
YO
3351 /* store the type in the flags */
3352 convert->flags = nodetype;
a5ca303d 3353 DEBUG_r({
538e84ed
KW
3354 optimize = convert
3355 + NODE_STEP_REGNODE
a5ca303d
YO
3356 + regarglen[ OP( convert ) ];
3357 });
538e84ed 3358 /* XXX We really should free up the resource in trie now,
a5ca303d 3359 as we won't use them - (which resources?) dmq */
3dab1dad 3360 }
a3621e74 3361 /* needed for dumping*/
e62cc96a 3362 DEBUG_r(if (optimize) {
07be1b83 3363 regnode *opt = convert;
bcdf7404 3364
e62cc96a 3365 while ( ++opt < optimize) {
07be1b83
YO
3366 Set_Node_Offset_Length(opt,0,0);
3367 }
538e84ed
KW
3368 /*
3369 Try to clean up some of the debris left after the
786e8c11 3370 optimisation.
a3621e74 3371 */
786e8c11 3372 while( optimize < jumper ) {
07be1b83 3373 mjd_nodelen += Node_Length((optimize));
a3621e74 3374 OP( optimize ) = OPTIMIZED;
07be1b83 3375 Set_Node_Offset_Length(optimize,0,0);
a3621e74
YO
3376 optimize++;
3377 }
07be1b83 3378 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
a3621e74
YO
3379 });
3380 } /* end node insert */
2e64971a
DM
3381
3382 /* Finish populating the prev field of the wordinfo array. Walk back
3383 * from each accept state until we find another accept state, and if
3384 * so, point the first word's .prev field at the second word. If the
3385 * second already has a .prev field set, stop now. This will be the
3386 * case either if we've already processed that word's accept state,
3b753521
FN
3387 * or that state had multiple words, and the overspill words were
3388 * already linked up earlier.
2e64971a
DM
3389 */
3390 {
3391 U16 word;
3392 U32 state;
3393 U16 prev;
3394
3395 for (word=1; word <= trie->wordcount; word++) {
3396 prev = 0;
3397 if (trie->wordinfo[word].prev)
3398 continue;
3399 state = trie->wordinfo[word].accept;
3400 while (state) {
3401 state = prev_states[state];
3402 if (!state)
3403 break;
3404 prev = trie->states[state].wordnum;
3405 if (prev)
3406 break;
3407 }
3408 trie->wordinfo[word].prev = prev;
3409 }
3410 Safefree(prev_states);
3411 }
3412
3413
3414 /* and now dump out the compressed format */
3415 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3416
55eed653 3417 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2b8b4781
NC
3418#ifdef DEBUGGING
3419 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3420 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3421#else
03e70be4 3422 SvREFCNT_dec_NN(revcharmap);
07be1b83 3423#endif
538e84ed
KW
3424 return trie->jump
3425 ? MADE_JUMP_TRIE
3426 : trie->startstate>1
3427 ? MADE_EXACT_TRIE
786e8c11
YO
3428 : MADE_TRIE;
3429}
3430
615a2e7f
YO
3431STATIC regnode *
3432S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
786e8c11 3433{
b423522f
KW
3434/* The Trie is constructed and compressed now so we can build a fail array if
3435 * it's needed
786e8c11 3436
b423522f
KW
3437 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3438 3.32 in the
3439 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3440 Ullman 1985/88
786e8c11
YO
3441 ISBN 0-201-10088-6
3442
b423522f
KW
3443 We find the fail state for each state in the trie, this state is the longest
3444 proper suffix of the current state's 'word' that is also a proper prefix of
3445 another word in our trie. State 1 represents the word '' and is thus the
3446 default fail state. This allows the DFA not to have to restart after its
3447 tried and failed a word at a given point, it simply continues as though it
3448 had been matching the other word in the first place.
786e8c11
YO
3449 Consider
3450 'abcdgu'=~/abcdefg|cdgu/
b423522f
KW
3451 When we get to 'd' we are still matching the first word, we would encounter
3452 'g' which would fail, which would bring us to the state representing 'd' in
3453 the second word where we would try 'g' and succeed, proceeding to match
3454 'cdgu'.
786e8c11
YO
3455 */
3456 /* add a fail transition */
3251b653
NC
3457 const U32 trie_offset = ARG(source);
3458 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
786e8c11
YO
3459 U32 *q;
3460 const U32 ucharcount = trie->uniquecharcount;
1e2e3d02 3461 const U32 numstates = trie->statecount;
786e8c11
YO
3462 const U32 ubound = trie->lasttrans + ucharcount;
3463 U32 q_read = 0;
3464 U32 q_write = 0;
3465 U32 charid;
3466 U32 base = trie->states[ 1 ].trans.base;
3467 U32 *fail;
3468 reg_ac_data *aho;
cf78de0b 3469 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
615a2e7f 3470 regnode *stclass;
786e8c11 3471 GET_RE_DEBUG_FLAGS_DECL;
7918f24d 3472
615a2e7f 3473 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
81611534 3474 PERL_UNUSED_CONTEXT;
786e8c11
YO
3475#ifndef DEBUGGING
3476 PERL_UNUSED_ARG(depth);
3477#endif
3478
615a2e7f
YO
3479 if ( OP(source) == TRIE ) {
3480 struct regnode_1 *op = (struct regnode_1 *)
3481 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3482 StructCopy(source,op,struct regnode_1);
3483 stclass = (regnode *)op;
3484 } else {
3485 struct regnode_charclass *op = (struct regnode_charclass *)
3486 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3487 StructCopy(source,op,struct regnode_charclass);
3488 stclass = (regnode *)op;
3489 }
2f306ab9 3490 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
786e8c11
YO
3491
3492 ARG_SET( stclass, data_slot );
c944940b 3493 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
f8fc2ecf 3494 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3251b653 3495 aho->trie=trie_offset;
446bd890
NC
3496 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3497 Copy( trie->states, aho->states, numstates, reg_trie_state );
786e8c11 3498 Newxz( q, numstates, U32);
c944940b 3499 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
786e8c11
YO
3500 aho->refcount = 1;
3501 fail = aho->fail;
3502 /* initialize fail[0..1] to be 1 so that we always have
3503 a valid final fail state */
3504 fail[ 0 ] = fail[ 1 ] = 1;
3505
3506 for ( charid = 0; charid < ucharcount ; charid++ ) {
3507 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3508 if ( newstate ) {
3509 q[ q_write ] = newstate;
3510 /* set to point at the root */
3511 fail[ q[ q_write++ ] ]=1;
3512 }
3513 }
3514 while ( q_read < q_write) {
3515 const U32 cur = q[ q_read++ % numstates ];
3516 base = trie->states[ cur ].trans.base;
3517
3518 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3519 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3520 if (ch_state) {
3521 U32 fail_state = cur;
3522 U32 fail_base;
3523 do {
3524 fail_state = fail[ fail_state ];
3525 fail_base = aho->states[ fail_state ].trans.base;
3526 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3527
3528 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3529 fail[ ch_state ] = fail_state;
3530 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3531 {
3532 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3533 }
3534 q[ q_write++ % numstates] = ch_state;