5 * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
7 * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
10 /* This file contains functions for compiling a regular expression. See
11 * also regexec.c which funnily enough, contains functions for executing
12 * a regular expression.
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.
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!
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.
29 /* The names of the functions have been changed from regcomp and
30 * regexec to pregcomp and pregexec in order to avoid conflicts
31 * with the POSIX routines of the same names.
34 #ifdef PERL_EXT_RE_BUILD
39 * pregcomp and pregexec -- regsub and regerror are not used in perl
41 * Copyright (c) 1986 by University of Toronto.
42 * Written by Henry Spencer. Not derived from licensed software.
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:
48 * 1. The author is not responsible for the consequences of use of
49 * this software, no matter how awful, even if they arise
52 * 2. The origin of this software must not be misrepresented, either
53 * by explicit claim or by omission.
55 * 3. Altered versions must be plainly marked as such, and must not
56 * be misrepresented as being the original software.
59 **** Alterations to Henry's code are...
61 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63 **** by Larry Wall and others
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.
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.
74 #define PERL_IN_REGCOMP_C
77 #ifndef PERL_IN_XSUB_RE
82 #ifdef PERL_IN_XSUB_RE
84 EXTERN_C const struct regexp_engine my_reg_engine;
89 #include "dquote_inline.h"
90 #include "invlist_inline.h"
91 #include "unicode_constants.h"
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
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)
97 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
98 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
101 #define STATIC static
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. */
108 typedef 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 */
114 struct scan_frame *this_prev_frame; /* this previous frame */
115 struct scan_frame *prev_frame; /* previous frame */
116 struct scan_frame *next_frame; /* next frame */
119 /* Certain characters are output as a sequence with the first being a
121 #define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
124 struct RExC_state_t {
125 U32 flags; /* RXf_* are we folding, multilining? */
126 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
127 char *precomp; /* uncompiled string. */
128 char *precomp_end; /* pointer to end of uncompiled string. */
129 REGEXP *rx_sv; /* The SV that is the regexp. */
130 regexp *rx; /* perl core regexp structure */
131 regexp_internal *rxi; /* internal data for regexp object
133 char *start; /* Start of input for compile */
134 char *end; /* End of input for compile */
135 char *parse; /* Input-scan pointer. */
136 char *copy_start; /* start of copy of input within
137 constructed parse string */
138 char *copy_start_in_input; /* Position in input string
139 corresponding to copy_start */
140 SSize_t whilem_seen; /* number of WHILEM in this expr */
141 regnode *emit_start; /* Start of emitted-code area */
142 regnode_offset emit; /* Code-emit pointer */
143 I32 naughty; /* How bad is this pattern? */
144 I32 sawback; /* Did we see \1, ...? */
146 SSize_t size; /* Number of regnode equivalents in
149 /* position beyond 'precomp' of the warning message furthest away from
150 * 'precomp'. During the parse, no warnings are raised for any problems
151 * earlier in the parse than this position. This works if warnings are
152 * raised the first time a given spot is parsed, and if only one
153 * independent warning is raised for any given spot */
154 Size_t latest_warn_offset;
156 I32 npar; /* Capture buffer count so far in the
157 parse, (OPEN) plus one. ("par" 0 is
159 I32 total_par; /* During initial parse, is either 0,
160 or -1; the latter indicating a
161 reparse is needed. After that pass,
162 it is what 'npar' became after the
163 pass. Hence, it being > 0 indicates
164 we are in a reparse situation */
165 I32 nestroot; /* root parens we are in - used by
168 regnode_offset *open_parens; /* offsets to open parens */
169 regnode_offset *close_parens; /* offsets to close parens */
170 regnode *end_op; /* END node in program */
171 I32 utf8; /* whether the pattern is utf8 or not */
172 I32 orig_utf8; /* whether the pattern was originally in utf8 */
173 /* XXX use this for future optimisation of case
174 * where pattern must be upgraded to utf8. */
175 I32 uni_semantics; /* If a d charset modifier should use unicode
176 rules, even if the pattern is not in
178 HV *paren_names; /* Paren names */
180 regnode **recurse; /* Recurse regops */
181 I32 recurse_count; /* Number of recurse regops we have generated */
182 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
184 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
187 I32 override_recoding;
189 I32 recode_x_to_native;
191 I32 in_multi_char_class;
192 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
194 int code_index; /* next code_blocks[] slot */
195 SSize_t maxlen; /* mininum possible number of chars in string to match */
196 scan_frame *frame_head;
197 scan_frame *frame_last;
200 #ifdef ADD_TO_REGEXEC
201 char *starttry; /* -Dr: where regtry was called. */
202 #define RExC_starttry (pRExC_state->starttry)
204 SV *runtime_code_qr; /* qr with the runtime code blocks */
206 const char *lastparse;
208 AV *paren_name_list; /* idx -> name */
209 U32 study_chunk_recursed_count;
213 #define RExC_lastparse (pRExC_state->lastparse)
214 #define RExC_lastnum (pRExC_state->lastnum)
215 #define RExC_paren_name_list (pRExC_state->paren_name_list)
216 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
217 #define RExC_mysv (pRExC_state->mysv1)
218 #define RExC_mysv1 (pRExC_state->mysv1)
219 #define RExC_mysv2 (pRExC_state->mysv2)
222 bool seen_unfolded_sharp_s;
229 #define RExC_flags (pRExC_state->flags)
230 #define RExC_pm_flags (pRExC_state->pm_flags)
231 #define RExC_precomp (pRExC_state->precomp)
232 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
233 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
234 #define RExC_precomp_end (pRExC_state->precomp_end)
235 #define RExC_rx_sv (pRExC_state->rx_sv)
236 #define RExC_rx (pRExC_state->rx)
237 #define RExC_rxi (pRExC_state->rxi)
238 #define RExC_start (pRExC_state->start)
239 #define RExC_end (pRExC_state->end)
240 #define RExC_parse (pRExC_state->parse)
241 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
242 #define RExC_whilem_seen (pRExC_state->whilem_seen)
244 /* Set during the sizing pass when there is a LATIN SMALL LETTER SHARP S in any
245 * EXACTF node, hence was parsed under /di rules. If later in the parse,
246 * something forces the pattern into using /ui rules, the sharp s should be
247 * folded into the sequence 'ss', which takes up more space than previously
248 * calculated. This means that the sizing pass needs to be restarted. (The
249 * node also becomes an EXACTFU_SS.) For all other characters, an EXACTF node
250 * that gets converted to /ui (and EXACTFU) occupies the same amount of space,
251 * so there is no need to resize [perl #125990]. */
252 #define RExC_seen_unfolded_sharp_s (pRExC_state->seen_unfolded_sharp_s)
254 #ifdef RE_TRACK_PATTERN_OFFSETS
255 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
258 #define RExC_emit (pRExC_state->emit)
259 #define RExC_emit_start (pRExC_state->emit_start)
260 #define RExC_sawback (pRExC_state->sawback)
261 #define RExC_seen (pRExC_state->seen)
262 #define RExC_size (pRExC_state->size)
263 #define RExC_maxlen (pRExC_state->maxlen)
264 #define RExC_npar (pRExC_state->npar)
265 #define RExC_total_parens (pRExC_state->total_par)
266 #define RExC_nestroot (pRExC_state->nestroot)
267 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
268 #define RExC_utf8 (pRExC_state->utf8)
269 #define RExC_uni_semantics (pRExC_state->uni_semantics)
270 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
271 #define RExC_open_parens (pRExC_state->open_parens)
272 #define RExC_close_parens (pRExC_state->close_parens)
273 #define RExC_end_op (pRExC_state->end_op)
274 #define RExC_paren_names (pRExC_state->paren_names)
275 #define RExC_recurse (pRExC_state->recurse)
276 #define RExC_recurse_count (pRExC_state->recurse_count)
277 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
278 #define RExC_study_chunk_recursed_bytes \
279 (pRExC_state->study_chunk_recursed_bytes)
280 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
281 #define RExC_contains_locale (pRExC_state->contains_locale)
283 # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
285 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
286 #define RExC_frame_head (pRExC_state->frame_head)
287 #define RExC_frame_last (pRExC_state->frame_last)
288 #define RExC_frame_count (pRExC_state->frame_count)
289 #define RExC_strict (pRExC_state->strict)
290 #define RExC_study_started (pRExC_state->study_started)
291 #define RExC_warn_text (pRExC_state->warn_text)
292 #define RExC_in_script_run (pRExC_state->in_script_run)
293 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
295 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
296 * a flag to disable back-off on the fixed/floating substrings - if it's
297 * a high complexity pattern we assume the benefit of avoiding a full match
298 * is worth the cost of checking for the substrings even if they rarely help.
300 #define RExC_naughty (pRExC_state->naughty)
301 #define TOO_NAUGHTY (10)
302 #define MARK_NAUGHTY(add) \
303 if (RExC_naughty < TOO_NAUGHTY) \
304 RExC_naughty += (add)
305 #define MARK_NAUGHTY_EXP(exp, add) \
306 if (RExC_naughty < TOO_NAUGHTY) \
307 RExC_naughty += RExC_naughty / (exp) + (add)
309 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
310 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
311 ((*s) == '{' && regcurly(s)))
314 * Flags to be passed up and down.
316 #define WORST 0 /* Worst case. */
317 #define HASWIDTH 0x01 /* Known to match non-null strings. */
319 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
320 * character. (There needs to be a case: in the switch statement in regexec.c
321 * for any node marked SIMPLE.) Note that this is not the same thing as
324 #define SPSTART 0x04 /* Starts with * or + */
325 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
326 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
327 #define RESTART_PARSE 0x20 /* Need to redo the parse */
328 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
329 calcuate sizes as UTF-8 */
331 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
333 /* whether trie related optimizations are enabled */
334 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
335 #define TRIE_STUDY_OPT
336 #define FULL_TRIE_STUDY
342 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
343 #define PBITVAL(paren) (1 << ((paren) & 7))
344 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
345 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
346 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
348 #define REQUIRE_UTF8(flagp) STMT_START { \
350 *flagp = RESTART_PARSE|NEED_UTF8; \
355 /* Change from /d into /u rules, and restart the parse if we've already seen
356 * something whose size would increase as a result, by setting *flagp and
357 * returning 'restart_retval'. RExC_uni_semantics is a flag that indicates
358 * we've changed to /u during the parse. */
359 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
361 if (DEPENDS_SEMANTICS) { \
362 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
363 RExC_uni_semantics = 1; \
364 *flagp |= RESTART_PARSE; \
365 return restart_retval; \
369 #define BRANCH_MAX_OFFSET U16_MAX
370 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
372 RExC_use_BRANCHJ = 1; \
373 *flagp |= RESTART_PARSE; \
374 return restart_retval; \
377 #define REQUIRE_PARENS_PASS \
379 if (RExC_total_parens == 0) RExC_total_parens = -1; \
382 /* Executes a return statement with the value 'X', if 'flags' contains any of
383 * 'RESTART_PARSE', 'NEED_UTF8', or 'extra'. If so, *flagp is set to those
385 #define RETURN_X_ON_RESTART_OR_FLAGS(X, flags, flagp, extra) \
387 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
388 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
393 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
394 RETURN_X_ON_RESTART_OR_FLAGS(0,flags,flagp,extra)
396 #define RETURN_X_ON_RESTART(X, flags,flagp) \
397 RETURN_X_ON_RESTART_OR_FLAGS( X, flags, flagp, 0)
400 #define RETURN_FAIL_ON_RESTART_FLAGP_OR_FLAGS(flagp,extra) \
401 if (*(flagp) & (RESTART_PARSE|(extra))) return 0
403 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
405 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
406 RETURN_X_ON_RESTART(0, flags,flagp)
407 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
408 RETURN_FAIL_ON_RESTART_FLAGP_OR_FLAGS(flagp, 0)
410 /* This converts the named class defined in regcomp.h to its equivalent class
411 * number defined in handy.h. */
412 #define namedclass_to_classnum(class) ((int) ((class) / 2))
413 #define classnum_to_namedclass(classnum) ((classnum) * 2)
415 #define _invlist_union_complement_2nd(a, b, output) \
416 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
417 #define _invlist_intersection_complement_2nd(a, b, output) \
418 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
420 /* About scan_data_t.
422 During optimisation we recurse through the regexp program performing
423 various inplace (keyhole style) optimisations. In addition study_chunk
424 and scan_commit populate this data structure with information about
425 what strings MUST appear in the pattern. We look for the longest
426 string that must appear at a fixed location, and we look for the
427 longest string that may appear at a floating location. So for instance
432 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
433 strings (because they follow a .* construct). study_chunk will identify
434 both FOO and BAR as being the longest fixed and floating strings respectively.
436 The strings can be composites, for instance
440 will result in a composite fixed substring 'foo'.
442 For each string some basic information is maintained:
445 This is the position the string must appear at, or not before.
446 It also implicitly (when combined with minlenp) tells us how many
447 characters must match before the string we are searching for.
448 Likewise when combined with minlenp and the length of the string it
449 tells us how many characters must appear after the string we have
453 Only used for floating strings. This is the rightmost point that
454 the string can appear at. If set to SSize_t_MAX it indicates that the
455 string can occur infinitely far to the right.
456 For fixed strings, it is equal to min_offset.
459 A pointer to the minimum number of characters of the pattern that the
460 string was found inside. This is important as in the case of positive
461 lookahead or positive lookbehind we can have multiple patterns
466 The minimum length of the pattern overall is 3, the minimum length
467 of the lookahead part is 3, but the minimum length of the part that
468 will actually match is 1. So 'FOO's minimum length is 3, but the
469 minimum length for the F is 1. This is important as the minimum length
470 is used to determine offsets in front of and behind the string being
471 looked for. Since strings can be composites this is the length of the
472 pattern at the time it was committed with a scan_commit. Note that
473 the length is calculated by study_chunk, so that the minimum lengths
474 are not known until the full pattern has been compiled, thus the
475 pointer to the value.
479 In the case of lookbehind the string being searched for can be
480 offset past the start point of the final matching string.
481 If this value was just blithely removed from the min_offset it would
482 invalidate some of the calculations for how many chars must match
483 before or after (as they are derived from min_offset and minlen and
484 the length of the string being searched for).
485 When the final pattern is compiled and the data is moved from the
486 scan_data_t structure into the regexp structure the information
487 about lookbehind is factored in, with the information that would
488 have been lost precalculated in the end_shift field for the
491 The fields pos_min and pos_delta are used to store the minimum offset
492 and the delta to the maximum offset at the current point in the pattern.
496 struct scan_data_substrs {
497 SV *str; /* longest substring found in pattern */
498 SSize_t min_offset; /* earliest point in string it can appear */
499 SSize_t max_offset; /* latest point in string it can appear */
500 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
501 SSize_t lookbehind; /* is the pos of the string modified by LB */
502 I32 flags; /* per substring SF_* and SCF_* flags */
505 typedef struct scan_data_t {
506 /*I32 len_min; unused */
507 /*I32 len_delta; unused */
511 SSize_t last_end; /* min value, <0 unless valid. */
512 SSize_t last_start_min;
513 SSize_t last_start_max;
514 U8 cur_is_floating; /* whether the last_* values should be set as
515 * the next fixed (0) or floating (1)
518 /* [0] is longest fixed substring so far, [1] is longest float so far */
519 struct scan_data_substrs substrs[2];
521 I32 flags; /* common SF_* and SCF_* flags */
523 SSize_t *last_closep;
524 regnode_ssc *start_class;
528 * Forward declarations for pregcomp()'s friends.
531 static const scan_data_t zero_scan_data = {
532 0, 0, NULL, 0, 0, 0, 0,
534 { NULL, 0, 0, 0, 0, 0 },
535 { NULL, 0, 0, 0, 0, 0 },
542 #define SF_BEFORE_SEOL 0x0001
543 #define SF_BEFORE_MEOL 0x0002
544 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
546 #define SF_IS_INF 0x0040
547 #define SF_HAS_PAR 0x0080
548 #define SF_IN_PAR 0x0100
549 #define SF_HAS_EVAL 0x0200
552 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
553 * longest substring in the pattern. When it is not set the optimiser keeps
554 * track of position, but does not keep track of the actual strings seen,
556 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
559 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
560 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
561 * turned off because of the alternation (BRANCH). */
562 #define SCF_DO_SUBSTR 0x0400
564 #define SCF_DO_STCLASS_AND 0x0800
565 #define SCF_DO_STCLASS_OR 0x1000
566 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
567 #define SCF_WHILEM_VISITED_POS 0x2000
569 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
570 #define SCF_SEEN_ACCEPT 0x8000
571 #define SCF_TRIE_DOING_RESTUDY 0x10000
572 #define SCF_IN_DEFINE 0x20000
577 #define UTF cBOOL(RExC_utf8)
579 /* The enums for all these are ordered so things work out correctly */
580 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
581 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
582 == REGEX_DEPENDS_CHARSET)
583 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
584 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
585 >= REGEX_UNICODE_CHARSET)
586 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
587 == REGEX_ASCII_RESTRICTED_CHARSET)
588 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
589 >= REGEX_ASCII_RESTRICTED_CHARSET)
590 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
591 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
593 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
595 /* For programs that want to be strictly Unicode compatible by dying if any
596 * attempt is made to match a non-Unicode code point against a Unicode
598 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
600 #define OOB_NAMEDCLASS -1
602 /* There is no code point that is out-of-bounds, so this is problematic. But
603 * its only current use is to initialize a variable that is always set before
605 #define OOB_UNICODE 0xDEADBEEF
607 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
610 /* length of regex to show in messages that don't mark a position within */
611 #define RegexLengthToShowInErrorMessages 127
614 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
615 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
616 * op/pragma/warn/regcomp.
618 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
619 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
621 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
622 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
624 /* The code in this file in places uses one level of recursion with parsing
625 * rebased to an alternate string constructed by us in memory. This can take
626 * the form of something that is completely different from the input, or
627 * something that uses the input as part of the alternate. In the first case,
628 * there should be no possibility of an error, as we are in complete control of
629 * the alternate string. But in the second case we don't completely control
630 * the input portion, so there may be errors in that. Here's an example:
632 * is handled specially because \x{df} folds to a sequence of more than one
633 * character: 'ss'. What is done is to create and parse an alternate string,
634 * which looks like this:
635 * /(?:\x{DF}|[abc\x{DF}def])/ui
636 * where it uses the input unchanged in the middle of something it constructs,
637 * which is a branch for the DF outside the character class, and clustering
638 * parens around the whole thing. (It knows enough to skip the DF inside the
639 * class while in this substitute parse.) 'abc' and 'def' may have errors that
640 * need to be reported. The general situation looks like this:
642 * |<------- identical ------>|
644 * Input: ---------------------------------------------------------------
645 * Constructed: ---------------------------------------------------
647 * |<------- identical ------>|
649 * sI..eI is the portion of the input pattern we are concerned with here.
650 * sC..EC is the constructed substitute parse string.
651 * sC..tC is constructed by us
652 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
653 * In the diagram, these are vertically aligned.
654 * eC..EC is also constructed by us.
655 * xC is the position in the substitute parse string where we found a
657 * xI is the position in the original pattern corresponding to xC.
659 * We want to display a message showing the real input string. Thus we need to
660 * translate from xC to xI. We know that xC >= tC, since the portion of the
661 * string sC..tC has been constructed by us, and so shouldn't have errors. We
663 * xI = tI + (xC - tC)
665 * When the substitute parse is constructed, the code needs to set:
668 * RExC_copy_start_in_input (tI)
669 * RExC_copy_start_in_constructed (tC)
670 * and restore them when done.
672 * During normal processing of the input pattern, both
673 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
674 * sI, so that xC equals xI.
677 #define sI RExC_precomp
678 #define eI RExC_precomp_end
679 #define sC RExC_start
681 #define tI RExC_copy_start_in_input
682 #define tC RExC_copy_start_in_constructed
683 #define xI(xC) (tI + (xC - tC))
684 #define xI_offset(xC) (xI(xC) - sI)
686 #define REPORT_LOCATION_ARGS(xC) \
688 (xI(xC) > eI) /* Don't run off end */ \
689 ? eI - sI /* Length before the <--HERE */ \
690 : ((xI_offset(xC) >= 0) \
692 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
693 IVdf " trying to output message for " \
695 __FILE__, __LINE__, (IV) xI_offset(xC), \
696 ((int) (eC - sC)), sC), 0)), \
697 sI), /* The input pattern printed up to the <--HERE */ \
699 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
700 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
702 /* Used to point after bad bytes for an error message, but avoid skipping
703 * past a nul byte. */
704 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
706 /* Set up to clean up after our imminent demise */
707 #define PREPARE_TO_DIE \
710 SAVEFREESV(RExC_rx_sv); \
711 if (RExC_open_parens) \
712 SAVEFREEPV(RExC_open_parens); \
713 if (RExC_close_parens) \
714 SAVEFREEPV(RExC_close_parens); \
718 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
719 * arg. Show regex, up to a maximum length. If it's too long, chop and add
722 #define _FAIL(code) STMT_START { \
723 const char *ellipses = ""; \
724 IV len = RExC_precomp_end - RExC_precomp; \
727 if (len > RegexLengthToShowInErrorMessages) { \
728 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
729 len = RegexLengthToShowInErrorMessages - 10; \
735 #define FAIL(msg) _FAIL( \
736 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
737 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
739 #define FAIL2(msg,arg) _FAIL( \
740 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
741 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
744 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
746 #define Simple_vFAIL(m) STMT_START { \
747 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
748 m, REPORT_LOCATION_ARGS(RExC_parse)); \
752 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
754 #define vFAIL(m) STMT_START { \
760 * Like Simple_vFAIL(), but accepts two arguments.
762 #define Simple_vFAIL2(m,a1) STMT_START { \
763 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
764 REPORT_LOCATION_ARGS(RExC_parse)); \
768 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
770 #define vFAIL2(m,a1) STMT_START { \
772 Simple_vFAIL2(m, a1); \
777 * Like Simple_vFAIL(), but accepts three arguments.
779 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
780 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
781 REPORT_LOCATION_ARGS(RExC_parse)); \
785 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
787 #define vFAIL3(m,a1,a2) STMT_START { \
789 Simple_vFAIL3(m, a1, a2); \
793 * Like Simple_vFAIL(), but accepts four arguments.
795 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
796 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
797 REPORT_LOCATION_ARGS(RExC_parse)); \
800 #define vFAIL4(m,a1,a2,a3) STMT_START { \
802 Simple_vFAIL4(m, a1, a2, a3); \
805 /* A specialized version of vFAIL2 that works with UTF8f */
806 #define vFAIL2utf8f(m, a1) STMT_START { \
808 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
809 REPORT_LOCATION_ARGS(RExC_parse)); \
812 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
814 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
815 REPORT_LOCATION_ARGS(RExC_parse)); \
818 /* Setting this to NULL is a signal to not output warnings */
819 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
820 #define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
822 /* Since a warning can be generated multiple times as the input is reparsed, we
823 * output it the first time we come to that point in the parse, but suppress it
824 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
825 * generate any warnings */
826 #define TO_OUTPUT_WARNINGS(loc) \
827 ( RExC_copy_start_in_constructed \
828 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
830 /* After we've emitted a warning, we save the position in the input so we don't
832 #define UPDATE_WARNINGS_LOC(loc) \
834 if (TO_OUTPUT_WARNINGS(loc)) { \
835 RExC_latest_warn_offset = (xI(loc)) - RExC_precomp; \
839 /* 'warns' is the output of the packWARNx macro used in 'code' */
840 #define _WARN_HELPER(loc, warns, code) \
842 if (! RExC_copy_start_in_constructed) { \
843 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
844 " expected at '%s'", \
845 __FILE__, __LINE__, loc); \
847 if (TO_OUTPUT_WARNINGS(loc)) { \
851 UPDATE_WARNINGS_LOC(loc); \
855 /* m is not necessarily a "literal string", in this macro */
856 #define reg_warn_non_literal_string(loc, m) \
857 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
858 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
859 "%s" REPORT_LOCATION, \
860 m, REPORT_LOCATION_ARGS(loc)))
862 #define ckWARNreg(loc,m) \
863 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
864 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
866 REPORT_LOCATION_ARGS(loc)))
868 #define vWARN(loc, m) \
869 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
870 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
872 REPORT_LOCATION_ARGS(loc))) \
874 #define vWARN_dep(loc, m) \
875 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
876 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
878 REPORT_LOCATION_ARGS(loc)))
880 #define ckWARNdep(loc,m) \
881 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
882 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
884 REPORT_LOCATION_ARGS(loc)))
886 #define ckWARNregdep(loc,m) \
887 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
888 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
891 REPORT_LOCATION_ARGS(loc)))
893 #define ckWARN2reg_d(loc,m, a1) \
894 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
895 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
897 a1, REPORT_LOCATION_ARGS(loc)))
899 #define ckWARN2reg(loc, m, a1) \
900 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
901 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
903 a1, REPORT_LOCATION_ARGS(loc)))
905 #define vWARN3(loc, m, a1, a2) \
906 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
907 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
909 a1, a2, REPORT_LOCATION_ARGS(loc)))
911 #define ckWARN3reg(loc, m, a1, a2) \
912 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
913 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
916 REPORT_LOCATION_ARGS(loc)))
918 #define vWARN4(loc, m, a1, a2, a3) \
919 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
920 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
923 REPORT_LOCATION_ARGS(loc)))
925 #define ckWARN4reg(loc, m, a1, a2, a3) \
926 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
927 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
930 REPORT_LOCATION_ARGS(loc)))
932 #define vWARN5(loc, m, a1, a2, a3, a4) \
933 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
934 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
937 REPORT_LOCATION_ARGS(loc)))
939 #define ckWARNexperimental(loc, class, m) \
940 _WARN_HELPER(loc, packWARN(class), \
941 Perl_ck_warner_d(aTHX_ packWARN(class), \
943 REPORT_LOCATION_ARGS(loc)))
945 /* Convert between a pointer to a node and its offset from the beginning of the
947 #define REGNODE_p(offset) (RExC_emit_start + (offset))
948 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
950 /* Macros for recording node offsets. 20001227 mjd@plover.com
951 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
952 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
953 * Element 0 holds the number n.
954 * Position is 1 indexed.
956 #ifndef RE_TRACK_PATTERN_OFFSETS
957 #define Set_Node_Offset_To_R(offset,byte)
958 #define Set_Node_Offset(node,byte)
959 #define Set_Cur_Node_Offset
960 #define Set_Node_Length_To_R(node,len)
961 #define Set_Node_Length(node,len)
962 #define Set_Node_Cur_Length(node,start)
963 #define Node_Offset(n)
964 #define Node_Length(n)
965 #define Set_Node_Offset_Length(node,offset,len)
966 #define ProgLen(ri) ri->u.proglen
967 #define SetProgLen(ri,x) ri->u.proglen = x
968 #define Track_Code(code)
970 #define ProgLen(ri) ri->u.offsets[0]
971 #define SetProgLen(ri,x) ri->u.offsets[0] = x
972 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
973 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
974 __LINE__, (int)(offset), (int)(byte))); \
976 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
979 RExC_offsets[2*(offset)-1] = (byte); \
983 #define Set_Node_Offset(node,byte) \
984 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
985 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
987 #define Set_Node_Length_To_R(node,len) STMT_START { \
988 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
989 __LINE__, (int)(node), (int)(len))); \
991 Perl_croak(aTHX_ "value of node is %d in Length macro", \
994 RExC_offsets[2*(node)] = (len); \
998 #define Set_Node_Length(node,len) \
999 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1000 #define Set_Node_Cur_Length(node, start) \
1001 Set_Node_Length(node, RExC_parse - start)
1003 /* Get offsets and lengths */
1004 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1005 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1007 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1008 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1009 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1012 #define Track_Code(code) STMT_START { code } STMT_END
1015 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1016 #define EXPERIMENTAL_INPLACESCAN
1017 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1021 Perl_re_printf(pTHX_ const char *fmt, ...)
1025 PerlIO *f= Perl_debug_log;
1026 PERL_ARGS_ASSERT_RE_PRINTF;
1028 result = PerlIO_vprintf(f, fmt, ap);
1034 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1038 PerlIO *f= Perl_debug_log;
1039 PERL_ARGS_ASSERT_RE_INDENTF;
1040 va_start(ap, depth);
1041 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1042 result = PerlIO_vprintf(f, fmt, ap);
1046 #endif /* DEBUGGING */
1048 #define DEBUG_RExC_seen() \
1049 DEBUG_OPTIMISE_MORE_r({ \
1050 Perl_re_printf( aTHX_ "RExC_seen: "); \
1052 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1053 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1055 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1056 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1058 if (RExC_seen & REG_GPOS_SEEN) \
1059 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1061 if (RExC_seen & REG_RECURSE_SEEN) \
1062 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1064 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1065 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1067 if (RExC_seen & REG_VERBARG_SEEN) \
1068 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1070 if (RExC_seen & REG_CUTGROUP_SEEN) \
1071 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1073 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1074 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1076 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1077 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1079 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1080 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1082 Perl_re_printf( aTHX_ "\n"); \
1085 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1086 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1091 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1092 const char *close_str)
1097 Perl_re_printf( aTHX_ "%s", open_str);
1098 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1099 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1100 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1101 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1102 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1103 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1104 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1105 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1106 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1107 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1108 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1109 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1110 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1111 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1112 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1113 Perl_re_printf( aTHX_ "%s", close_str);
1118 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1119 U32 depth, int is_inf)
1121 GET_RE_DEBUG_FLAGS_DECL;
1123 DEBUG_OPTIMISE_MORE_r({
1126 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1130 (IV)data->pos_delta,
1134 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1136 Perl_re_printf( aTHX_
1137 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1139 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1140 is_inf ? "INF " : ""
1143 if (data->last_found) {
1145 Perl_re_printf(aTHX_
1146 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1147 SvPVX_const(data->last_found),
1149 (IV)data->last_start_min,
1150 (IV)data->last_start_max
1153 for (i = 0; i < 2; i++) {
1154 Perl_re_printf(aTHX_
1155 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1156 data->cur_is_floating == i ? "*" : "",
1157 i ? "Float" : "Fixed",
1158 SvPVX_const(data->substrs[i].str),
1159 (IV)data->substrs[i].min_offset,
1160 (IV)data->substrs[i].max_offset
1162 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1166 Perl_re_printf( aTHX_ "\n");
1172 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1173 regnode *scan, U32 depth, U32 flags)
1175 GET_RE_DEBUG_FLAGS_DECL;
1182 Next = regnext(scan);
1183 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1184 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1187 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1188 Next ? (REG_NODE_NUM(Next)) : 0 );
1189 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1190 Perl_re_printf( aTHX_ "\n");
1195 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1196 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1198 # define DEBUG_PEEP(str, scan, depth, flags) \
1199 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1202 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1203 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1207 /* =========================================================
1208 * BEGIN edit_distance stuff.
1210 * This calculates how many single character changes of any type are needed to
1211 * transform a string into another one. It is taken from version 3.1 of
1213 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1216 /* Our unsorted dictionary linked list. */
1217 /* Note we use UVs, not chars. */
1222 struct dictionary* next;
1224 typedef struct dictionary item;
1227 PERL_STATIC_INLINE item*
1228 push(UV key, item* curr)
1231 Newx(head, 1, item);
1239 PERL_STATIC_INLINE item*
1240 find(item* head, UV key)
1242 item* iterator = head;
1244 if (iterator->key == key){
1247 iterator = iterator->next;
1253 PERL_STATIC_INLINE item*
1254 uniquePush(item* head, UV key)
1256 item* iterator = head;
1259 if (iterator->key == key) {
1262 iterator = iterator->next;
1265 return push(key, head);
1268 PERL_STATIC_INLINE void
1269 dict_free(item* head)
1271 item* iterator = head;
1274 item* temp = iterator;
1275 iterator = iterator->next;
1282 /* End of Dictionary Stuff */
1284 /* All calculations/work are done here */
1286 S_edit_distance(const UV* src,
1288 const STRLEN x, /* length of src[] */
1289 const STRLEN y, /* length of tgt[] */
1290 const SSize_t maxDistance
1294 UV swapCount, swapScore, targetCharCount, i, j;
1296 UV score_ceil = x + y;
1298 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1300 /* intialize matrix start values */
1301 Newx(scores, ( (x + 2) * (y + 2)), UV);
1302 scores[0] = score_ceil;
1303 scores[1 * (y + 2) + 0] = score_ceil;
1304 scores[0 * (y + 2) + 1] = score_ceil;
1305 scores[1 * (y + 2) + 1] = 0;
1306 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1311 for (i=1;i<=x;i++) {
1313 head = uniquePush(head, src[i]);
1314 scores[(i+1) * (y + 2) + 1] = i;
1315 scores[(i+1) * (y + 2) + 0] = score_ceil;
1318 for (j=1;j<=y;j++) {
1321 head = uniquePush(head, tgt[j]);
1322 scores[1 * (y + 2) + (j + 1)] = j;
1323 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1326 targetCharCount = find(head, tgt[j-1])->value;
1327 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1329 if (src[i-1] != tgt[j-1]){
1330 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));
1334 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1338 find(head, src[i-1])->value = i;
1342 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1345 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1349 /* END of edit_distance() stuff
1350 * ========================================================= */
1352 /* is c a control character for which we have a mnemonic? */
1353 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1356 S_cntrl_to_mnemonic(const U8 c)
1358 /* Returns the mnemonic string that represents character 'c', if one
1359 * exists; NULL otherwise. The only ones that exist for the purposes of
1360 * this routine are a few control characters */
1363 case '\a': return "\\a";
1364 case '\b': return "\\b";
1365 case ESC_NATIVE: return "\\e";
1366 case '\f': return "\\f";
1367 case '\n': return "\\n";
1368 case '\r': return "\\r";
1369 case '\t': return "\\t";
1375 /* Mark that we cannot extend a found fixed substring at this point.
1376 Update the longest found anchored substring or the longest found
1377 floating substrings if needed. */
1380 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1381 SSize_t *minlenp, int is_inf)
1383 const STRLEN l = CHR_SVLEN(data->last_found);
1384 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1385 const STRLEN old_l = CHR_SVLEN(longest_sv);
1386 GET_RE_DEBUG_FLAGS_DECL;
1388 PERL_ARGS_ASSERT_SCAN_COMMIT;
1390 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1391 const U8 i = data->cur_is_floating;
1392 SvSetMagicSV(longest_sv, data->last_found);
1393 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1396 data->substrs[0].max_offset = data->substrs[0].min_offset;
1398 data->substrs[1].max_offset = (l
1399 ? data->last_start_max
1400 : (data->pos_delta > SSize_t_MAX - data->pos_min
1402 : data->pos_min + data->pos_delta));
1404 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1405 data->substrs[1].max_offset = SSize_t_MAX;
1408 if (data->flags & SF_BEFORE_EOL)
1409 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1411 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1412 data->substrs[i].minlenp = minlenp;
1413 data->substrs[i].lookbehind = 0;
1416 SvCUR_set(data->last_found, 0);
1418 SV * const sv = data->last_found;
1419 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1420 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1425 data->last_end = -1;
1426 data->flags &= ~SF_BEFORE_EOL;
1427 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1430 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1431 * list that describes which code points it matches */
1434 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1436 /* Set the SSC 'ssc' to match an empty string or any code point */
1438 PERL_ARGS_ASSERT_SSC_ANYTHING;
1440 assert(is_ANYOF_SYNTHETIC(ssc));
1442 /* mortalize so won't leak */
1443 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1444 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1448 S_ssc_is_anything(const regnode_ssc *ssc)
1450 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1451 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1452 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1453 * in any way, so there's no point in using it */
1458 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1460 assert(is_ANYOF_SYNTHETIC(ssc));
1462 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1466 /* See if the list consists solely of the range 0 - Infinity */
1467 invlist_iterinit(ssc->invlist);
1468 ret = invlist_iternext(ssc->invlist, &start, &end)
1472 invlist_iterfinish(ssc->invlist);
1478 /* If e.g., both \w and \W are set, matches everything */
1479 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1481 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1482 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1492 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1494 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1495 * string, any code point, or any posix class under locale */
1497 PERL_ARGS_ASSERT_SSC_INIT;
1499 Zero(ssc, 1, regnode_ssc);
1500 set_ANYOF_SYNTHETIC(ssc);
1501 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1504 /* If any portion of the regex is to operate under locale rules that aren't
1505 * fully known at compile time, initialization includes it. The reason
1506 * this isn't done for all regexes is that the optimizer was written under
1507 * the assumption that locale was all-or-nothing. Given the complexity and
1508 * lack of documentation in the optimizer, and that there are inadequate
1509 * test cases for locale, many parts of it may not work properly, it is
1510 * safest to avoid locale unless necessary. */
1511 if (RExC_contains_locale) {
1512 ANYOF_POSIXL_SETALL(ssc);
1515 ANYOF_POSIXL_ZERO(ssc);
1520 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1521 const regnode_ssc *ssc)
1523 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1524 * to the list of code points matched, and locale posix classes; hence does
1525 * not check its flags) */
1530 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1532 assert(is_ANYOF_SYNTHETIC(ssc));
1534 invlist_iterinit(ssc->invlist);
1535 ret = invlist_iternext(ssc->invlist, &start, &end)
1539 invlist_iterfinish(ssc->invlist);
1545 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1553 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1554 const regnode_charclass* const node)
1556 /* Returns a mortal inversion list defining which code points are matched
1557 * by 'node', which is of type ANYOF. Handles complementing the result if
1558 * appropriate. If some code points aren't knowable at this time, the
1559 * returned list must, and will, contain every code point that is a
1563 SV* only_utf8_locale_invlist = NULL;
1565 const U32 n = ARG(node);
1566 bool new_node_has_latin1 = FALSE;
1568 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1570 /* Look at the data structure created by S_set_ANYOF_arg() */
1571 if (n != ANYOF_ONLY_HAS_BITMAP) {
1572 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1573 AV * const av = MUTABLE_AV(SvRV(rv));
1574 SV **const ary = AvARRAY(av);
1575 assert(RExC_rxi->data->what[n] == 's');
1577 if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1578 invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1]), NULL));
1580 else if (ary[0] && ary[0] != &PL_sv_undef) {
1582 /* Here, no compile-time swash, and there are things that won't be
1583 * known until runtime -- we have to assume it could be anything */
1584 invlist = sv_2mortal(_new_invlist(1));
1585 return _add_range_to_invlist(invlist, 0, UV_MAX);
1587 else if (ary[3] && ary[3] != &PL_sv_undef) {
1589 /* Here no compile-time swash, and no run-time only data. Use the
1590 * node's inversion list */
1591 invlist = sv_2mortal(invlist_clone(ary[3], NULL));
1594 /* Get the code points valid only under UTF-8 locales */
1595 if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1596 && ary[2] && ary[2] != &PL_sv_undef)
1598 only_utf8_locale_invlist = ary[2];
1603 invlist = sv_2mortal(_new_invlist(0));
1606 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1607 * code points, and an inversion list for the others, but if there are code
1608 * points that should match only conditionally on the target string being
1609 * UTF-8, those are placed in the inversion list, and not the bitmap.
1610 * Since there are circumstances under which they could match, they are
1611 * included in the SSC. But if the ANYOF node is to be inverted, we have
1612 * to exclude them here, so that when we invert below, the end result
1613 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1614 * have to do this here before we add the unconditionally matched code
1616 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1617 _invlist_intersection_complement_2nd(invlist,
1622 /* Add in the points from the bit map */
1623 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1624 if (ANYOF_BITMAP_TEST(node, i)) {
1625 unsigned int start = i++;
1627 for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) {
1630 invlist = _add_range_to_invlist(invlist, start, i-1);
1631 new_node_has_latin1 = TRUE;
1635 /* If this can match all upper Latin1 code points, have to add them
1636 * as well. But don't add them if inverting, as when that gets done below,
1637 * it would exclude all these characters, including the ones it shouldn't
1638 * that were added just above */
1639 if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1640 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1642 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1645 /* Similarly for these */
1646 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1647 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1650 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1651 _invlist_invert(invlist);
1653 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1655 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1656 * locale. We can skip this if there are no 0-255 at all. */
1657 _invlist_union(invlist, PL_Latin1, &invlist);
1660 /* Similarly add the UTF-8 locale possible matches. These have to be
1661 * deferred until after the non-UTF-8 locale ones are taken care of just
1662 * above, or it leads to wrong results under ANYOF_INVERT */
1663 if (only_utf8_locale_invlist) {
1664 _invlist_union_maybe_complement_2nd(invlist,
1665 only_utf8_locale_invlist,
1666 ANYOF_FLAGS(node) & ANYOF_INVERT,
1673 /* These two functions currently do the exact same thing */
1674 #define ssc_init_zero ssc_init
1676 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1677 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1679 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1680 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1681 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1684 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1685 const regnode_charclass *and_with)
1687 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1688 * another SSC or a regular ANYOF class. Can create false positives. */
1693 PERL_ARGS_ASSERT_SSC_AND;
1695 assert(is_ANYOF_SYNTHETIC(ssc));
1697 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1698 * the code point inversion list and just the relevant flags */
1699 if (is_ANYOF_SYNTHETIC(and_with)) {
1700 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1701 anded_flags = ANYOF_FLAGS(and_with);
1703 /* XXX This is a kludge around what appears to be deficiencies in the
1704 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1705 * there are paths through the optimizer where it doesn't get weeded
1706 * out when it should. And if we don't make some extra provision for
1707 * it like the code just below, it doesn't get added when it should.
1708 * This solution is to add it only when AND'ing, which is here, and
1709 * only when what is being AND'ed is the pristine, original node
1710 * matching anything. Thus it is like adding it to ssc_anything() but
1711 * only when the result is to be AND'ed. Probably the same solution
1712 * could be adopted for the same problem we have with /l matching,
1713 * which is solved differently in S_ssc_init(), and that would lead to
1714 * fewer false positives than that solution has. But if this solution
1715 * creates bugs, the consequences are only that a warning isn't raised
1716 * that should be; while the consequences for having /l bugs is
1717 * incorrect matches */
1718 if (ssc_is_anything((regnode_ssc *)and_with)) {
1719 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1723 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1724 if (OP(and_with) == ANYOFD) {
1725 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1728 anded_flags = ANYOF_FLAGS(and_with)
1729 &( ANYOF_COMMON_FLAGS
1730 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1731 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1732 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1734 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1739 ANYOF_FLAGS(ssc) &= anded_flags;
1741 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1742 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1743 * 'and_with' may be inverted. When not inverted, we have the situation of
1745 * (C1 | P1) & (C2 | P2)
1746 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1747 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1748 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1749 * <= ((C1 & C2) | P1 | P2)
1750 * Alternatively, the last few steps could be:
1751 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1752 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1753 * <= (C1 | C2 | (P1 & P2))
1754 * We favor the second approach if either P1 or P2 is non-empty. This is
1755 * because these components are a barrier to doing optimizations, as what
1756 * they match cannot be known until the moment of matching as they are
1757 * dependent on the current locale, 'AND"ing them likely will reduce or
1759 * But we can do better if we know that C1,P1 are in their initial state (a
1760 * frequent occurrence), each matching everything:
1761 * (<everything>) & (C2 | P2) = C2 | P2
1762 * Similarly, if C2,P2 are in their initial state (again a frequent
1763 * occurrence), the result is a no-op
1764 * (C1 | P1) & (<everything>) = C1 | P1
1767 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1768 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1769 * <= (C1 & ~C2) | (P1 & ~P2)
1772 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1773 && ! is_ANYOF_SYNTHETIC(and_with))
1777 ssc_intersection(ssc,
1779 FALSE /* Has already been inverted */
1782 /* If either P1 or P2 is empty, the intersection will be also; can skip
1784 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1785 ANYOF_POSIXL_ZERO(ssc);
1787 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1789 /* Note that the Posix class component P from 'and_with' actually
1791 * P = Pa | Pb | ... | Pn
1792 * where each component is one posix class, such as in [\w\s].
1794 * ~P = ~(Pa | Pb | ... | Pn)
1795 * = ~Pa & ~Pb & ... & ~Pn
1796 * <= ~Pa | ~Pb | ... | ~Pn
1797 * The last is something we can easily calculate, but unfortunately
1798 * is likely to have many false positives. We could do better
1799 * in some (but certainly not all) instances if two classes in
1800 * P have known relationships. For example
1801 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1803 * :lower: & :print: = :lower:
1804 * And similarly for classes that must be disjoint. For example,
1805 * since \s and \w can have no elements in common based on rules in
1806 * the POSIX standard,
1807 * \w & ^\S = nothing
1808 * Unfortunately, some vendor locales do not meet the Posix
1809 * standard, in particular almost everything by Microsoft.
1810 * The loop below just changes e.g., \w into \W and vice versa */
1812 regnode_charclass_posixl temp;
1813 int add = 1; /* To calculate the index of the complement */
1815 Zero(&temp, 1, regnode_charclass_posixl);
1816 ANYOF_POSIXL_ZERO(&temp);
1817 for (i = 0; i < ANYOF_MAX; i++) {
1819 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1820 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1822 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1823 ANYOF_POSIXL_SET(&temp, i + add);
1825 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1827 ANYOF_POSIXL_AND(&temp, ssc);
1829 } /* else ssc already has no posixes */
1830 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1831 in its initial state */
1832 else if (! is_ANYOF_SYNTHETIC(and_with)
1833 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1835 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1836 * copy it over 'ssc' */
1837 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1838 if (is_ANYOF_SYNTHETIC(and_with)) {
1839 StructCopy(and_with, ssc, regnode_ssc);
1842 ssc->invlist = anded_cp_list;
1843 ANYOF_POSIXL_ZERO(ssc);
1844 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1845 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1849 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1850 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1852 /* One or the other of P1, P2 is non-empty. */
1853 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1854 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1856 ssc_union(ssc, anded_cp_list, FALSE);
1858 else { /* P1 = P2 = empty */
1859 ssc_intersection(ssc, anded_cp_list, FALSE);
1865 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1866 const regnode_charclass *or_with)
1868 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1869 * another SSC or a regular ANYOF class. Can create false positives if
1870 * 'or_with' is to be inverted. */
1875 PERL_ARGS_ASSERT_SSC_OR;
1877 assert(is_ANYOF_SYNTHETIC(ssc));
1879 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1880 * the code point inversion list and just the relevant flags */
1881 if (is_ANYOF_SYNTHETIC(or_with)) {
1882 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1883 ored_flags = ANYOF_FLAGS(or_with);
1886 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1887 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1888 if (OP(or_with) != ANYOFD) {
1890 |= ANYOF_FLAGS(or_with)
1891 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1892 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1893 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1895 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1900 ANYOF_FLAGS(ssc) |= ored_flags;
1902 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1903 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1904 * 'or_with' may be inverted. When not inverted, we have the simple
1905 * situation of computing:
1906 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1907 * If P1|P2 yields a situation with both a class and its complement are
1908 * set, like having both \w and \W, this matches all code points, and we
1909 * can delete these from the P component of the ssc going forward. XXX We
1910 * might be able to delete all the P components, but I (khw) am not certain
1911 * about this, and it is better to be safe.
1914 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1915 * <= (C1 | P1) | ~C2
1916 * <= (C1 | ~C2) | P1
1917 * (which results in actually simpler code than the non-inverted case)
1920 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1921 && ! is_ANYOF_SYNTHETIC(or_with))
1923 /* We ignore P2, leaving P1 going forward */
1924 } /* else Not inverted */
1925 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1926 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1927 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1929 for (i = 0; i < ANYOF_MAX; i += 2) {
1930 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1932 ssc_match_all_cp(ssc);
1933 ANYOF_POSIXL_CLEAR(ssc, i);
1934 ANYOF_POSIXL_CLEAR(ssc, i+1);
1942 FALSE /* Already has been inverted */
1946 PERL_STATIC_INLINE void
1947 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1949 PERL_ARGS_ASSERT_SSC_UNION;
1951 assert(is_ANYOF_SYNTHETIC(ssc));
1953 _invlist_union_maybe_complement_2nd(ssc->invlist,
1959 PERL_STATIC_INLINE void
1960 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1962 const bool invert2nd)
1964 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1966 assert(is_ANYOF_SYNTHETIC(ssc));
1968 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1974 PERL_STATIC_INLINE void
1975 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1977 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1979 assert(is_ANYOF_SYNTHETIC(ssc));
1981 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1984 PERL_STATIC_INLINE void
1985 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1987 /* AND just the single code point 'cp' into the SSC 'ssc' */
1989 SV* cp_list = _new_invlist(2);
1991 PERL_ARGS_ASSERT_SSC_CP_AND;
1993 assert(is_ANYOF_SYNTHETIC(ssc));
1995 cp_list = add_cp_to_invlist(cp_list, cp);
1996 ssc_intersection(ssc, cp_list,
1997 FALSE /* Not inverted */
1999 SvREFCNT_dec_NN(cp_list);
2002 PERL_STATIC_INLINE void
2003 S_ssc_clear_locale(regnode_ssc *ssc)
2005 /* Set the SSC 'ssc' to not match any locale things */
2006 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2008 assert(is_ANYOF_SYNTHETIC(ssc));
2010 ANYOF_POSIXL_ZERO(ssc);
2011 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2014 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2017 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2019 /* The synthetic start class is used to hopefully quickly winnow down
2020 * places where a pattern could start a match in the target string. If it
2021 * doesn't really narrow things down that much, there isn't much point to
2022 * having the overhead of using it. This function uses some very crude
2023 * heuristics to decide if to use the ssc or not.
2025 * It returns TRUE if 'ssc' rules out more than half what it considers to
2026 * be the "likely" possible matches, but of course it doesn't know what the
2027 * actual things being matched are going to be; these are only guesses
2029 * For /l matches, it assumes that the only likely matches are going to be
2030 * in the 0-255 range, uniformly distributed, so half of that is 127
2031 * For /a and /d matches, it assumes that the likely matches will be just
2032 * the ASCII range, so half of that is 63
2033 * For /u and there isn't anything matching above the Latin1 range, it
2034 * assumes that that is the only range likely to be matched, and uses
2035 * half that as the cut-off: 127. If anything matches above Latin1,
2036 * it assumes that all of Unicode could match (uniformly), except for
2037 * non-Unicode code points and things in the General Category "Other"
2038 * (unassigned, private use, surrogates, controls and formats). This
2039 * is a much large number. */
2041 U32 count = 0; /* Running total of number of code points matched by
2043 UV start, end; /* Start and end points of current range in inversion
2045 const U32 max_code_points = (LOC)
2047 : (( ! UNI_SEMANTICS
2048 || invlist_highest(ssc->invlist) < 256)
2051 const U32 max_match = max_code_points / 2;
2053 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2055 invlist_iterinit(ssc->invlist);
2056 while (invlist_iternext(ssc->invlist, &start, &end)) {
2057 if (start >= max_code_points) {
2060 end = MIN(end, max_code_points - 1);
2061 count += end - start + 1;
2062 if (count >= max_match) {
2063 invlist_iterfinish(ssc->invlist);
2073 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2075 /* The inversion list in the SSC is marked mortal; now we need a more
2076 * permanent copy, which is stored the same way that is done in a regular
2077 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2080 SV* invlist = invlist_clone(ssc->invlist, NULL);
2082 PERL_ARGS_ASSERT_SSC_FINALIZE;
2084 assert(is_ANYOF_SYNTHETIC(ssc));
2086 /* The code in this file assumes that all but these flags aren't relevant
2087 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2088 * by the time we reach here */
2089 assert(! (ANYOF_FLAGS(ssc)
2090 & ~( ANYOF_COMMON_FLAGS
2091 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2092 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2094 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2096 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
2097 NULL, NULL, NULL, FALSE);
2099 /* Make sure is clone-safe */
2100 ssc->invlist = NULL;
2102 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2103 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2104 OP(ssc) = ANYOFPOSIXL;
2106 else if (RExC_contains_locale) {
2110 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2113 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2114 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2115 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2116 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2117 ? (TRIE_LIST_CUR( idx ) - 1) \
2123 dump_trie(trie,widecharmap,revcharmap)
2124 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2125 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2127 These routines dump out a trie in a somewhat readable format.
2128 The _interim_ variants are used for debugging the interim
2129 tables that are used to generate the final compressed
2130 representation which is what dump_trie expects.
2132 Part of the reason for their existence is to provide a form
2133 of documentation as to how the different representations function.
2138 Dumps the final compressed table form of the trie to Perl_debug_log.
2139 Used for debugging make_trie().
2143 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2144 AV *revcharmap, U32 depth)
2147 SV *sv=sv_newmortal();
2148 int colwidth= widecharmap ? 6 : 4;
2150 GET_RE_DEBUG_FLAGS_DECL;
2152 PERL_ARGS_ASSERT_DUMP_TRIE;
2154 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2155 depth+1, "Match","Base","Ofs" );
2157 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2158 SV ** const tmp = av_fetch( revcharmap, state, 0);
2160 Perl_re_printf( aTHX_ "%*s",
2162 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2163 PL_colors[0], PL_colors[1],
2164 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2165 PERL_PV_ESCAPE_FIRSTCHAR
2170 Perl_re_printf( aTHX_ "\n");
2171 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2173 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2174 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2175 Perl_re_printf( aTHX_ "\n");
2177 for( state = 1 ; state < trie->statecount ; state++ ) {
2178 const U32 base = trie->states[ state ].trans.base;
2180 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2182 if ( trie->states[ state ].wordnum ) {
2183 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2185 Perl_re_printf( aTHX_ "%6s", "" );
2188 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2193 while( ( base + ofs < trie->uniquecharcount ) ||
2194 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2195 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2199 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2201 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2202 if ( ( base + ofs >= trie->uniquecharcount )
2203 && ( base + ofs - trie->uniquecharcount
2205 && trie->trans[ base + ofs
2206 - trie->uniquecharcount ].check == state )
2208 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2209 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2212 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2216 Perl_re_printf( aTHX_ "]");
2219 Perl_re_printf( aTHX_ "\n" );
2221 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2223 for (word=1; word <= trie->wordcount; word++) {
2224 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2225 (int)word, (int)(trie->wordinfo[word].prev),
2226 (int)(trie->wordinfo[word].len));
2228 Perl_re_printf( aTHX_ "\n" );
2231 Dumps a fully constructed but uncompressed trie in list form.
2232 List tries normally only are used for construction when the number of
2233 possible chars (trie->uniquecharcount) is very high.
2234 Used for debugging make_trie().
2237 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2238 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2242 SV *sv=sv_newmortal();
2243 int colwidth= widecharmap ? 6 : 4;
2244 GET_RE_DEBUG_FLAGS_DECL;
2246 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2248 /* print out the table precompression. */
2249 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2251 Perl_re_indentf( aTHX_ "%s",
2252 depth+1, "------:-----+-----------------\n" );
2254 for( state=1 ; state < next_alloc ; state ++ ) {
2257 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2258 depth+1, (UV)state );
2259 if ( ! trie->states[ state ].wordnum ) {
2260 Perl_re_printf( aTHX_ "%5s| ","");
2262 Perl_re_printf( aTHX_ "W%4x| ",
2263 trie->states[ state ].wordnum
2266 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2267 SV ** const tmp = av_fetch( revcharmap,
2268 TRIE_LIST_ITEM(state, charid).forid, 0);
2270 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2272 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2274 PL_colors[0], PL_colors[1],
2275 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2276 | PERL_PV_ESCAPE_FIRSTCHAR
2278 TRIE_LIST_ITEM(state, charid).forid,
2279 (UV)TRIE_LIST_ITEM(state, charid).newstate
2282 Perl_re_printf( aTHX_ "\n%*s| ",
2283 (int)((depth * 2) + 14), "");
2286 Perl_re_printf( aTHX_ "\n");
2291 Dumps a fully constructed but uncompressed trie in table form.
2292 This is the normal DFA style state transition table, with a few
2293 twists to facilitate compression later.
2294 Used for debugging make_trie().
2297 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2298 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2303 SV *sv=sv_newmortal();
2304 int colwidth= widecharmap ? 6 : 4;
2305 GET_RE_DEBUG_FLAGS_DECL;
2307 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2310 print out the table precompression so that we can do a visual check
2311 that they are identical.
2314 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2316 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2317 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2319 Perl_re_printf( aTHX_ "%*s",
2321 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2322 PL_colors[0], PL_colors[1],
2323 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2324 PERL_PV_ESCAPE_FIRSTCHAR
2330 Perl_re_printf( aTHX_ "\n");
2331 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2333 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2334 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2337 Perl_re_printf( aTHX_ "\n" );
2339 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2341 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2343 (UV)TRIE_NODENUM( state ) );
2345 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2346 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2348 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2350 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2352 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2353 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2354 (UV)trie->trans[ state ].check );
2356 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2357 (UV)trie->trans[ state ].check,
2358 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2366 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2367 startbranch: the first branch in the whole branch sequence
2368 first : start branch of sequence of branch-exact nodes.
2369 May be the same as startbranch
2370 last : Thing following the last branch.
2371 May be the same as tail.
2372 tail : item following the branch sequence
2373 count : words in the sequence
2374 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2375 depth : indent depth
2377 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2379 A trie is an N'ary tree where the branches are determined by digital
2380 decomposition of the key. IE, at the root node you look up the 1st character and
2381 follow that branch repeat until you find the end of the branches. Nodes can be
2382 marked as "accepting" meaning they represent a complete word. Eg:
2386 would convert into the following structure. Numbers represent states, letters
2387 following numbers represent valid transitions on the letter from that state, if
2388 the number is in square brackets it represents an accepting state, otherwise it
2389 will be in parenthesis.
2391 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2395 (1) +-i->(6)-+-s->[7]
2397 +-s->(3)-+-h->(4)-+-e->[5]
2399 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2401 This shows that when matching against the string 'hers' we will begin at state 1
2402 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2403 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2404 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2405 single traverse. We store a mapping from accepting to state to which word was
2406 matched, and then when we have multiple possibilities we try to complete the
2407 rest of the regex in the order in which they occurred in the alternation.
2409 The only prior NFA like behaviour that would be changed by the TRIE support is
2410 the silent ignoring of duplicate alternations which are of the form:
2412 / (DUPE|DUPE) X? (?{ ... }) Y /x
2414 Thus EVAL blocks following a trie may be called a different number of times with
2415 and without the optimisation. With the optimisations dupes will be silently
2416 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2417 the following demonstrates:
2419 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2421 which prints out 'word' three times, but
2423 'words'=~/(word|word|word)(?{ print $1 })S/
2425 which doesnt print it out at all. This is due to other optimisations kicking in.
2427 Example of what happens on a structural level:
2429 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2431 1: CURLYM[1] {1,32767}(18)
2442 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2443 and should turn into:
2445 1: CURLYM[1] {1,32767}(18)
2447 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2455 Cases where tail != last would be like /(?foo|bar)baz/:
2465 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2466 and would end up looking like:
2469 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2476 d = uvchr_to_utf8_flags(d, uv, 0);
2478 is the recommended Unicode-aware way of saying
2483 #define TRIE_STORE_REVCHAR(val) \
2486 SV *zlopp = newSV(UTF8_MAXBYTES); \
2487 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2488 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2489 SvCUR_set(zlopp, kapow - flrbbbbb); \
2492 av_push(revcharmap, zlopp); \
2494 char ooooff = (char)val; \
2495 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2499 /* This gets the next character from the input, folding it if not already
2501 #define TRIE_READ_CHAR STMT_START { \
2504 /* if it is UTF then it is either already folded, or does not need \
2506 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2508 else if (folder == PL_fold_latin1) { \
2509 /* This folder implies Unicode rules, which in the range expressible \
2510 * by not UTF is the lower case, with the two exceptions, one of \
2511 * which should have been taken care of before calling this */ \
2512 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2513 uvc = toLOWER_L1(*uc); \
2514 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2517 /* raw data, will be folded later if needed */ \
2525 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2526 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2527 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2528 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2529 TRIE_LIST_LEN( state ) = ging; \
2531 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2532 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2533 TRIE_LIST_CUR( state )++; \
2536 #define TRIE_LIST_NEW(state) STMT_START { \
2537 Newx( trie->states[ state ].trans.list, \
2538 4, reg_trie_trans_le ); \
2539 TRIE_LIST_CUR( state ) = 1; \
2540 TRIE_LIST_LEN( state ) = 4; \
2543 #define TRIE_HANDLE_WORD(state) STMT_START { \
2544 U16 dupe= trie->states[ state ].wordnum; \
2545 regnode * const noper_next = regnext( noper ); \
2548 /* store the word for dumping */ \
2550 if (OP(noper) != NOTHING) \
2551 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2553 tmp = newSVpvn_utf8( "", 0, UTF ); \
2554 av_push( trie_words, tmp ); \
2558 trie->wordinfo[curword].prev = 0; \
2559 trie->wordinfo[curword].len = wordlen; \
2560 trie->wordinfo[curword].accept = state; \
2562 if ( noper_next < tail ) { \
2564 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2566 trie->jump[curword] = (U16)(noper_next - convert); \
2568 jumper = noper_next; \
2570 nextbranch= regnext(cur); \
2574 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2575 /* chain, so that when the bits of chain are later */\
2576 /* linked together, the dups appear in the chain */\
2577 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2578 trie->wordinfo[dupe].prev = curword; \
2580 /* we haven't inserted this word yet. */ \
2581 trie->states[ state ].wordnum = curword; \
2586 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2587 ( ( base + charid >= ucharcount \
2588 && base + charid < ubound \
2589 && state == trie->trans[ base - ucharcount + charid ].check \
2590 && trie->trans[ base - ucharcount + charid ].next ) \
2591 ? trie->trans[ base - ucharcount + charid ].next \
2592 : ( state==1 ? special : 0 ) \
2595 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2597 TRIE_BITMAP_SET(trie, uvc); \
2598 /* store the folded codepoint */ \
2600 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2603 /* store first byte of utf8 representation of */ \
2604 /* variant codepoints */ \
2605 if (! UVCHR_IS_INVARIANT(uvc)) { \
2606 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2611 #define MADE_JUMP_TRIE 2
2612 #define MADE_EXACT_TRIE 4
2615 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2616 regnode *first, regnode *last, regnode *tail,
2617 U32 word_count, U32 flags, U32 depth)
2619 /* first pass, loop through and scan words */
2620 reg_trie_data *trie;
2621 HV *widecharmap = NULL;
2622 AV *revcharmap = newAV();
2628 regnode *jumper = NULL;
2629 regnode *nextbranch = NULL;
2630 regnode *convert = NULL;
2631 U32 *prev_states; /* temp array mapping each state to previous one */
2632 /* we just use folder as a flag in utf8 */
2633 const U8 * folder = NULL;
2635 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2636 * which stands for one trie structure, one hash, optionally followed
2639 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2640 AV *trie_words = NULL;
2641 /* along with revcharmap, this only used during construction but both are
2642 * useful during debugging so we store them in the struct when debugging.
2645 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2646 STRLEN trie_charcount=0;
2648 SV *re_trie_maxbuff;
2649 GET_RE_DEBUG_FLAGS_DECL;
2651 PERL_ARGS_ASSERT_MAKE_TRIE;
2653 PERL_UNUSED_ARG(depth);
2657 case EXACT: case EXACTL: break;
2661 case EXACTFLU8: folder = PL_fold_latin1; break;
2662 case EXACTF: folder = PL_fold; break;
2663 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2666 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2668 trie->startstate = 1;
2669 trie->wordcount = word_count;
2670 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2671 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2672 if (flags == EXACT || flags == EXACTL)
2673 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2674 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2675 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2678 trie_words = newAV();
2681 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2682 assert(re_trie_maxbuff);
2683 if (!SvIOK(re_trie_maxbuff)) {
2684 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2686 DEBUG_TRIE_COMPILE_r({
2687 Perl_re_indentf( aTHX_
2688 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2690 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2691 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2694 /* Find the node we are going to overwrite */
2695 if ( first == startbranch && OP( last ) != BRANCH ) {
2696 /* whole branch chain */
2699 /* branch sub-chain */
2700 convert = NEXTOPER( first );
2703 /* -- First loop and Setup --
2705 We first traverse the branches and scan each word to determine if it
2706 contains widechars, and how many unique chars there are, this is
2707 important as we have to build a table with at least as many columns as we
2710 We use an array of integers to represent the character codes 0..255
2711 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2712 the native representation of the character value as the key and IV's for
2715 *TODO* If we keep track of how many times each character is used we can
2716 remap the columns so that the table compression later on is more
2717 efficient in terms of memory by ensuring the most common value is in the
2718 middle and the least common are on the outside. IMO this would be better
2719 than a most to least common mapping as theres a decent chance the most
2720 common letter will share a node with the least common, meaning the node
2721 will not be compressible. With a middle is most common approach the worst
2722 case is when we have the least common nodes twice.
2726 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2727 regnode *noper = NEXTOPER( cur );
2731 U32 wordlen = 0; /* required init */
2732 STRLEN minchars = 0;
2733 STRLEN maxchars = 0;
2734 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2737 if (OP(noper) == NOTHING) {
2738 /* skip past a NOTHING at the start of an alternation
2739 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2741 regnode *noper_next= regnext(noper);
2742 if (noper_next < tail)
2746 if ( noper < tail &&
2748 OP(noper) == flags ||
2751 OP(noper) == EXACTFU_SS
2755 uc= (U8*)STRING(noper);
2756 e= uc + STR_LEN(noper);
2763 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2764 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2765 regardless of encoding */
2766 if (OP( noper ) == EXACTFU_SS) {
2767 /* false positives are ok, so just set this */
2768 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2772 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2774 TRIE_CHARCOUNT(trie)++;
2777 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2778 * is in effect. Under /i, this character can match itself, or
2779 * anything that folds to it. If not under /i, it can match just
2780 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2781 * all fold to k, and all are single characters. But some folds
2782 * expand to more than one character, so for example LATIN SMALL
2783 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2784 * the string beginning at 'uc' is 'ffi', it could be matched by
2785 * three characters, or just by the one ligature character. (It
2786 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2787 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2788 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2789 * match.) The trie needs to know the minimum and maximum number
2790 * of characters that could match so that it can use size alone to
2791 * quickly reject many match attempts. The max is simple: it is
2792 * the number of folded characters in this branch (since a fold is
2793 * never shorter than what folds to it. */
2797 /* And the min is equal to the max if not under /i (indicated by
2798 * 'folder' being NULL), or there are no multi-character folds. If
2799 * there is a multi-character fold, the min is incremented just
2800 * once, for the character that folds to the sequence. Each
2801 * character in the sequence needs to be added to the list below of
2802 * characters in the trie, but we count only the first towards the
2803 * min number of characters needed. This is done through the
2804 * variable 'foldlen', which is returned by the macros that look
2805 * for these sequences as the number of bytes the sequence
2806 * occupies. Each time through the loop, we decrement 'foldlen' by
2807 * how many bytes the current char occupies. Only when it reaches
2808 * 0 do we increment 'minchars' or look for another multi-character
2810 if (folder == NULL) {
2813 else if (foldlen > 0) {
2814 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2819 /* See if *uc is the beginning of a multi-character fold. If
2820 * so, we decrement the length remaining to look at, to account
2821 * for the current character this iteration. (We can use 'uc'
2822 * instead of the fold returned by TRIE_READ_CHAR because for
2823 * non-UTF, the latin1_safe macro is smart enough to account
2824 * for all the unfolded characters, and because for UTF, the
2825 * string will already have been folded earlier in the
2826 * compilation process */
2828 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2829 foldlen -= UTF8SKIP(uc);
2832 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2837 /* The current character (and any potential folds) should be added
2838 * to the possible matching characters for this position in this
2842 U8 folded= folder[ (U8) uvc ];
2843 if ( !trie->charmap[ folded ] ) {
2844 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2845 TRIE_STORE_REVCHAR( folded );
2848 if ( !trie->charmap[ uvc ] ) {
2849 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2850 TRIE_STORE_REVCHAR( uvc );
2853 /* store the codepoint in the bitmap, and its folded
2855 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2856 set_bit = 0; /* We've done our bit :-) */
2860 /* XXX We could come up with the list of code points that fold
2861 * to this using PL_utf8_foldclosures, except not for
2862 * multi-char folds, as there may be multiple combinations
2863 * there that could work, which needs to wait until runtime to
2864 * resolve (The comment about LIGATURE FFI above is such an
2869 widecharmap = newHV();
2871 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2874 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2876 if ( !SvTRUE( *svpp ) ) {
2877 sv_setiv( *svpp, ++trie->uniquecharcount );
2878 TRIE_STORE_REVCHAR(uvc);
2881 } /* end loop through characters in this branch of the trie */
2883 /* We take the min and max for this branch and combine to find the min
2884 * and max for all branches processed so far */
2885 if( cur == first ) {
2886 trie->minlen = minchars;
2887 trie->maxlen = maxchars;
2888 } else if (minchars < trie->minlen) {
2889 trie->minlen = minchars;
2890 } else if (maxchars > trie->maxlen) {
2891 trie->maxlen = maxchars;
2893 } /* end first pass */
2894 DEBUG_TRIE_COMPILE_r(
2895 Perl_re_indentf( aTHX_
2896 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2898 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2899 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2900 (int)trie->minlen, (int)trie->maxlen )
2904 We now know what we are dealing with in terms of unique chars and
2905 string sizes so we can calculate how much memory a naive
2906 representation using a flat table will take. If it's over a reasonable
2907 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2908 conservative but potentially much slower representation using an array
2911 At the end we convert both representations into the same compressed
2912 form that will be used in regexec.c for matching with. The latter
2913 is a form that cannot be used to construct with but has memory
2914 properties similar to the list form and access properties similar
2915 to the table form making it both suitable for fast searches and
2916 small enough that its feasable to store for the duration of a program.
2918 See the comment in the code where the compressed table is produced
2919 inplace from the flat tabe representation for an explanation of how
2920 the compression works.
2925 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2928 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2929 > SvIV(re_trie_maxbuff) )
2932 Second Pass -- Array Of Lists Representation
2934 Each state will be represented by a list of charid:state records
2935 (reg_trie_trans_le) the first such element holds the CUR and LEN
2936 points of the allocated array. (See defines above).
2938 We build the initial structure using the lists, and then convert
2939 it into the compressed table form which allows faster lookups
2940 (but cant be modified once converted).
2943 STRLEN transcount = 1;
2945 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
2948 trie->states = (reg_trie_state *)
2949 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2950 sizeof(reg_trie_state) );
2954 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2956 regnode *noper = NEXTOPER( cur );
2957 U32 state = 1; /* required init */
2958 U16 charid = 0; /* sanity init */
2959 U32 wordlen = 0; /* required init */
2961 if (OP(noper) == NOTHING) {
2962 regnode *noper_next= regnext(noper);
2963 if (noper_next < tail)
2967 if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
2968 const U8 *uc= (U8*)STRING(noper);
2969 const U8 *e= uc + STR_LEN(noper);
2971 for ( ; uc < e ; uc += len ) {
2976 charid = trie->charmap[ uvc ];
2978 SV** const svpp = hv_fetch( widecharmap,
2985 charid=(U16)SvIV( *svpp );
2988 /* charid is now 0 if we dont know the char read, or
2989 * nonzero if we do */
2996 if ( !trie->states[ state ].trans.list ) {
2997 TRIE_LIST_NEW( state );
3000 check <= TRIE_LIST_USED( state );
3003 if ( TRIE_LIST_ITEM( state, check ).forid
3006 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3011 newstate = next_alloc++;
3012 prev_states[newstate] = state;
3013 TRIE_LIST_PUSH( state, charid, newstate );
3018 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3022 TRIE_HANDLE_WORD(state);
3024 } /* end second pass */
3026 /* next alloc is the NEXT state to be allocated */
3027 trie->statecount = next_alloc;
3028 trie->states = (reg_trie_state *)
3029 PerlMemShared_realloc( trie->states,
3031 * sizeof(reg_trie_state) );
3033 /* and now dump it out before we compress it */
3034 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3035 revcharmap, next_alloc,
3039 trie->trans = (reg_trie_trans *)
3040 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3047 for( state=1 ; state < next_alloc ; state ++ ) {
3051 DEBUG_TRIE_COMPILE_MORE_r(
3052 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3056 if (trie->states[state].trans.list) {
3057 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3061 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3062 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3063 if ( forid < minid ) {
3065 } else if ( forid > maxid ) {
3069 if ( transcount < tp + maxid - minid + 1) {
3071 trie->trans = (reg_trie_trans *)
3072 PerlMemShared_realloc( trie->trans,
3074 * sizeof(reg_trie_trans) );
3075 Zero( trie->trans + (transcount / 2),
3079 base = trie->uniquecharcount + tp - minid;
3080 if ( maxid == minid ) {
3082 for ( ; zp < tp ; zp++ ) {
3083 if ( ! trie->trans[ zp ].next ) {
3084 base = trie->uniquecharcount + zp - minid;
3085 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3087 trie->trans[ zp ].check = state;
3093 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3095 trie->trans[ tp ].check = state;
3100 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3101 const U32 tid = base
3102 - trie->uniquecharcount
3103 + TRIE_LIST_ITEM( state, idx ).forid;
3104 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3106 trie->trans[ tid ].check = state;
3108 tp += ( maxid - minid + 1 );
3110 Safefree(trie->states[ state ].trans.list);
3113 DEBUG_TRIE_COMPILE_MORE_r(
3114 Perl_re_printf( aTHX_ " base: %d\n",base);
3117 trie->states[ state ].trans.base=base;
3119 trie->lasttrans = tp + 1;
3123 Second Pass -- Flat Table Representation.
3125 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3126 each. We know that we will need Charcount+1 trans at most to store
3127 the data (one row per char at worst case) So we preallocate both
3128 structures assuming worst case.
3130 We then construct the trie using only the .next slots of the entry
3133 We use the .check field of the first entry of the node temporarily
3134 to make compression both faster and easier by keeping track of how
3135 many non zero fields are in the node.
3137 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3140 There are two terms at use here: state as a TRIE_NODEIDX() which is
3141 a number representing the first entry of the node, and state as a
3142 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3143 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3144 if there are 2 entrys per node. eg:
3152 The table is internally in the right hand, idx form. However as we
3153 also have to deal with the states array which is indexed by nodenum
3154 we have to use TRIE_NODENUM() to convert.
3157 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3160 trie->trans = (reg_trie_trans *)
3161 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3162 * trie->uniquecharcount + 1,
3163 sizeof(reg_trie_trans) );
3164 trie->states = (reg_trie_state *)
3165 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3166 sizeof(reg_trie_state) );
3167 next_alloc = trie->uniquecharcount + 1;
3170 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3172 regnode *noper = NEXTOPER( cur );
3174 U32 state = 1; /* required init */
3176 U16 charid = 0; /* sanity init */
3177 U32 accept_state = 0; /* sanity init */
3179 U32 wordlen = 0; /* required init */
3181 if (OP(noper) == NOTHING) {
3182 regnode *noper_next= regnext(noper);
3183 if (noper_next < tail)
3187 if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
3188 const U8 *uc= (U8*)STRING(noper);
3189 const U8 *e= uc + STR_LEN(noper);
3191 for ( ; uc < e ; uc += len ) {
3196 charid = trie->charmap[ uvc ];
3198 SV* const * const svpp = hv_fetch( widecharmap,
3202 charid = svpp ? (U16)SvIV(*svpp) : 0;
3206 if ( !trie->trans[ state + charid ].next ) {
3207 trie->trans[ state + charid ].next = next_alloc;
3208 trie->trans[ state ].check++;
3209 prev_states[TRIE_NODENUM(next_alloc)]
3210 = TRIE_NODENUM(state);
3211 next_alloc += trie->uniquecharcount;
3213 state = trie->trans[ state + charid ].next;
3215 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3217 /* charid is now 0 if we dont know the char read, or
3218 * nonzero if we do */
3221 accept_state = TRIE_NODENUM( state );
3222 TRIE_HANDLE_WORD(accept_state);
3224 } /* end second pass */
3226 /* and now dump it out before we compress it */
3227 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3229 next_alloc, depth+1));
3233 * Inplace compress the table.*
3235 For sparse data sets the table constructed by the trie algorithm will
3236 be mostly 0/FAIL transitions or to put it another way mostly empty.
3237 (Note that leaf nodes will not contain any transitions.)
3239 This algorithm compresses the tables by eliminating most such
3240 transitions, at the cost of a modest bit of extra work during lookup:
3242 - Each states[] entry contains a .base field which indicates the
3243 index in the state[] array wheres its transition data is stored.
3245 - If .base is 0 there are no valid transitions from that node.
3247 - If .base is nonzero then charid is added to it to find an entry in
3250 -If trans[states[state].base+charid].check!=state then the
3251 transition is taken to be a 0/Fail transition. Thus if there are fail
3252 transitions at the front of the node then the .base offset will point
3253 somewhere inside the previous nodes data (or maybe even into a node
3254 even earlier), but the .check field determines if the transition is
3258 The following process inplace converts the table to the compressed
3259 table: We first do not compress the root node 1,and mark all its
3260 .check pointers as 1 and set its .base pointer as 1 as well. This
3261 allows us to do a DFA construction from the compressed table later,
3262 and ensures that any .base pointers we calculate later are greater
3265 - We set 'pos' to indicate the first entry of the second node.
3267 - We then iterate over the columns of the node, finding the first and
3268 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3269 and set the .check pointers accordingly, and advance pos
3270 appropriately and repreat for the next node. Note that when we copy
3271 the next pointers we have to convert them from the original
3272 NODEIDX form to NODENUM form as the former is not valid post
3275 - If a node has no transitions used we mark its base as 0 and do not
3276 advance the pos pointer.
3278 - If a node only has one transition we use a second pointer into the
3279 structure to fill in allocated fail transitions from other states.
3280 This pointer is independent of the main pointer and scans forward
3281 looking for null transitions that are allocated to a state. When it
3282 finds one it writes the single transition into the "hole". If the
3283 pointer doesnt find one the single transition is appended as normal.
3285 - Once compressed we can Renew/realloc the structures to release the
3288 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3289 specifically Fig 3.47 and the associated pseudocode.
3293 const U32 laststate = TRIE_NODENUM( next_alloc );
3296 trie->statecount = laststate;
3298 for ( state = 1 ; state < laststate ; state++ ) {
3300 const U32 stateidx = TRIE_NODEIDX( state );
3301 const U32 o_used = trie->trans[ stateidx ].check;
3302 U32 used = trie->trans[ stateidx ].check;
3303 trie->trans[ stateidx ].check = 0;
3306 used && charid < trie->uniquecharcount;
3309 if ( flag || trie->trans[ stateidx + charid ].next ) {
3310 if ( trie->trans[ stateidx + charid ].next ) {
3312 for ( ; zp < pos ; zp++ ) {
3313 if ( ! trie->trans[ zp ].next ) {
3317 trie->states[ state ].trans.base
3319 + trie->uniquecharcount
3321 trie->trans[ zp ].next
3322 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3324 trie->trans[ zp ].check = state;
3325 if ( ++zp > pos ) pos = zp;
3332 trie->states[ state ].trans.base
3333 = pos + trie->uniquecharcount - charid ;
3335 trie->trans[ pos ].next
3336 = SAFE_TRIE_NODENUM(
3337 trie->trans[ stateidx + charid ].next );
3338 trie->trans[ pos ].check = state;
3343 trie->lasttrans = pos + 1;
3344 trie->states = (reg_trie_state *)
3345 PerlMemShared_realloc( trie->states, laststate
3346 * sizeof(reg_trie_state) );
3347 DEBUG_TRIE_COMPILE_MORE_r(
3348 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3350 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3354 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3357 } /* end table compress */
3359 DEBUG_TRIE_COMPILE_MORE_r(
3360 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3362 (UV)trie->statecount,
3363 (UV)trie->lasttrans)
3365 /* resize the trans array to remove unused space */
3366 trie->trans = (reg_trie_trans *)
3367 PerlMemShared_realloc( trie->trans, trie->lasttrans
3368 * sizeof(reg_trie_trans) );
3370 { /* Modify the program and insert the new TRIE node */
3371 U8 nodetype =(U8)(flags & 0xFF);
3375 regnode *optimize = NULL;
3376 #ifdef RE_TRACK_PATTERN_OFFSETS
3379 U32 mjd_nodelen = 0;
3380 #endif /* RE_TRACK_PATTERN_OFFSETS */
3381 #endif /* DEBUGGING */
3383 This means we convert either the first branch or the first Exact,
3384 depending on whether the thing following (in 'last') is a branch
3385 or not and whther first is the startbranch (ie is it a sub part of
3386 the alternation or is it the whole thing.)
3387 Assuming its a sub part we convert the EXACT otherwise we convert
3388 the whole branch sequence, including the first.
3390 /* Find the node we are going to overwrite */
3391 if ( first != startbranch || OP( last ) == BRANCH ) {
3392 /* branch sub-chain */
3393 NEXT_OFF( first ) = (U16)(last - first);
3394 #ifdef RE_TRACK_PATTERN_OFFSETS
3396 mjd_offset= Node_Offset((convert));
3397 mjd_nodelen= Node_Length((convert));
3400 /* whole branch chain */
3402 #ifdef RE_TRACK_PATTERN_OFFSETS
3405 const regnode *nop = NEXTOPER( convert );
3406 mjd_offset= Node_Offset((nop));
3407 mjd_nodelen= Node_Length((nop));
3411 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3413 (UV)mjd_offset, (UV)mjd_nodelen)
3416 /* But first we check to see if there is a common prefix we can
3417 split out as an EXACT and put in front of the TRIE node. */
3418 trie->startstate= 1;
3419 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3420 /* we want to find the first state that has more than
3421 * one transition, if that state is not the first state
3422 * then we have a common prefix which we can remove.
3425 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3427 I32 first_ofs = -1; /* keeps track of the ofs of the first
3428 transition, -1 means none */
3430 const U32 base = trie->states[ state ].trans.base;
3432 /* does this state terminate an alternation? */
3433 if ( trie->states[state].wordnum )
3436 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3437 if ( ( base + ofs >= trie->uniquecharcount ) &&
3438 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3439 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3441 if ( ++count > 1 ) {
3442 /* we have more than one transition */
3445 /* if this is the first state there is no common prefix
3446 * to extract, so we can exit */
3447 if ( state == 1 ) break;
3448 tmp = av_fetch( revcharmap, ofs, 0);
3449 ch = (U8*)SvPV_nolen_const( *tmp );
3451 /* if we are on count 2 then we need to initialize the
3452 * bitmap, and store the previous char if there was one
3455 /* clear the bitmap */
3456 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3458 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3461 if (first_ofs >= 0) {
3462 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3463 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3465 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3467 Perl_re_printf( aTHX_ "%s", (char*)ch)
3471 /* store the current firstchar in the bitmap */
3472 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3473 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3479 /* This state has only one transition, its transition is part
3480 * of a common prefix - we need to concatenate the char it
3481 * represents to what we have so far. */
3482 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3484 char *ch = SvPV( *tmp, len );
3486 SV *sv=sv_newmortal();
3487 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3489 (UV)state, (UV)first_ofs,
3490 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3491 PL_colors[0], PL_colors[1],
3492 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3493 PERL_PV_ESCAPE_FIRSTCHAR
3498 OP( convert ) = nodetype;
3499 str=STRING(convert);
3502 STR_LEN(convert) += len;
3508 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3513 trie->prefixlen = (state-1);
3515 regnode *n = convert+NODE_SZ_STR(convert);
3516 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3517 trie->startstate = state;
3518 trie->minlen -= (state - 1);
3519 trie->maxlen -= (state - 1);
3521 /* At least the UNICOS C compiler choked on this
3522 * being argument to DEBUG_r(), so let's just have
3525 #ifdef PERL_EXT_RE_BUILD
3531 regnode *fix = convert;
3532 U32 word = trie->wordcount;
3533 #ifdef RE_TRACK_PATTERN_OFFSETS
3536 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3537 while( ++fix < n ) {
3538 Set_Node_Offset_Length(fix, 0, 0);
3541 SV ** const tmp = av_fetch( trie_words, word, 0 );
3543 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3544 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3546 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3554 NEXT_OFF(convert) = (U16)(tail - convert);
3555 DEBUG_r(optimize= n);
3561 if ( trie->maxlen ) {
3562 NEXT_OFF( convert ) = (U16)(tail - convert);
3563 ARG_SET( convert, data_slot );
3564 /* Store the offset to the first unabsorbed branch in
3565 jump[0], which is otherwise unused by the jump logic.
3566 We use this when dumping a trie and during optimisation. */
3568 trie->jump[0] = (U16)(nextbranch - convert);
3570 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3571 * and there is a bitmap
3572 * and the first "jump target" node we found leaves enough room
3573 * then convert the TRIE node into a TRIEC node, with the bitmap
3574 * embedded inline in the opcode - this is hypothetically faster.
3576 if ( !trie->states[trie->startstate].wordnum
3578 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3580 OP( convert ) = TRIEC;
3581 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3582 PerlMemShared_free(trie->bitmap);
3585 OP( convert ) = TRIE;
3587 /* store the type in the flags */
3588 convert->flags = nodetype;
3592 + regarglen[ OP( convert ) ];
3594 /* XXX We really should free up the resource in trie now,
3595 as we won't use them - (which resources?) dmq */
3597 /* needed for dumping*/
3598 DEBUG_r(if (optimize) {
3599 regnode *opt = convert;
3601 while ( ++opt < optimize) {
3602 Set_Node_Offset_Length(opt, 0, 0);
3605 Try to clean up some of the debris left after the
3608 while( optimize < jumper ) {
3609 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3610 OP( optimize ) = OPTIMIZED;
3611 Set_Node_Offset_Length(optimize, 0, 0);
3614 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3616 } /* end node insert */
3618 /* Finish populating the prev field of the wordinfo array. Walk back
3619 * from each accept state until we find another accept state, and if
3620 * so, point the first word's .prev field at the second word. If the
3621 * second already has a .prev field set, stop now. This will be the
3622 * case either if we've already processed that word's accept state,
3623 * or that state had multiple words, and the overspill words were
3624 * already linked up earlier.
3631 for (word=1; word <= trie->wordcount; word++) {
3633 if (trie->wordinfo[word].prev)
3635 state = trie->wordinfo[word].accept;
3637 state = prev_states[state];
3640 prev = trie->states[state].wordnum;
3644 trie->wordinfo[word].prev = prev;
3646 Safefree(prev_states);
3650 /* and now dump out the compressed format */
3651 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3653 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3655 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3656 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3658 SvREFCNT_dec_NN(revcharmap);
3662 : trie->startstate>1
3668 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3670 /* The Trie is constructed and compressed now so we can build a fail array if
3673 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3675 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3679 We find the fail state for each state in the trie, this state is the longest
3680 proper suffix of the current state's 'word' that is also a proper prefix of
3681 another word in our trie. State 1 represents the word '' and is thus the
3682 default fail state. This allows the DFA not to have to restart after its
3683 tried and failed a word at a given point, it simply continues as though it
3684 had been matching the other word in the first place.
3686 'abcdgu'=~/abcdefg|cdgu/
3687 When we get to 'd' we are still matching the first word, we would encounter
3688 'g' which would fail, which would bring us to the state representing 'd' in
3689 the second word where we would try 'g' and succeed, proceeding to match
3692 /* add a fail transition */
3693 const U32 trie_offset = ARG(source);
3694 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3696 const U32 ucharcount = trie->uniquecharcount;
3697 const U32 numstates = trie->statecount;
3698 const U32 ubound = trie->lasttrans + ucharcount;
3702 U32 base = trie->states[ 1 ].trans.base;
3705 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3707 GET_RE_DEBUG_FLAGS_DECL;
3709 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3710 PERL_UNUSED_CONTEXT;
3712 PERL_UNUSED_ARG(depth);
3715 if ( OP(source) == TRIE ) {
3716 struct regnode_1 *op = (struct regnode_1 *)
3717 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3718 StructCopy(source, op, struct regnode_1);
3719 stclass = (regnode *)op;
3721 struct regnode_charclass *op = (struct regnode_charclass *)
3722 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3723 StructCopy(source, op, struct regnode_charclass);
3724 stclass = (regnode *)op;
3726 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3728 ARG_SET( stclass, data_slot );
3729 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3730 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3731 aho->trie=trie_offset;
3732 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3733 Copy( trie->states, aho->states, numstates, reg_trie_state );
3734 Newx( q, numstates, U32);
3735 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3738 /* initialize fail[0..1] to be 1 so that we always have
3739 a valid final fail state */
3740 fail[ 0 ] = fail[ 1 ] = 1;
3742 for ( charid = 0; charid < ucharcount ; charid++ ) {
3743 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3745 q[ q_write ] = newstate;
3746 /* set to point at the root */
3747 fail[ q[ q_write++ ] ]=1;
3750 while ( q_read < q_write) {
3751 const U32 cur = q[ q_read++ % numstates ];
3752 base = trie->states[ cur ].trans.base;
3754 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3755 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3757 U32 fail_state = cur;
3760 fail_state = fail[ fail_state ];
3761 fail_base = aho->states[ fail_state ].trans.base;
3762 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3764 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3765 fail[ ch_state ] = fail_state;
3766 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3768 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3770 q[ q_write++ % numstates] = ch_state;
3774 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3775 when we fail in state 1, this allows us to use the
3776 charclass scan to find a valid start char. This is based on the principle
3777 that theres a good chance the string being searched contains lots of stuff
3778 that cant be a start char.
3780 fail[ 0 ] = fail[ 1 ] = 0;
3781 DEBUG_TRIE_COMPILE_r({
3782 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3783 depth, (UV)numstates
3785 for( q_read=1; q_read<numstates; q_read++ ) {
3786 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3788 Perl_re_printf( aTHX_ "\n");
3791 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3796 /* The below joins as many adjacent EXACTish nodes as possible into a single
3797 * one. The regop may be changed if the node(s) contain certain sequences that
3798 * require special handling. The joining is only done if:
3799 * 1) there is room in the current conglomerated node to entirely contain the
3801 * 2) they are the exact same node type
3803 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3804 * these get optimized out
3806 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3807 * as possible, even if that means splitting an existing node so that its first
3808 * part is moved to the preceeding node. This would maximise the efficiency of
3809 * memEQ during matching.
3811 * If a node is to match under /i (folded), the number of characters it matches
3812 * can be different than its character length if it contains a multi-character
3813 * fold. *min_subtract is set to the total delta number of characters of the
3816 * And *unfolded_multi_char is set to indicate whether or not the node contains
3817 * an unfolded multi-char fold. This happens when it won't be known until
3818 * runtime whether the fold is valid or not; namely
3819 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3820 * target string being matched against turns out to be UTF-8 is that fold
3822 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3824 * (Multi-char folds whose components are all above the Latin1 range are not
3825 * run-time locale dependent, and have already been folded by the time this
3826 * function is called.)
3828 * This is as good a place as any to discuss the design of handling these
3829 * multi-character fold sequences. It's been wrong in Perl for a very long
3830 * time. There are three code points in Unicode whose multi-character folds
3831 * were long ago discovered to mess things up. The previous designs for
3832 * dealing with these involved assigning a special node for them. This
3833 * approach doesn't always work, as evidenced by this example:
3834 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3835 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3836 * would match just the \xDF, it won't be able to handle the case where a
3837 * successful match would have to cross the node's boundary. The new approach
3838 * that hopefully generally solves the problem generates an EXACTFU_SS node
3839 * that is "sss" in this case.
3841 * It turns out that there are problems with all multi-character folds, and not
3842 * just these three. Now the code is general, for all such cases. The
3843 * approach taken is:
3844 * 1) This routine examines each EXACTFish node that could contain multi-
3845 * character folded sequences. Since a single character can fold into
3846 * such a sequence, the minimum match length for this node is less than
3847 * the number of characters in the node. This routine returns in
3848 * *min_subtract how many characters to subtract from the the actual
3849 * length of the string to get a real minimum match length; it is 0 if
3850 * there are no multi-char foldeds. This delta is used by the caller to
3851 * adjust the min length of the match, and the delta between min and max,
3852 * so that the optimizer doesn't reject these possibilities based on size
3854 * 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3855 * is used for an EXACTFU node that contains at least one "ss" sequence in
3856 * it. For non-UTF-8 patterns and strings, this is the only case where
3857 * there is a possible fold length change. That means that a regular
3858 * EXACTFU node without UTF-8 involvement doesn't have to concern itself
3859 * with length changes, and so can be processed faster. regexec.c takes
3860 * advantage of this. Generally, an EXACTFish node that is in UTF-8 is
3861 * pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3862 * known until runtime). This saves effort in regex matching. However,
3863 * the pre-folding isn't done for non-UTF8 patterns because the fold of
3864 * the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3865 * forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
3866 * again, EXACTFL) nodes fold to isn't known until runtime. The fold
3867 * possibilities for the non-UTF8 patterns are quite simple, except for
3868 * the sharp s. All the ones that don't involve a UTF-8 target string are
3869 * members of a fold-pair, and arrays are set up for all of them so that
3870 * the other member of the pair can be found quickly. Code elsewhere in
3871 * this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3872 * 'ss', even if the pattern isn't UTF-8. This avoids the issues
3873 * described in the next item.
3874 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3875 * validity of the fold won't be known until runtime, and so must remain
3876 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
3877 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3878 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3879 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3880 * The reason this is a problem is that the optimizer part of regexec.c
3881 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3882 * that a character in the pattern corresponds to at most a single
3883 * character in the target string. (And I do mean character, and not byte
3884 * here, unlike other parts of the documentation that have never been
3885 * updated to account for multibyte Unicode.) sharp s in EXACTF and
3886 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3887 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
3888 * EXACTFL nodes, violate the assumption, and they are the only instances
3889 * where it is violated. I'm reluctant to try to change the assumption,
3890 * as the code involved is impenetrable to me (khw), so instead the code
3891 * here punts. This routine examines EXACTFL nodes, and (when the pattern
3892 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3893 * boolean indicating whether or not the node contains such a fold. When
3894 * it is true, the caller sets a flag that later causes the optimizer in
3895 * this file to not set values for the floating and fixed string lengths,
3896 * and thus avoids the optimizer code in regexec.c that makes the invalid
3897 * assumption. Thus, there is no optimization based on string lengths for
3898 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3899 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
3900 * assumption is wrong only in these cases is that all other non-UTF-8
3901 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3902 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3903 * EXACTF nodes because we don't know at compile time if it actually
3904 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3905 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3906 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
3907 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3908 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3909 * string would require the pattern to be forced into UTF-8, the overhead
3910 * of which we want to avoid. Similarly the unfolded multi-char folds in
3911 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3914 * Similarly, the code that generates tries doesn't currently handle
3915 * not-already-folded multi-char folds, and it looks like a pain to change
3916 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
3917 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
3918 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
3919 * using /iaa matching will be doing so almost entirely with ASCII
3920 * strings, so this should rarely be encountered in practice */
3922 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3923 if (PL_regkind[OP(scan)] == EXACT) \
3924 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
3927 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3928 UV *min_subtract, bool *unfolded_multi_char,
3929 U32 flags, regnode *val, U32 depth)
3931 /* Merge several consecutive EXACTish nodes into one. */
3932 regnode *n = regnext(scan);
3934 regnode *next = scan + NODE_SZ_STR(scan);
3938 regnode *stop = scan;
3939 GET_RE_DEBUG_FLAGS_DECL;
3941 PERL_UNUSED_ARG(depth);
3944 PERL_ARGS_ASSERT_JOIN_EXACT;
3945 #ifndef EXPERIMENTAL_INPLACESCAN
3946 PERL_UNUSED_ARG(flags);
3947 PERL_UNUSED_ARG(val);
3949 DEBUG_PEEP("join", scan, depth, 0);
3951 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3952 * EXACT ones that are mergeable to the current one. */
3954 && (PL_regkind[OP(n)] == NOTHING
3955 || (stringok && OP(n) == OP(scan)))
3957 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3960 if (OP(n) == TAIL || n > next)
3962 if (PL_regkind[OP(n)] == NOTHING) {
3963 DEBUG_PEEP("skip:", n, depth, 0);
3964 NEXT_OFF(scan) += NEXT_OFF(n);
3965 next = n + NODE_STEP_REGNODE;
3972 else if (stringok) {
3973 const unsigned int oldl = STR_LEN(scan);
3974 regnode * const nnext = regnext(n);
3976 /* XXX I (khw) kind of doubt that this works on platforms (should
3977 * Perl ever run on one) where U8_MAX is above 255 because of lots
3978 * of other assumptions */
3979 /* Don't join if the sum can't fit into a single node */
3980 if (oldl + STR_LEN(n) > U8_MAX)
3983 DEBUG_PEEP("merg", n, depth, 0);
3986 NEXT_OFF(scan) += NEXT_OFF(n);
3987 STR_LEN(scan) += STR_LEN(n);
3988 next = n + NODE_SZ_STR(n);
3989 /* Now we can overwrite *n : */
3990 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3998 #ifdef EXPERIMENTAL_INPLACESCAN
3999 if (flags && !NEXT_OFF(n)) {
4000 DEBUG_PEEP("atch", val, depth, 0);
4001 if (reg_off_by_arg[OP(n)]) {
4002 ARG_SET(n, val - n);
4005 NEXT_OFF(n) = val - n;
4013 *unfolded_multi_char