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