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