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