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