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