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