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