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