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