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
78 #ifdef PERL_IN_XSUB_RE
80 EXTERN_C const struct regexp_engine my_reg_engine;
85 #include "dquote_inline.h"
86 #include "invlist_inline.h"
87 #include "unicode_constants.h"
89 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
90 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
91 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
92 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
93 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
94 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
100 /* this is a chain of data about sub patterns we are processing that
101 need to be handled separately/specially in study_chunk. Its so
102 we can simulate recursion without losing state. */
104 typedef struct scan_frame {
105 regnode *last_regnode; /* last node to process in this frame */
106 regnode *next_regnode; /* next node to process when last is reached */
107 U32 prev_recursed_depth;
108 I32 stopparen; /* what stopparen do we use */
110 struct scan_frame *this_prev_frame; /* this previous frame */
111 struct scan_frame *prev_frame; /* previous frame */
112 struct scan_frame *next_frame; /* next frame */
115 /* Certain characters are output as a sequence with the first being a
117 #define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
120 struct RExC_state_t {
121 U32 flags; /* RXf_* are we folding, multilining? */
122 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
123 char *precomp; /* uncompiled string. */
124 char *precomp_end; /* pointer to end of uncompiled string. */
125 REGEXP *rx_sv; /* The SV that is the regexp. */
126 regexp *rx; /* perl core regexp structure */
127 regexp_internal *rxi; /* internal data for regexp object
129 char *start; /* Start of input for compile */
130 char *end; /* End of input for compile */
131 char *parse; /* Input-scan pointer. */
132 char *copy_start; /* start of copy of input within
133 constructed parse string */
134 char *copy_start_in_input; /* Position in input string
135 corresponding to copy_start */
136 SSize_t whilem_seen; /* number of WHILEM in this expr */
137 regnode *emit_start; /* Start of emitted-code area */
138 regnode_offset emit; /* Code-emit pointer */
139 I32 naughty; /* How bad is this pattern? */
140 I32 sawback; /* Did we see \1, ...? */
142 SSize_t size; /* Number of regnode equivalents in
145 /* position beyond 'precomp' of the warning message furthest away from
146 * 'precomp'. During the parse, no warnings are raised for any problems
147 * earlier in the parse than this position. This works if warnings are
148 * raised the first time a given spot is parsed, and if only one
149 * independent warning is raised for any given spot */
150 Size_t latest_warn_offset;
152 I32 npar; /* Capture buffer count so far in the
153 parse, (OPEN) plus one. ("par" 0 is
155 I32 total_par; /* During initial parse, is either 0,
156 or -1; the latter indicating a
157 reparse is needed. After that pass,
158 it is what 'npar' became after the
159 pass. Hence, it being > 0 indicates
160 we are in a reparse situation */
161 I32 nestroot; /* root parens we are in - used by
164 regnode_offset *open_parens; /* offsets to open parens */
165 regnode_offset *close_parens; /* offsets to close parens */
166 regnode *end_op; /* END node in program */
167 I32 utf8; /* whether the pattern is utf8 or not */
168 I32 orig_utf8; /* whether the pattern was originally in utf8 */
169 /* XXX use this for future optimisation of case
170 * where pattern must be upgraded to utf8. */
171 I32 uni_semantics; /* If a d charset modifier should use unicode
172 rules, even if the pattern is not in
174 HV *paren_names; /* Paren names */
176 regnode **recurse; /* Recurse regops */
177 I32 recurse_count; /* Number of recurse regops we have generated */
178 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
180 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
183 I32 override_recoding;
185 I32 recode_x_to_native;
187 I32 in_multi_char_class;
188 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
190 int code_index; /* next code_blocks[] slot */
191 SSize_t maxlen; /* mininum possible number of chars in string to match */
192 scan_frame *frame_head;
193 scan_frame *frame_last;
197 #ifdef ADD_TO_REGEXEC
198 char *starttry; /* -Dr: where regtry was called. */
199 #define RExC_starttry (pRExC_state->starttry)
201 SV *runtime_code_qr; /* qr with the runtime code blocks */
203 const char *lastparse;
205 AV *paren_name_list; /* idx -> name */
206 U32 study_chunk_recursed_count;
210 #define RExC_lastparse (pRExC_state->lastparse)
211 #define RExC_lastnum (pRExC_state->lastnum)
212 #define RExC_paren_name_list (pRExC_state->paren_name_list)
213 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
214 #define RExC_mysv (pRExC_state->mysv1)
215 #define RExC_mysv1 (pRExC_state->mysv1)
216 #define RExC_mysv2 (pRExC_state->mysv2)
226 #define RExC_flags (pRExC_state->flags)
227 #define RExC_pm_flags (pRExC_state->pm_flags)
228 #define RExC_precomp (pRExC_state->precomp)
229 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
230 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
231 #define RExC_precomp_end (pRExC_state->precomp_end)
232 #define RExC_rx_sv (pRExC_state->rx_sv)
233 #define RExC_rx (pRExC_state->rx)
234 #define RExC_rxi (pRExC_state->rxi)
235 #define RExC_start (pRExC_state->start)
236 #define RExC_end (pRExC_state->end)
237 #define RExC_parse (pRExC_state->parse)
238 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
239 #define RExC_whilem_seen (pRExC_state->whilem_seen)
240 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
241 under /d from /u ? */
244 #ifdef RE_TRACK_PATTERN_OFFSETS
245 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
248 #define RExC_emit (pRExC_state->emit)
249 #define RExC_emit_start (pRExC_state->emit_start)
250 #define RExC_sawback (pRExC_state->sawback)
251 #define RExC_seen (pRExC_state->seen)
252 #define RExC_size (pRExC_state->size)
253 #define RExC_maxlen (pRExC_state->maxlen)
254 #define RExC_npar (pRExC_state->npar)
255 #define RExC_total_parens (pRExC_state->total_par)
256 #define RExC_nestroot (pRExC_state->nestroot)
257 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
258 #define RExC_utf8 (pRExC_state->utf8)
259 #define RExC_uni_semantics (pRExC_state->uni_semantics)
260 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
261 #define RExC_open_parens (pRExC_state->open_parens)
262 #define RExC_close_parens (pRExC_state->close_parens)
263 #define RExC_end_op (pRExC_state->end_op)
264 #define RExC_paren_names (pRExC_state->paren_names)
265 #define RExC_recurse (pRExC_state->recurse)
266 #define RExC_recurse_count (pRExC_state->recurse_count)
267 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
268 #define RExC_study_chunk_recursed_bytes \
269 (pRExC_state->study_chunk_recursed_bytes)
270 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
271 #define RExC_contains_locale (pRExC_state->contains_locale)
273 # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
275 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
276 #define RExC_frame_head (pRExC_state->frame_head)
277 #define RExC_frame_last (pRExC_state->frame_last)
278 #define RExC_frame_count (pRExC_state->frame_count)
279 #define RExC_strict (pRExC_state->strict)
280 #define RExC_study_started (pRExC_state->study_started)
281 #define RExC_warn_text (pRExC_state->warn_text)
282 #define RExC_in_script_run (pRExC_state->in_script_run)
283 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
284 #define RExC_unlexed_names (pRExC_state->unlexed_names)
286 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
287 * a flag to disable back-off on the fixed/floating substrings - if it's
288 * a high complexity pattern we assume the benefit of avoiding a full match
289 * is worth the cost of checking for the substrings even if they rarely help.
291 #define RExC_naughty (pRExC_state->naughty)
292 #define TOO_NAUGHTY (10)
293 #define MARK_NAUGHTY(add) \
294 if (RExC_naughty < TOO_NAUGHTY) \
295 RExC_naughty += (add)
296 #define MARK_NAUGHTY_EXP(exp, add) \
297 if (RExC_naughty < TOO_NAUGHTY) \
298 RExC_naughty += RExC_naughty / (exp) + (add)
300 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
301 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
302 ((*s) == '{' && regcurly(s)))
305 * Flags to be passed up and down.
307 #define WORST 0 /* Worst case. */
308 #define HASWIDTH 0x01 /* Known to not match null strings, could match
311 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
312 * character. (There needs to be a case: in the switch statement in regexec.c
313 * for any node marked SIMPLE.) Note that this is not the same thing as
316 #define SPSTART 0x04 /* Starts with * or + */
317 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
318 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
319 #define RESTART_PARSE 0x20 /* Need to redo the parse */
320 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
321 calcuate sizes as UTF-8 */
323 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
325 /* whether trie related optimizations are enabled */
326 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
327 #define TRIE_STUDY_OPT
328 #define FULL_TRIE_STUDY
334 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
335 #define PBITVAL(paren) (1 << ((paren) & 7))
336 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
337 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
338 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
340 #define REQUIRE_UTF8(flagp) STMT_START { \
342 *flagp = RESTART_PARSE|NEED_UTF8; \
347 /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
348 * a flag that indicates we need to override /d with /u as a result of
349 * something in the pattern. It should only be used in regards to calling
350 * set_regex_charset() or get_regex_charse() */
351 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
353 if (DEPENDS_SEMANTICS) { \
354 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
355 RExC_uni_semantics = 1; \
356 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \
357 /* No need to restart the parse if we haven't seen \
358 * anything that differs between /u and /d, and no need \
359 * to restart immediately if we're going to reparse \
360 * anyway to count parens */ \
361 *flagp |= RESTART_PARSE; \
362 return restart_retval; \
367 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
369 RExC_use_BRANCHJ = 1; \
370 if (LIKELY(! IN_PARENS_PASS)) { \
371 /* No need to restart the parse immediately if we're \
372 * going to reparse anyway to count parens */ \
373 *flagp |= RESTART_PARSE; \
374 return restart_retval; \
378 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
379 * less. After that, it must always be positive, because the whole re is
380 * considered to be surrounded by virtual parens. Setting it to negative
381 * indicates there is some construct that needs to know the actual number of
382 * parens to be properly handled. And that means an extra pass will be
383 * required after we've counted them all */
384 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
385 #define REQUIRE_PARENS_PASS \
386 STMT_START { /* No-op if have completed a pass */ \
387 if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \
389 #define IN_PARENS_PASS (RExC_total_parens < 0)
392 /* This is used to return failure (zero) early from the calling function if
393 * various flags in 'flags' are set. Two flags always cause a return:
394 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
395 * additional flags that should cause a return; 0 if none. If the return will
396 * be done, '*flagp' is first set to be all of the flags that caused the
398 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
400 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
401 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
406 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
408 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
409 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
410 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
411 if (MUST_RESTART(*(flagp))) return 0
413 /* This converts the named class defined in regcomp.h to its equivalent class
414 * number defined in handy.h. */
415 #define namedclass_to_classnum(class) ((int) ((class) / 2))
416 #define classnum_to_namedclass(classnum) ((classnum) * 2)
418 #define _invlist_union_complement_2nd(a, b, output) \
419 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
420 #define _invlist_intersection_complement_2nd(a, b, output) \
421 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
423 /* About scan_data_t.
425 During optimisation we recurse through the regexp program performing
426 various inplace (keyhole style) optimisations. In addition study_chunk
427 and scan_commit populate this data structure with information about
428 what strings MUST appear in the pattern. We look for the longest
429 string that must appear at a fixed location, and we look for the
430 longest string that may appear at a floating location. So for instance
435 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
436 strings (because they follow a .* construct). study_chunk will identify
437 both FOO and BAR as being the longest fixed and floating strings respectively.
439 The strings can be composites, for instance
443 will result in a composite fixed substring 'foo'.
445 For each string some basic information is maintained:
448 This is the position the string must appear at, or not before.
449 It also implicitly (when combined with minlenp) tells us how many
450 characters must match before the string we are searching for.
451 Likewise when combined with minlenp and the length of the string it
452 tells us how many characters must appear after the string we have
456 Only used for floating strings. This is the rightmost point that
457 the string can appear at. If set to SSize_t_MAX it indicates that the
458 string can occur infinitely far to the right.
459 For fixed strings, it is equal to min_offset.
462 A pointer to the minimum number of characters of the pattern that the
463 string was found inside. This is important as in the case of positive
464 lookahead or positive lookbehind we can have multiple patterns
469 The minimum length of the pattern overall is 3, the minimum length
470 of the lookahead part is 3, but the minimum length of the part that
471 will actually match is 1. So 'FOO's minimum length is 3, but the
472 minimum length for the F is 1. This is important as the minimum length
473 is used to determine offsets in front of and behind the string being
474 looked for. Since strings can be composites this is the length of the
475 pattern at the time it was committed with a scan_commit. Note that
476 the length is calculated by study_chunk, so that the minimum lengths
477 are not known until the full pattern has been compiled, thus the
478 pointer to the value.
482 In the case of lookbehind the string being searched for can be
483 offset past the start point of the final matching string.
484 If this value was just blithely removed from the min_offset it would
485 invalidate some of the calculations for how many chars must match
486 before or after (as they are derived from min_offset and minlen and
487 the length of the string being searched for).
488 When the final pattern is compiled and the data is moved from the
489 scan_data_t structure into the regexp structure the information
490 about lookbehind is factored in, with the information that would
491 have been lost precalculated in the end_shift field for the
494 The fields pos_min and pos_delta are used to store the minimum offset
495 and the delta to the maximum offset at the current point in the pattern.
499 struct scan_data_substrs {
500 SV *str; /* longest substring found in pattern */
501 SSize_t min_offset; /* earliest point in string it can appear */
502 SSize_t max_offset; /* latest point in string it can appear */
503 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
504 SSize_t lookbehind; /* is the pos of the string modified by LB */
505 I32 flags; /* per substring SF_* and SCF_* flags */
508 typedef struct scan_data_t {
509 /*I32 len_min; unused */
510 /*I32 len_delta; unused */
514 SSize_t last_end; /* min value, <0 unless valid. */
515 SSize_t last_start_min;
516 SSize_t last_start_max;
517 U8 cur_is_floating; /* whether the last_* values should be set as
518 * the next fixed (0) or floating (1)
521 /* [0] is longest fixed substring so far, [1] is longest float so far */
522 struct scan_data_substrs substrs[2];
524 I32 flags; /* common SF_* and SCF_* flags */
526 SSize_t *last_closep;
527 regnode_ssc *start_class;
531 * Forward declarations for pregcomp()'s friends.
534 static const scan_data_t zero_scan_data = {
535 0, 0, NULL, 0, 0, 0, 0,
537 { NULL, 0, 0, 0, 0, 0 },
538 { NULL, 0, 0, 0, 0, 0 },
545 #define SF_BEFORE_SEOL 0x0001
546 #define SF_BEFORE_MEOL 0x0002
547 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
549 #define SF_IS_INF 0x0040
550 #define SF_HAS_PAR 0x0080
551 #define SF_IN_PAR 0x0100
552 #define SF_HAS_EVAL 0x0200
555 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
556 * longest substring in the pattern. When it is not set the optimiser keeps
557 * track of position, but does not keep track of the actual strings seen,
559 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
562 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
563 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
564 * turned off because of the alternation (BRANCH). */
565 #define SCF_DO_SUBSTR 0x0400
567 #define SCF_DO_STCLASS_AND 0x0800
568 #define SCF_DO_STCLASS_OR 0x1000
569 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
570 #define SCF_WHILEM_VISITED_POS 0x2000
572 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
573 #define SCF_SEEN_ACCEPT 0x8000
574 #define SCF_TRIE_DOING_RESTUDY 0x10000
575 #define SCF_IN_DEFINE 0x20000
580 #define UTF cBOOL(RExC_utf8)
582 /* The enums for all these are ordered so things work out correctly */
583 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
584 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
585 == REGEX_DEPENDS_CHARSET)
586 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
587 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
588 >= REGEX_UNICODE_CHARSET)
589 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
590 == REGEX_ASCII_RESTRICTED_CHARSET)
591 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
592 >= REGEX_ASCII_RESTRICTED_CHARSET)
593 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
594 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
596 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
598 /* For programs that want to be strictly Unicode compatible by dying if any
599 * attempt is made to match a non-Unicode code point against a Unicode
601 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
603 #define OOB_NAMEDCLASS -1
605 /* There is no code point that is out-of-bounds, so this is problematic. But
606 * its only current use is to initialize a variable that is always set before
608 #define OOB_UNICODE 0xDEADBEEF
610 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
613 /* length of regex to show in messages that don't mark a position within */
614 #define RegexLengthToShowInErrorMessages 127
617 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
618 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
619 * op/pragma/warn/regcomp.
621 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
622 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
624 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
625 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
627 /* The code in this file in places uses one level of recursion with parsing
628 * rebased to an alternate string constructed by us in memory. This can take
629 * the form of something that is completely different from the input, or
630 * something that uses the input as part of the alternate. In the first case,
631 * there should be no possibility of an error, as we are in complete control of
632 * the alternate string. But in the second case we don't completely control
633 * the input portion, so there may be errors in that. Here's an example:
635 * is handled specially because \x{df} folds to a sequence of more than one
636 * character: 'ss'. What is done is to create and parse an alternate string,
637 * which looks like this:
638 * /(?:\x{DF}|[abc\x{DF}def])/ui
639 * where it uses the input unchanged in the middle of something it constructs,
640 * which is a branch for the DF outside the character class, and clustering
641 * parens around the whole thing. (It knows enough to skip the DF inside the
642 * class while in this substitute parse.) 'abc' and 'def' may have errors that
643 * need to be reported. The general situation looks like this:
645 * |<------- identical ------>|
647 * Input: ---------------------------------------------------------------
648 * Constructed: ---------------------------------------------------
650 * |<------- identical ------>|
652 * sI..eI is the portion of the input pattern we are concerned with here.
653 * sC..EC is the constructed substitute parse string.
654 * sC..tC is constructed by us
655 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
656 * In the diagram, these are vertically aligned.
657 * eC..EC is also constructed by us.
658 * xC is the position in the substitute parse string where we found a
660 * xI is the position in the original pattern corresponding to xC.
662 * We want to display a message showing the real input string. Thus we need to
663 * translate from xC to xI. We know that xC >= tC, since the portion of the
664 * string sC..tC has been constructed by us, and so shouldn't have errors. We
666 * xI = tI + (xC - tC)
668 * When the substitute parse is constructed, the code needs to set:
671 * RExC_copy_start_in_input (tI)
672 * RExC_copy_start_in_constructed (tC)
673 * and restore them when done.
675 * During normal processing of the input pattern, both
676 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
677 * sI, so that xC equals xI.
680 #define sI RExC_precomp
681 #define eI RExC_precomp_end
682 #define sC RExC_start
684 #define tI RExC_copy_start_in_input
685 #define tC RExC_copy_start_in_constructed
686 #define xI(xC) (tI + (xC - tC))
687 #define xI_offset(xC) (xI(xC) - sI)
689 #define REPORT_LOCATION_ARGS(xC) \
691 (xI(xC) > eI) /* Don't run off end */ \
692 ? eI - sI /* Length before the <--HERE */ \
693 : ((xI_offset(xC) >= 0) \
695 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
696 IVdf " trying to output message for " \
698 __FILE__, __LINE__, (IV) xI_offset(xC), \
699 ((int) (eC - sC)), sC), 0)), \
700 sI), /* The input pattern printed up to the <--HERE */ \
702 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
703 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
705 /* Used to point after bad bytes for an error message, but avoid skipping
706 * past a nul byte. */
707 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
709 /* Set up to clean up after our imminent demise */
710 #define PREPARE_TO_DIE \
713 SAVEFREESV(RExC_rx_sv); \
714 if (RExC_open_parens) \
715 SAVEFREEPV(RExC_open_parens); \
716 if (RExC_close_parens) \
717 SAVEFREEPV(RExC_close_parens); \
721 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
722 * arg. Show regex, up to a maximum length. If it's too long, chop and add
725 #define _FAIL(code) STMT_START { \
726 const char *ellipses = ""; \
727 IV len = RExC_precomp_end - RExC_precomp; \
730 if (len > RegexLengthToShowInErrorMessages) { \
731 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
732 len = RegexLengthToShowInErrorMessages - 10; \
738 #define FAIL(msg) _FAIL( \
739 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
740 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
742 #define FAIL2(msg,arg) _FAIL( \
743 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
744 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
747 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
749 #define Simple_vFAIL(m) STMT_START { \
750 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
751 m, REPORT_LOCATION_ARGS(RExC_parse)); \
755 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
757 #define vFAIL(m) STMT_START { \
763 * Like Simple_vFAIL(), but accepts two arguments.
765 #define Simple_vFAIL2(m,a1) STMT_START { \
766 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
767 REPORT_LOCATION_ARGS(RExC_parse)); \
771 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
773 #define vFAIL2(m,a1) STMT_START { \
775 Simple_vFAIL2(m, a1); \
780 * Like Simple_vFAIL(), but accepts three arguments.
782 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
783 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
784 REPORT_LOCATION_ARGS(RExC_parse)); \
788 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
790 #define vFAIL3(m,a1,a2) STMT_START { \
792 Simple_vFAIL3(m, a1, a2); \
796 * Like Simple_vFAIL(), but accepts four arguments.
798 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
799 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
800 REPORT_LOCATION_ARGS(RExC_parse)); \
803 #define vFAIL4(m,a1,a2,a3) STMT_START { \
805 Simple_vFAIL4(m, a1, a2, a3); \
808 /* A specialized version of vFAIL2 that works with UTF8f */
809 #define vFAIL2utf8f(m, a1) STMT_START { \
811 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
812 REPORT_LOCATION_ARGS(RExC_parse)); \
815 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
817 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
818 REPORT_LOCATION_ARGS(RExC_parse)); \
821 /* Setting this to NULL is a signal to not output warnings */
822 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
823 #define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
825 /* Since a warning can be generated multiple times as the input is reparsed, we
826 * output it the first time we come to that point in the parse, but suppress it
827 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
828 * generate any warnings */
829 #define TO_OUTPUT_WARNINGS(loc) \
830 ( RExC_copy_start_in_constructed \
831 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
833 /* After we've emitted a warning, we save the position in the input so we don't
835 #define UPDATE_WARNINGS_LOC(loc) \
837 if (TO_OUTPUT_WARNINGS(loc)) { \
838 RExC_latest_warn_offset = (xI(loc)) - RExC_precomp; \
842 /* 'warns' is the output of the packWARNx macro used in 'code' */
843 #define _WARN_HELPER(loc, warns, code) \
845 if (! RExC_copy_start_in_constructed) { \
846 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
847 " expected at '%s'", \
848 __FILE__, __LINE__, loc); \
850 if (TO_OUTPUT_WARNINGS(loc)) { \
854 UPDATE_WARNINGS_LOC(loc); \
858 /* m is not necessarily a "literal string", in this macro */
859 #define reg_warn_non_literal_string(loc, m) \
860 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
861 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
862 "%s" REPORT_LOCATION, \
863 m, REPORT_LOCATION_ARGS(loc)))
865 #define ckWARNreg(loc,m) \
866 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
867 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
869 REPORT_LOCATION_ARGS(loc)))
871 #define vWARN(loc, m) \
872 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
873 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
875 REPORT_LOCATION_ARGS(loc))) \
877 #define vWARN_dep(loc, m) \
878 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
879 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
881 REPORT_LOCATION_ARGS(loc)))
883 #define ckWARNdep(loc,m) \
884 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
885 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
887 REPORT_LOCATION_ARGS(loc)))
889 #define ckWARNregdep(loc,m) \
890 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
891 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
894 REPORT_LOCATION_ARGS(loc)))
896 #define ckWARN2reg_d(loc,m, a1) \
897 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
898 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
900 a1, REPORT_LOCATION_ARGS(loc)))
902 #define ckWARN2reg(loc, m, a1) \
903 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
904 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
906 a1, REPORT_LOCATION_ARGS(loc)))
908 #define vWARN3(loc, m, a1, a2) \
909 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
910 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
912 a1, a2, REPORT_LOCATION_ARGS(loc)))
914 #define ckWARN3reg(loc, m, a1, a2) \
915 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
916 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
919 REPORT_LOCATION_ARGS(loc)))
921 #define vWARN4(loc, m, a1, a2, a3) \
922 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
923 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
926 REPORT_LOCATION_ARGS(loc)))
928 #define ckWARN4reg(loc, m, a1, a2, a3) \
929 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
930 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
933 REPORT_LOCATION_ARGS(loc)))
935 #define vWARN5(loc, m, a1, a2, a3, a4) \
936 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
937 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
940 REPORT_LOCATION_ARGS(loc)))
942 #define ckWARNexperimental(loc, class, m) \
943 _WARN_HELPER(loc, packWARN(class), \
944 Perl_ck_warner_d(aTHX_ packWARN(class), \
946 REPORT_LOCATION_ARGS(loc)))
948 /* Convert between a pointer to a node and its offset from the beginning of the
950 #define REGNODE_p(offset) (RExC_emit_start + (offset))
951 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
953 /* Macros for recording node offsets. 20001227 mjd@plover.com
954 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
955 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
956 * Element 0 holds the number n.
957 * Position is 1 indexed.
959 #ifndef RE_TRACK_PATTERN_OFFSETS
960 #define Set_Node_Offset_To_R(offset,byte)
961 #define Set_Node_Offset(node,byte)
962 #define Set_Cur_Node_Offset
963 #define Set_Node_Length_To_R(node,len)
964 #define Set_Node_Length(node,len)
965 #define Set_Node_Cur_Length(node,start)
966 #define Node_Offset(n)
967 #define Node_Length(n)
968 #define Set_Node_Offset_Length(node,offset,len)
969 #define ProgLen(ri) ri->u.proglen
970 #define SetProgLen(ri,x) ri->u.proglen = x
971 #define Track_Code(code)
973 #define ProgLen(ri) ri->u.offsets[0]
974 #define SetProgLen(ri,x) ri->u.offsets[0] = x
975 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
976 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
977 __LINE__, (int)(offset), (int)(byte))); \
979 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
982 RExC_offsets[2*(offset)-1] = (byte); \
986 #define Set_Node_Offset(node,byte) \
987 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
988 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
990 #define Set_Node_Length_To_R(node,len) STMT_START { \
991 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
992 __LINE__, (int)(node), (int)(len))); \
994 Perl_croak(aTHX_ "value of node is %d in Length macro", \
997 RExC_offsets[2*(node)] = (len); \
1001 #define Set_Node_Length(node,len) \
1002 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1003 #define Set_Node_Cur_Length(node, start) \
1004 Set_Node_Length(node, RExC_parse - start)
1006 /* Get offsets and lengths */
1007 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1008 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1010 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1011 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1012 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1015 #define Track_Code(code) STMT_START { code } STMT_END
1018 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1019 #define EXPERIMENTAL_INPLACESCAN
1020 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1024 Perl_re_printf(pTHX_ const char *fmt, ...)
1028 PerlIO *f= Perl_debug_log;
1029 PERL_ARGS_ASSERT_RE_PRINTF;
1031 result = PerlIO_vprintf(f, fmt, ap);
1037 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1041 PerlIO *f= Perl_debug_log;
1042 PERL_ARGS_ASSERT_RE_INDENTF;
1043 va_start(ap, depth);
1044 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1045 result = PerlIO_vprintf(f, fmt, ap);
1049 #endif /* DEBUGGING */
1051 #define DEBUG_RExC_seen() \
1052 DEBUG_OPTIMISE_MORE_r({ \
1053 Perl_re_printf( aTHX_ "RExC_seen: "); \
1055 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1056 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1058 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1059 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1061 if (RExC_seen & REG_GPOS_SEEN) \
1062 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1064 if (RExC_seen & REG_RECURSE_SEEN) \
1065 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1067 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1068 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1070 if (RExC_seen & REG_VERBARG_SEEN) \
1071 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1073 if (RExC_seen & REG_CUTGROUP_SEEN) \
1074 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1076 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1077 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1079 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1080 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1082 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1083 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1085 Perl_re_printf( aTHX_ "\n"); \
1088 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1089 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1094 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1095 const char *close_str)
1100 Perl_re_printf( aTHX_ "%s", open_str);
1101 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1102 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1103 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1104 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1105 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1106 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1107 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1108 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1109 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1110 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1111 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1112 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1113 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1114 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1115 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1116 Perl_re_printf( aTHX_ "%s", close_str);
1121 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1122 U32 depth, int is_inf)
1124 GET_RE_DEBUG_FLAGS_DECL;
1126 DEBUG_OPTIMISE_MORE_r({
1129 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1133 (IV)data->pos_delta,
1137 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1139 Perl_re_printf( aTHX_
1140 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1142 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1143 is_inf ? "INF " : ""
1146 if (data->last_found) {
1148 Perl_re_printf(aTHX_
1149 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1150 SvPVX_const(data->last_found),
1152 (IV)data->last_start_min,
1153 (IV)data->last_start_max
1156 for (i = 0; i < 2; i++) {
1157 Perl_re_printf(aTHX_
1158 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1159 data->cur_is_floating == i ? "*" : "",
1160 i ? "Float" : "Fixed",
1161 SvPVX_const(data->substrs[i].str),
1162 (IV)data->substrs[i].min_offset,
1163 (IV)data->substrs[i].max_offset
1165 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1169 Perl_re_printf( aTHX_ "\n");
1175 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1176 regnode *scan, U32 depth, U32 flags)
1178 GET_RE_DEBUG_FLAGS_DECL;
1185 Next = regnext(scan);
1186 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1187 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1190 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1191 Next ? (REG_NODE_NUM(Next)) : 0 );
1192 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1193 Perl_re_printf( aTHX_ "\n");
1198 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1199 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1201 # define DEBUG_PEEP(str, scan, depth, flags) \
1202 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1205 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1206 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1210 /* =========================================================
1211 * BEGIN edit_distance stuff.
1213 * This calculates how many single character changes of any type are needed to
1214 * transform a string into another one. It is taken from version 3.1 of
1216 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1219 /* Our unsorted dictionary linked list. */
1220 /* Note we use UVs, not chars. */
1225 struct dictionary* next;
1227 typedef struct dictionary item;
1230 PERL_STATIC_INLINE item*
1231 push(UV key, item* curr)
1234 Newx(head, 1, item);
1242 PERL_STATIC_INLINE item*
1243 find(item* head, UV key)
1245 item* iterator = head;
1247 if (iterator->key == key){
1250 iterator = iterator->next;
1256 PERL_STATIC_INLINE item*
1257 uniquePush(item* head, UV key)
1259 item* iterator = head;
1262 if (iterator->key == key) {
1265 iterator = iterator->next;
1268 return push(key, head);
1271 PERL_STATIC_INLINE void
1272 dict_free(item* head)
1274 item* iterator = head;
1277 item* temp = iterator;
1278 iterator = iterator->next;
1285 /* End of Dictionary Stuff */
1287 /* All calculations/work are done here */
1289 S_edit_distance(const UV* src,
1291 const STRLEN x, /* length of src[] */
1292 const STRLEN y, /* length of tgt[] */
1293 const SSize_t maxDistance
1297 UV swapCount, swapScore, targetCharCount, i, j;
1299 UV score_ceil = x + y;
1301 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1303 /* intialize matrix start values */
1304 Newx(scores, ( (x + 2) * (y + 2)), UV);
1305 scores[0] = score_ceil;
1306 scores[1 * (y + 2) + 0] = score_ceil;
1307 scores[0 * (y + 2) + 1] = score_ceil;
1308 scores[1 * (y + 2) + 1] = 0;
1309 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1314 for (i=1;i<=x;i++) {
1316 head = uniquePush(head, src[i]);
1317 scores[(i+1) * (y + 2) + 1] = i;
1318 scores[(i+1) * (y + 2) + 0] = score_ceil;
1321 for (j=1;j<=y;j++) {
1324 head = uniquePush(head, tgt[j]);
1325 scores[1 * (y + 2) + (j + 1)] = j;
1326 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1329 targetCharCount = find(head, tgt[j-1])->value;
1330 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1332 if (src[i-1] != tgt[j-1]){
1333 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));
1337 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1341 find(head, src[i-1])->value = i;
1345 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1348 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1352 /* END of edit_distance() stuff
1353 * ========================================================= */
1355 /* is c a control character for which we have a mnemonic? */
1356 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1359 S_cntrl_to_mnemonic(const U8 c)
1361 /* Returns the mnemonic string that represents character 'c', if one
1362 * exists; NULL otherwise. The only ones that exist for the purposes of
1363 * this routine are a few control characters */
1366 case '\a': return "\\a";
1367 case '\b': return "\\b";
1368 case ESC_NATIVE: return "\\e";
1369 case '\f': return "\\f";
1370 case '\n': return "\\n";
1371 case '\r': return "\\r";
1372 case '\t': return "\\t";
1378 /* Mark that we cannot extend a found fixed substring at this point.
1379 Update the longest found anchored substring or the longest found
1380 floating substrings if needed. */
1383 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1384 SSize_t *minlenp, int is_inf)
1386 const STRLEN l = CHR_SVLEN(data->last_found);
1387 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1388 const STRLEN old_l = CHR_SVLEN(longest_sv);
1389 GET_RE_DEBUG_FLAGS_DECL;
1391 PERL_ARGS_ASSERT_SCAN_COMMIT;
1393 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1394 const U8 i = data->cur_is_floating;
1395 SvSetMagicSV(longest_sv, data->last_found);
1396 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1399 data->substrs[0].max_offset = data->substrs[0].min_offset;
1401 data->substrs[1].max_offset = (l
1402 ? data->last_start_max
1403 : (data->pos_delta > SSize_t_MAX - data->pos_min
1405 : data->pos_min + data->pos_delta));
1407 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1408 data->substrs[1].max_offset = SSize_t_MAX;
1411 if (data->flags & SF_BEFORE_EOL)
1412 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1414 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1415 data->substrs[i].minlenp = minlenp;
1416 data->substrs[i].lookbehind = 0;
1419 SvCUR_set(data->last_found, 0);
1421 SV * const sv = data->last_found;
1422 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1423 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1428 data->last_end = -1;
1429 data->flags &= ~SF_BEFORE_EOL;
1430 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1433 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1434 * list that describes which code points it matches */
1437 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1439 /* Set the SSC 'ssc' to match an empty string or any code point */
1441 PERL_ARGS_ASSERT_SSC_ANYTHING;
1443 assert(is_ANYOF_SYNTHETIC(ssc));
1445 /* mortalize so won't leak */
1446 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1447 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1451 S_ssc_is_anything(const regnode_ssc *ssc)
1453 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1454 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1455 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1456 * in any way, so there's no point in using it */
1461 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1463 assert(is_ANYOF_SYNTHETIC(ssc));
1465 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1469 /* See if the list consists solely of the range 0 - Infinity */
1470 invlist_iterinit(ssc->invlist);
1471 ret = invlist_iternext(ssc->invlist, &start, &end)
1475 invlist_iterfinish(ssc->invlist);
1481 /* If e.g., both \w and \W are set, matches everything */
1482 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1484 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1485 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1495 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1497 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1498 * string, any code point, or any posix class under locale */
1500 PERL_ARGS_ASSERT_SSC_INIT;
1502 Zero(ssc, 1, regnode_ssc);
1503 set_ANYOF_SYNTHETIC(ssc);
1504 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1507 /* If any portion of the regex is to operate under locale rules that aren't
1508 * fully known at compile time, initialization includes it. The reason
1509 * this isn't done for all regexes is that the optimizer was written under
1510 * the assumption that locale was all-or-nothing. Given the complexity and
1511 * lack of documentation in the optimizer, and that there are inadequate
1512 * test cases for locale, many parts of it may not work properly, it is
1513 * safest to avoid locale unless necessary. */
1514 if (RExC_contains_locale) {
1515 ANYOF_POSIXL_SETALL(ssc);
1518 ANYOF_POSIXL_ZERO(ssc);
1523 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1524 const regnode_ssc *ssc)
1526 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1527 * to the list of code points matched, and locale posix classes; hence does
1528 * not check its flags) */
1533 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1535 assert(is_ANYOF_SYNTHETIC(ssc));
1537 invlist_iterinit(ssc->invlist);
1538 ret = invlist_iternext(ssc->invlist, &start, &end)
1542 invlist_iterfinish(ssc->invlist);
1548 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1555 #define INVLIST_INDEX 0
1556 #define ONLY_LOCALE_MATCHES_INDEX 1
1557 #define DEFERRED_USER_DEFINED_INDEX 2
1560 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1561 const regnode_charclass* const node)
1563 /* Returns a mortal inversion list defining which code points are matched
1564 * by 'node', which is of type ANYOF. Handles complementing the result if
1565 * appropriate. If some code points aren't knowable at this time, the
1566 * returned list must, and will, contain every code point that is a
1571 SV* only_utf8_locale_invlist = NULL;
1573 const U32 n = ARG(node);
1574 bool new_node_has_latin1 = FALSE;
1576 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1578 /* Look at the data structure created by S_set_ANYOF_arg() */
1579 if (n != ANYOF_ONLY_HAS_BITMAP) {
1580 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1581 AV * const av = MUTABLE_AV(SvRV(rv));
1582 SV **const ary = AvARRAY(av);
1583 assert(RExC_rxi->data->what[n] == 's');
1585 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1587 /* Here there are things that won't be known until runtime -- we
1588 * have to assume it could be anything */
1589 invlist = sv_2mortal(_new_invlist(1));
1590 return _add_range_to_invlist(invlist, 0, UV_MAX);
1592 else if (ary[INVLIST_INDEX]) {
1594 /* Use the node's inversion list */
1595 invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1598 /* Get the code points valid only under UTF-8 locales */
1599 if ( (ANYOF_FLAGS(node) & ANYOFL_FOLD)
1600 && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1602 only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1607 invlist = sv_2mortal(_new_invlist(0));
1610 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1611 * code points, and an inversion list for the others, but if there are code
1612 * points that should match only conditionally on the target string being
1613 * UTF-8, those are placed in the inversion list, and not the bitmap.
1614 * Since there are circumstances under which they could match, they are
1615 * included in the SSC. But if the ANYOF node is to be inverted, we have
1616 * to exclude them here, so that when we invert below, the end result
1617 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1618 * have to do this here before we add the unconditionally matched code
1620 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1621 _invlist_intersection_complement_2nd(invlist,
1626 /* Add in the points from the bit map */
1627 if (OP(node) != ANYOFH) {
1628 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1629 if (ANYOF_BITMAP_TEST(node, i)) {
1630 unsigned int start = i++;
1632 for (; i < NUM_ANYOF_CODE_POINTS
1633 && ANYOF_BITMAP_TEST(node, i); ++i)
1637 invlist = _add_range_to_invlist(invlist, start, i-1);
1638 new_node_has_latin1 = TRUE;
1643 /* If this can match all upper Latin1 code points, have to add them
1644 * as well. But don't add them if inverting, as when that gets done below,
1645 * it would exclude all these characters, including the ones it shouldn't
1646 * that were added just above */
1647 if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1648 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1650 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1653 /* Similarly for these */
1654 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1655 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1658 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1659 _invlist_invert(invlist);
1661 else if (ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1662 if (new_node_has_latin1) {
1664 /* Under /li, any 0-255 could fold to any other 0-255, depending on
1665 * the locale. We can skip this if there are no 0-255 at all. */
1666 _invlist_union(invlist, PL_Latin1, &invlist);
1668 invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1669 invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1672 if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1673 invlist = add_cp_to_invlist(invlist, 'I');
1675 if (_invlist_contains_cp(invlist,
1676 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1678 invlist = add_cp_to_invlist(invlist, 'i');
1683 /* Similarly add the UTF-8 locale possible matches. These have to be
1684 * deferred until after the non-UTF-8 locale ones are taken care of just
1685 * above, or it leads to wrong results under ANYOF_INVERT */
1686 if (only_utf8_locale_invlist) {
1687 _invlist_union_maybe_complement_2nd(invlist,
1688 only_utf8_locale_invlist,
1689 ANYOF_FLAGS(node) & ANYOF_INVERT,
1696 /* These two functions currently do the exact same thing */
1697 #define ssc_init_zero ssc_init
1699 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1700 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1702 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1703 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1704 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1707 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1708 const regnode_charclass *and_with)
1710 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1711 * another SSC or a regular ANYOF class. Can create false positives. */
1716 PERL_ARGS_ASSERT_SSC_AND;
1718 assert(is_ANYOF_SYNTHETIC(ssc));
1720 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1721 * the code point inversion list and just the relevant flags */
1722 if (is_ANYOF_SYNTHETIC(and_with)) {
1723 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1724 anded_flags = ANYOF_FLAGS(and_with);
1726 /* XXX This is a kludge around what appears to be deficiencies in the
1727 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1728 * there are paths through the optimizer where it doesn't get weeded
1729 * out when it should. And if we don't make some extra provision for
1730 * it like the code just below, it doesn't get added when it should.
1731 * This solution is to add it only when AND'ing, which is here, and
1732 * only when what is being AND'ed is the pristine, original node
1733 * matching anything. Thus it is like adding it to ssc_anything() but
1734 * only when the result is to be AND'ed. Probably the same solution
1735 * could be adopted for the same problem we have with /l matching,
1736 * which is solved differently in S_ssc_init(), and that would lead to
1737 * fewer false positives than that solution has. But if this solution
1738 * creates bugs, the consequences are only that a warning isn't raised
1739 * that should be; while the consequences for having /l bugs is
1740 * incorrect matches */
1741 if (ssc_is_anything((regnode_ssc *)and_with)) {
1742 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1746 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1747 if (OP(and_with) == ANYOFD) {
1748 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1751 anded_flags = ANYOF_FLAGS(and_with)
1752 &( ANYOF_COMMON_FLAGS
1753 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1754 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1755 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1757 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1762 ANYOF_FLAGS(ssc) &= anded_flags;
1764 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1765 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1766 * 'and_with' may be inverted. When not inverted, we have the situation of
1768 * (C1 | P1) & (C2 | P2)
1769 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1770 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1771 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1772 * <= ((C1 & C2) | P1 | P2)
1773 * Alternatively, the last few steps could be:
1774 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1775 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1776 * <= (C1 | C2 | (P1 & P2))
1777 * We favor the second approach if either P1 or P2 is non-empty. This is
1778 * because these components are a barrier to doing optimizations, as what
1779 * they match cannot be known until the moment of matching as they are
1780 * dependent on the current locale, 'AND"ing them likely will reduce or
1782 * But we can do better if we know that C1,P1 are in their initial state (a
1783 * frequent occurrence), each matching everything:
1784 * (<everything>) & (C2 | P2) = C2 | P2
1785 * Similarly, if C2,P2 are in their initial state (again a frequent
1786 * occurrence), the result is a no-op
1787 * (C1 | P1) & (<everything>) = C1 | P1
1790 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1791 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1792 * <= (C1 & ~C2) | (P1 & ~P2)
1795 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1796 && ! is_ANYOF_SYNTHETIC(and_with))
1800 ssc_intersection(ssc,
1802 FALSE /* Has already been inverted */
1805 /* If either P1 or P2 is empty, the intersection will be also; can skip
1807 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1808 ANYOF_POSIXL_ZERO(ssc);
1810 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1812 /* Note that the Posix class component P from 'and_with' actually
1814 * P = Pa | Pb | ... | Pn
1815 * where each component is one posix class, such as in [\w\s].
1817 * ~P = ~(Pa | Pb | ... | Pn)
1818 * = ~Pa & ~Pb & ... & ~Pn
1819 * <= ~Pa | ~Pb | ... | ~Pn
1820 * The last is something we can easily calculate, but unfortunately
1821 * is likely to have many false positives. We could do better
1822 * in some (but certainly not all) instances if two classes in
1823 * P have known relationships. For example
1824 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1826 * :lower: & :print: = :lower:
1827 * And similarly for classes that must be disjoint. For example,
1828 * since \s and \w can have no elements in common based on rules in
1829 * the POSIX standard,
1830 * \w & ^\S = nothing
1831 * Unfortunately, some vendor locales do not meet the Posix
1832 * standard, in particular almost everything by Microsoft.
1833 * The loop below just changes e.g., \w into \W and vice versa */
1835 regnode_charclass_posixl temp;
1836 int add = 1; /* To calculate the index of the complement */
1838 Zero(&temp, 1, regnode_charclass_posixl);
1839 ANYOF_POSIXL_ZERO(&temp);
1840 for (i = 0; i < ANYOF_MAX; i++) {
1842 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1843 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1845 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1846 ANYOF_POSIXL_SET(&temp, i + add);
1848 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1850 ANYOF_POSIXL_AND(&temp, ssc);
1852 } /* else ssc already has no posixes */
1853 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1854 in its initial state */
1855 else if (! is_ANYOF_SYNTHETIC(and_with)
1856 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1858 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1859 * copy it over 'ssc' */
1860 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1861 if (is_ANYOF_SYNTHETIC(and_with)) {
1862 StructCopy(and_with, ssc, regnode_ssc);
1865 ssc->invlist = anded_cp_list;
1866 ANYOF_POSIXL_ZERO(ssc);
1867 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1868 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1872 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1873 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1875 /* One or the other of P1, P2 is non-empty. */
1876 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1877 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1879 ssc_union(ssc, anded_cp_list, FALSE);
1881 else { /* P1 = P2 = empty */
1882 ssc_intersection(ssc, anded_cp_list, FALSE);
1888 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1889 const regnode_charclass *or_with)
1891 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1892 * another SSC or a regular ANYOF class. Can create false positives if
1893 * 'or_with' is to be inverted. */
1898 PERL_ARGS_ASSERT_SSC_OR;
1900 assert(is_ANYOF_SYNTHETIC(ssc));
1902 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1903 * the code point inversion list and just the relevant flags */
1904 if (is_ANYOF_SYNTHETIC(or_with)) {
1905 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1906 ored_flags = ANYOF_FLAGS(or_with);
1909 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1910 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1911 if (OP(or_with) != ANYOFD) {
1913 |= ANYOF_FLAGS(or_with)
1914 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1915 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1916 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1918 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1923 ANYOF_FLAGS(ssc) |= ored_flags;
1925 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1926 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1927 * 'or_with' may be inverted. When not inverted, we have the simple
1928 * situation of computing:
1929 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1930 * If P1|P2 yields a situation with both a class and its complement are
1931 * set, like having both \w and \W, this matches all code points, and we
1932 * can delete these from the P component of the ssc going forward. XXX We
1933 * might be able to delete all the P components, but I (khw) am not certain
1934 * about this, and it is better to be safe.
1937 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1938 * <= (C1 | P1) | ~C2
1939 * <= (C1 | ~C2) | P1
1940 * (which results in actually simpler code than the non-inverted case)
1943 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1944 && ! is_ANYOF_SYNTHETIC(or_with))
1946 /* We ignore P2, leaving P1 going forward */
1947 } /* else Not inverted */
1948 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1949 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1950 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1952 for (i = 0; i < ANYOF_MAX; i += 2) {
1953 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1955 ssc_match_all_cp(ssc);
1956 ANYOF_POSIXL_CLEAR(ssc, i);
1957 ANYOF_POSIXL_CLEAR(ssc, i+1);
1965 FALSE /* Already has been inverted */
1969 PERL_STATIC_INLINE void
1970 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1972 PERL_ARGS_ASSERT_SSC_UNION;
1974 assert(is_ANYOF_SYNTHETIC(ssc));
1976 _invlist_union_maybe_complement_2nd(ssc->invlist,
1982 PERL_STATIC_INLINE void
1983 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1985 const bool invert2nd)
1987 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1989 assert(is_ANYOF_SYNTHETIC(ssc));
1991 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1997 PERL_STATIC_INLINE void
1998 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2000 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2002 assert(is_ANYOF_SYNTHETIC(ssc));
2004 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2007 PERL_STATIC_INLINE void
2008 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2010 /* AND just the single code point 'cp' into the SSC 'ssc' */
2012 SV* cp_list = _new_invlist(2);
2014 PERL_ARGS_ASSERT_SSC_CP_AND;
2016 assert(is_ANYOF_SYNTHETIC(ssc));
2018 cp_list = add_cp_to_invlist(cp_list, cp);
2019 ssc_intersection(ssc, cp_list,
2020 FALSE /* Not inverted */
2022 SvREFCNT_dec_NN(cp_list);
2025 PERL_STATIC_INLINE void
2026 S_ssc_clear_locale(regnode_ssc *ssc)
2028 /* Set the SSC 'ssc' to not match any locale things */
2029 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2031 assert(is_ANYOF_SYNTHETIC(ssc));
2033 ANYOF_POSIXL_ZERO(ssc);
2034 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2037 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2040 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2042 /* The synthetic start class is used to hopefully quickly winnow down
2043 * places where a pattern could start a match in the target string. If it
2044 * doesn't really narrow things down that much, there isn't much point to
2045 * having the overhead of using it. This function uses some very crude
2046 * heuristics to decide if to use the ssc or not.
2048 * It returns TRUE if 'ssc' rules out more than half what it considers to
2049 * be the "likely" possible matches, but of course it doesn't know what the
2050 * actual things being matched are going to be; these are only guesses
2052 * For /l matches, it assumes that the only likely matches are going to be
2053 * in the 0-255 range, uniformly distributed, so half of that is 127
2054 * For /a and /d matches, it assumes that the likely matches will be just
2055 * the ASCII range, so half of that is 63
2056 * For /u and there isn't anything matching above the Latin1 range, it
2057 * assumes that that is the only range likely to be matched, and uses
2058 * half that as the cut-off: 127. If anything matches above Latin1,
2059 * it assumes that all of Unicode could match (uniformly), except for
2060 * non-Unicode code points and things in the General Category "Other"
2061 * (unassigned, private use, surrogates, controls and formats). This
2062 * is a much large number. */
2064 U32 count = 0; /* Running total of number of code points matched by
2066 UV start, end; /* Start and end points of current range in inversion
2067 XXX outdated. UTF-8 locales are common, what about invert? list */
2068 const U32 max_code_points = (LOC)
2070 : (( ! UNI_SEMANTICS
2071 || invlist_highest(ssc->invlist) < 256)
2074 const U32 max_match = max_code_points / 2;
2076 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2078 invlist_iterinit(ssc->invlist);
2079 while (invlist_iternext(ssc->invlist, &start, &end)) {
2080 if (start >= max_code_points) {
2083 end = MIN(end, max_code_points - 1);
2084 count += end - start + 1;
2085 if (count >= max_match) {
2086 invlist_iterfinish(ssc->invlist);
2096 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2098 /* The inversion list in the SSC is marked mortal; now we need a more
2099 * permanent copy, which is stored the same way that is done in a regular
2100 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2103 SV* invlist = invlist_clone(ssc->invlist, NULL);
2105 PERL_ARGS_ASSERT_SSC_FINALIZE;
2107 assert(is_ANYOF_SYNTHETIC(ssc));
2109 /* The code in this file assumes that all but these flags aren't relevant
2110 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2111 * by the time we reach here */
2112 assert(! (ANYOF_FLAGS(ssc)
2113 & ~( ANYOF_COMMON_FLAGS
2114 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2115 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2117 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2119 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2121 /* Make sure is clone-safe */
2122 ssc->invlist = NULL;
2124 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2125 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2126 OP(ssc) = ANYOFPOSIXL;
2128 else if (RExC_contains_locale) {
2132 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2135 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2136 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2137 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2138 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2139 ? (TRIE_LIST_CUR( idx ) - 1) \
2145 dump_trie(trie,widecharmap,revcharmap)
2146 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2147 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2149 These routines dump out a trie in a somewhat readable format.
2150 The _interim_ variants are used for debugging the interim
2151 tables that are used to generate the final compressed
2152 representation which is what dump_trie expects.
2154 Part of the reason for their existence is to provide a form
2155 of documentation as to how the different representations function.
2160 Dumps the final compressed table form of the trie to Perl_debug_log.
2161 Used for debugging make_trie().
2165 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2166 AV *revcharmap, U32 depth)
2169 SV *sv=sv_newmortal();
2170 int colwidth= widecharmap ? 6 : 4;
2172 GET_RE_DEBUG_FLAGS_DECL;
2174 PERL_ARGS_ASSERT_DUMP_TRIE;
2176 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2177 depth+1, "Match","Base","Ofs" );
2179 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2180 SV ** const tmp = av_fetch( revcharmap, state, 0);
2182 Perl_re_printf( aTHX_ "%*s",
2184 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2185 PL_colors[0], PL_colors[1],
2186 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2187 PERL_PV_ESCAPE_FIRSTCHAR
2192 Perl_re_printf( aTHX_ "\n");
2193 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2195 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2196 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2197 Perl_re_printf( aTHX_ "\n");
2199 for( state = 1 ; state < trie->statecount ; state++ ) {
2200 const U32 base = trie->states[ state ].trans.base;
2202 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2204 if ( trie->states[ state ].wordnum ) {
2205 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2207 Perl_re_printf( aTHX_ "%6s", "" );
2210 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2215 while( ( base + ofs < trie->uniquecharcount ) ||
2216 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2217 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2221 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2223 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2224 if ( ( base + ofs >= trie->uniquecharcount )
2225 && ( base + ofs - trie->uniquecharcount
2227 && trie->trans[ base + ofs
2228 - trie->uniquecharcount ].check == state )
2230 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2231 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2234 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2238 Perl_re_printf( aTHX_ "]");
2241 Perl_re_printf( aTHX_ "\n" );
2243 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2245 for (word=1; word <= trie->wordcount; word++) {
2246 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2247 (int)word, (int)(trie->wordinfo[word].prev),
2248 (int)(trie->wordinfo[word].len));
2250 Perl_re_printf( aTHX_ "\n" );
2253 Dumps a fully constructed but uncompressed trie in list form.
2254 List tries normally only are used for construction when the number of
2255 possible chars (trie->uniquecharcount) is very high.
2256 Used for debugging make_trie().
2259 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2260 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2264 SV *sv=sv_newmortal();
2265 int colwidth= widecharmap ? 6 : 4;
2266 GET_RE_DEBUG_FLAGS_DECL;
2268 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2270 /* print out the table precompression. */
2271 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2273 Perl_re_indentf( aTHX_ "%s",
2274 depth+1, "------:-----+-----------------\n" );
2276 for( state=1 ; state < next_alloc ; state ++ ) {
2279 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2280 depth+1, (UV)state );
2281 if ( ! trie->states[ state ].wordnum ) {
2282 Perl_re_printf( aTHX_ "%5s| ","");
2284 Perl_re_printf( aTHX_ "W%4x| ",
2285 trie->states[ state ].wordnum
2288 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2289 SV ** const tmp = av_fetch( revcharmap,
2290 TRIE_LIST_ITEM(state, charid).forid, 0);
2292 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2294 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2296 PL_colors[0], PL_colors[1],
2297 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2298 | PERL_PV_ESCAPE_FIRSTCHAR
2300 TRIE_LIST_ITEM(state, charid).forid,
2301 (UV)TRIE_LIST_ITEM(state, charid).newstate
2304 Perl_re_printf( aTHX_ "\n%*s| ",
2305 (int)((depth * 2) + 14), "");
2308 Perl_re_printf( aTHX_ "\n");
2313 Dumps a fully constructed but uncompressed trie in table form.
2314 This is the normal DFA style state transition table, with a few
2315 twists to facilitate compression later.
2316 Used for debugging make_trie().
2319 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2320 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2325 SV *sv=sv_newmortal();
2326 int colwidth= widecharmap ? 6 : 4;
2327 GET_RE_DEBUG_FLAGS_DECL;
2329 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2332 print out the table precompression so that we can do a visual check
2333 that they are identical.
2336 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2338 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2339 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2341 Perl_re_printf( aTHX_ "%*s",
2343 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2344 PL_colors[0], PL_colors[1],
2345 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2346 PERL_PV_ESCAPE_FIRSTCHAR
2352 Perl_re_printf( aTHX_ "\n");
2353 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2355 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2356 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2359 Perl_re_printf( aTHX_ "\n" );
2361 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2363 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2365 (UV)TRIE_NODENUM( state ) );
2367 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2368 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2370 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2372 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2374 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2375 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2376 (UV)trie->trans[ state ].check );
2378 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2379 (UV)trie->trans[ state ].check,
2380 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2388 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2389 startbranch: the first branch in the whole branch sequence
2390 first : start branch of sequence of branch-exact nodes.
2391 May be the same as startbranch
2392 last : Thing following the last branch.
2393 May be the same as tail.
2394 tail : item following the branch sequence
2395 count : words in the sequence
2396 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2397 depth : indent depth
2399 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2401 A trie is an N'ary tree where the branches are determined by digital
2402 decomposition of the key. IE, at the root node you look up the 1st character and
2403 follow that branch repeat until you find the end of the branches. Nodes can be
2404 marked as "accepting" meaning they represent a complete word. Eg:
2408 would convert into the following structure. Numbers represent states, letters
2409 following numbers represent valid transitions on the letter from that state, if
2410 the number is in square brackets it represents an accepting state, otherwise it
2411 will be in parenthesis.
2413 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2417 (1) +-i->(6)-+-s->[7]
2419 +-s->(3)-+-h->(4)-+-e->[5]
2421 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2423 This shows that when matching against the string 'hers' we will begin at state 1
2424 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2425 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2426 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2427 single traverse. We store a mapping from accepting to state to which word was
2428 matched, and then when we have multiple possibilities we try to complete the
2429 rest of the regex in the order in which they occurred in the alternation.
2431 The only prior NFA like behaviour that would be changed by the TRIE support is
2432 the silent ignoring of duplicate alternations which are of the form:
2434 / (DUPE|DUPE) X? (?{ ... }) Y /x
2436 Thus EVAL blocks following a trie may be called a different number of times with
2437 and without the optimisation. With the optimisations dupes will be silently
2438 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2439 the following demonstrates:
2441 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2443 which prints out 'word' three times, but
2445 'words'=~/(word|word|word)(?{ print $1 })S/
2447 which doesnt print it out at all. This is due to other optimisations kicking in.
2449 Example of what happens on a structural level:
2451 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2453 1: CURLYM[1] {1,32767}(18)
2464 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2465 and should turn into:
2467 1: CURLYM[1] {1,32767}(18)
2469 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2477 Cases where tail != last would be like /(?foo|bar)baz/:
2487 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2488 and would end up looking like:
2491 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2498 d = uvchr_to_utf8_flags(d, uv, 0);
2500 is the recommended Unicode-aware way of saying
2505 #define TRIE_STORE_REVCHAR(val) \
2508 SV *zlopp = newSV(UTF8_MAXBYTES); \
2509 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2510 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2511 SvCUR_set(zlopp, kapow - flrbbbbb); \
2514 av_push(revcharmap, zlopp); \
2516 char ooooff = (char)val; \
2517 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2521 /* This gets the next character from the input, folding it if not already
2523 #define TRIE_READ_CHAR STMT_START { \
2526 /* if it is UTF then it is either already folded, or does not need \
2528 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2530 else if (folder == PL_fold_latin1) { \
2531 /* This folder implies Unicode rules, which in the range expressible \
2532 * by not UTF is the lower case, with the two exceptions, one of \
2533 * which should have been taken care of before calling this */ \
2534 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2535 uvc = toLOWER_L1(*uc); \
2536 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2539 /* raw data, will be folded later if needed */ \
2547 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2548 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2549 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2550 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2551 TRIE_LIST_LEN( state ) = ging; \
2553 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2554 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2555 TRIE_LIST_CUR( state )++; \
2558 #define TRIE_LIST_NEW(state) STMT_START { \
2559 Newx( trie->states[ state ].trans.list, \
2560 4, reg_trie_trans_le ); \
2561 TRIE_LIST_CUR( state ) = 1; \
2562 TRIE_LIST_LEN( state ) = 4; \
2565 #define TRIE_HANDLE_WORD(state) STMT_START { \
2566 U16 dupe= trie->states[ state ].wordnum; \
2567 regnode * const noper_next = regnext( noper ); \
2570 /* store the word for dumping */ \
2572 if (OP(noper) != NOTHING) \
2573 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2575 tmp = newSVpvn_utf8( "", 0, UTF ); \
2576 av_push( trie_words, tmp ); \
2580 trie->wordinfo[curword].prev = 0; \
2581 trie->wordinfo[curword].len = wordlen; \
2582 trie->wordinfo[curword].accept = state; \
2584 if ( noper_next < tail ) { \
2586 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2588 trie->jump[curword] = (U16)(noper_next - convert); \
2590 jumper = noper_next; \
2592 nextbranch= regnext(cur); \
2596 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2597 /* chain, so that when the bits of chain are later */\
2598 /* linked together, the dups appear in the chain */\
2599 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2600 trie->wordinfo[dupe].prev = curword; \
2602 /* we haven't inserted this word yet. */ \
2603 trie->states[ state ].wordnum = curword; \
2608 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2609 ( ( base + charid >= ucharcount \
2610 && base + charid < ubound \
2611 && state == trie->trans[ base - ucharcount + charid ].check \
2612 && trie->trans[ base - ucharcount + charid ].next ) \
2613 ? trie->trans[ base - ucharcount + charid ].next \
2614 : ( state==1 ? special : 0 ) \
2617 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2619 TRIE_BITMAP_SET(trie, uvc); \
2620 /* store the folded codepoint */ \
2622 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2625 /* store first byte of utf8 representation of */ \
2626 /* variant codepoints */ \
2627 if (! UVCHR_IS_INVARIANT(uvc)) { \
2628 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2633 #define MADE_JUMP_TRIE 2
2634 #define MADE_EXACT_TRIE 4
2637 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2638 regnode *first, regnode *last, regnode *tail,
2639 U32 word_count, U32 flags, U32 depth)
2641 /* first pass, loop through and scan words */
2642 reg_trie_data *trie;
2643 HV *widecharmap = NULL;
2644 AV *revcharmap = newAV();
2650 regnode *jumper = NULL;
2651 regnode *nextbranch = NULL;
2652 regnode *convert = NULL;
2653 U32 *prev_states; /* temp array mapping each state to previous one */
2654 /* we just use folder as a flag in utf8 */
2655 const U8 * folder = NULL;
2657 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2658 * which stands for one trie structure, one hash, optionally followed
2661 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2662 AV *trie_words = NULL;
2663 /* along with revcharmap, this only used during construction but both are
2664 * useful during debugging so we store them in the struct when debugging.
2667 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2668 STRLEN trie_charcount=0;
2670 SV *re_trie_maxbuff;
2671 GET_RE_DEBUG_FLAGS_DECL;
2673 PERL_ARGS_ASSERT_MAKE_TRIE;
2675 PERL_UNUSED_ARG(depth);
2679 case EXACT: case EXACT_ONLY8: case EXACTL: break;
2683 case EXACTFLU8: folder = PL_fold_latin1; break;
2684 case EXACTF: folder = PL_fold; break;
2685 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2688 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2690 trie->startstate = 1;
2691 trie->wordcount = word_count;
2692 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2693 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2694 if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL)
2695 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2696 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2697 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2700 trie_words = newAV();
2703 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2704 assert(re_trie_maxbuff);
2705 if (!SvIOK(re_trie_maxbuff)) {
2706 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2708 DEBUG_TRIE_COMPILE_r({
2709 Perl_re_indentf( aTHX_
2710 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2712 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2713 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2716 /* Find the node we are going to overwrite */
2717 if ( first == startbranch && OP( last ) != BRANCH ) {
2718 /* whole branch chain */
2721 /* branch sub-chain */
2722 convert = NEXTOPER( first );
2725 /* -- First loop and Setup --
2727 We first traverse the branches and scan each word to determine if it
2728 contains widechars, and how many unique chars there are, this is
2729 important as we have to build a table with at least as many columns as we
2732 We use an array of integers to represent the character codes 0..255
2733 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2734 the native representation of the character value as the key and IV's for
2737 *TODO* If we keep track of how many times each character is used we can
2738 remap the columns so that the table compression later on is more
2739 efficient in terms of memory by ensuring the most common value is in the
2740 middle and the least common are on the outside. IMO this would be better
2741 than a most to least common mapping as theres a decent chance the most
2742 common letter will share a node with the least common, meaning the node
2743 will not be compressible. With a middle is most common approach the worst
2744 case is when we have the least common nodes twice.
2748 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2749 regnode *noper = NEXTOPER( cur );
2753 U32 wordlen = 0; /* required init */
2754 STRLEN minchars = 0;
2755 STRLEN maxchars = 0;
2756 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2759 if (OP(noper) == NOTHING) {
2760 /* skip past a NOTHING at the start of an alternation
2761 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2763 regnode *noper_next= regnext(noper);
2764 if (noper_next < tail)
2769 && ( OP(noper) == flags
2770 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
2771 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
2772 || OP(noper) == EXACTFUP))))
2774 uc= (U8*)STRING(noper);
2775 e= uc + STR_LEN(noper);
2782 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2783 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2784 regardless of encoding */
2785 if (OP( noper ) == EXACTFUP) {
2786 /* false positives are ok, so just set this */
2787 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2791 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2793 TRIE_CHARCOUNT(trie)++;
2796 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2797 * is in effect. Under /i, this character can match itself, or
2798 * anything that folds to it. If not under /i, it can match just
2799 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2800 * all fold to k, and all are single characters. But some folds
2801 * expand to more than one character, so for example LATIN SMALL
2802 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2803 * the string beginning at 'uc' is 'ffi', it could be matched by
2804 * three characters, or just by the one ligature character. (It
2805 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2806 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2807 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2808 * match.) The trie needs to know the minimum and maximum number
2809 * of characters that could match so that it can use size alone to
2810 * quickly reject many match attempts. The max is simple: it is
2811 * the number of folded characters in this branch (since a fold is
2812 * never shorter than what folds to it. */
2816 /* And the min is equal to the max if not under /i (indicated by
2817 * 'folder' being NULL), or there are no multi-character folds. If
2818 * there is a multi-character fold, the min is incremented just
2819 * once, for the character that folds to the sequence. Each
2820 * character in the sequence needs to be added to the list below of
2821 * characters in the trie, but we count only the first towards the
2822 * min number of characters needed. This is done through the
2823 * variable 'foldlen', which is returned by the macros that look
2824 * for these sequences as the number of bytes the sequence
2825 * occupies. Each time through the loop, we decrement 'foldlen' by
2826 * how many bytes the current char occupies. Only when it reaches
2827 * 0 do we increment 'minchars' or look for another multi-character
2829 if (folder == NULL) {
2832 else if (foldlen > 0) {
2833 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2838 /* See if *uc is the beginning of a multi-character fold. If
2839 * so, we decrement the length remaining to look at, to account
2840 * for the current character this iteration. (We can use 'uc'
2841 * instead of the fold returned by TRIE_READ_CHAR because for
2842 * non-UTF, the latin1_safe macro is smart enough to account
2843 * for all the unfolded characters, and because for UTF, the
2844 * string will already have been folded earlier in the
2845 * compilation process */
2847 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2848 foldlen -= UTF8SKIP(uc);
2851 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2856 /* The current character (and any potential folds) should be added
2857 * to the possible matching characters for this position in this
2861 U8 folded= folder[ (U8) uvc ];
2862 if ( !trie->charmap[ folded ] ) {
2863 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2864 TRIE_STORE_REVCHAR( folded );
2867 if ( !trie->charmap[ uvc ] ) {
2868 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2869 TRIE_STORE_REVCHAR( uvc );
2872 /* store the codepoint in the bitmap, and its folded
2874 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2875 set_bit = 0; /* We've done our bit :-) */
2879 /* XXX We could come up with the list of code points that fold
2880 * to this using PL_utf8_foldclosures, except not for
2881 * multi-char folds, as there may be multiple combinations
2882 * there that could work, which needs to wait until runtime to
2883 * resolve (The comment about LIGATURE FFI above is such an
2888 widecharmap = newHV();
2890 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2893 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2895 if ( !SvTRUE( *svpp ) ) {
2896 sv_setiv( *svpp, ++trie->uniquecharcount );
2897 TRIE_STORE_REVCHAR(uvc);
2900 } /* end loop through characters in this branch of the trie */
2902 /* We take the min and max for this branch and combine to find the min
2903 * and max for all branches processed so far */
2904 if( cur == first ) {
2905 trie->minlen = minchars;
2906 trie->maxlen = maxchars;
2907 } else if (minchars < trie->minlen) {
2908 trie->minlen = minchars;
2909 } else if (maxchars > trie->maxlen) {
2910 trie->maxlen = maxchars;
2912 } /* end first pass */
2913 DEBUG_TRIE_COMPILE_r(
2914 Perl_re_indentf( aTHX_
2915 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2917 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2918 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2919 (int)trie->minlen, (int)trie->maxlen )
2923 We now know what we are dealing with in terms of unique chars and
2924 string sizes so we can calculate how much memory a naive
2925 representation using a flat table will take. If it's over a reasonable
2926 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2927 conservative but potentially much slower representation using an array
2930 At the end we convert both representations into the same compressed
2931 form that will be used in regexec.c for matching with. The latter
2932 is a form that cannot be used to construct with but has memory
2933 properties similar to the list form and access properties similar
2934 to the table form making it both suitable for fast searches and
2935 small enough that its feasable to store for the duration of a program.
2937 See the comment in the code where the compressed table is produced
2938 inplace from the flat tabe representation for an explanation of how
2939 the compression works.
2944 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2947 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2948 > SvIV(re_trie_maxbuff) )
2951 Second Pass -- Array Of Lists Representation
2953 Each state will be represented by a list of charid:state records
2954 (reg_trie_trans_le) the first such element holds the CUR and LEN
2955 points of the allocated array. (See defines above).
2957 We build the initial structure using the lists, and then convert
2958 it into the compressed table form which allows faster lookups
2959 (but cant be modified once converted).
2962 STRLEN transcount = 1;
2964 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
2967 trie->states = (reg_trie_state *)
2968 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2969 sizeof(reg_trie_state) );
2973 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2975 regnode *noper = NEXTOPER( cur );
2976 U32 state = 1; /* required init */
2977 U16 charid = 0; /* sanity init */
2978 U32 wordlen = 0; /* required init */
2980 if (OP(noper) == NOTHING) {
2981 regnode *noper_next= regnext(noper);
2982 if (noper_next < tail)
2987 && ( OP(noper) == flags
2988 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
2989 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
2990 || OP(noper) == EXACTFUP))))
2992 const U8 *uc= (U8*)STRING(noper);
2993 const U8 *e= uc + STR_LEN(noper);
2995 for ( ; uc < e ; uc += len ) {
3000 charid = trie->charmap[ uvc ];
3002 SV** const svpp = hv_fetch( widecharmap,
3009 charid=(U16)SvIV( *svpp );
3012 /* charid is now 0 if we dont know the char read, or
3013 * nonzero if we do */
3020 if ( !trie->states[ state ].trans.list ) {
3021 TRIE_LIST_NEW( state );
3024 check <= TRIE_LIST_USED( state );
3027 if ( TRIE_LIST_ITEM( state, check ).forid
3030 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3035 newstate = next_alloc++;
3036 prev_states[newstate] = state;
3037 TRIE_LIST_PUSH( state, charid, newstate );
3042 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3046 TRIE_HANDLE_WORD(state);
3048 } /* end second pass */
3050 /* next alloc is the NEXT state to be allocated */
3051 trie->statecount = next_alloc;
3052 trie->states = (reg_trie_state *)
3053 PerlMemShared_realloc( trie->states,
3055 * sizeof(reg_trie_state) );
3057 /* and now dump it out before we compress it */
3058 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3059 revcharmap, next_alloc,
3063 trie->trans = (reg_trie_trans *)
3064 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3071 for( state=1 ; state < next_alloc ; state ++ ) {
3075 DEBUG_TRIE_COMPILE_MORE_r(
3076 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3080 if (trie->states[state].trans.list) {
3081 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3085 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3086 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3087 if ( forid < minid ) {
3089 } else if ( forid > maxid ) {
3093 if ( transcount < tp + maxid - minid + 1) {
3095 trie->trans = (reg_trie_trans *)
3096 PerlMemShared_realloc( trie->trans,
3098 * sizeof(reg_trie_trans) );
3099 Zero( trie->trans + (transcount / 2),
3103 base = trie->uniquecharcount + tp - minid;
3104 if ( maxid == minid ) {
3106 for ( ; zp < tp ; zp++ ) {
3107 if ( ! trie->trans[ zp ].next ) {
3108 base = trie->uniquecharcount + zp - minid;
3109 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3111 trie->trans[ zp ].check = state;
3117 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3119 trie->trans[ tp ].check = state;
3124 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3125 const U32 tid = base
3126 - trie->uniquecharcount
3127 + TRIE_LIST_ITEM( state, idx ).forid;
3128 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3130 trie->trans[ tid ].check = state;
3132 tp += ( maxid - minid + 1 );
3134 Safefree(trie->states[ state ].trans.list);
3137 DEBUG_TRIE_COMPILE_MORE_r(
3138 Perl_re_printf( aTHX_ " base: %d\n",base);
3141 trie->states[ state ].trans.base=base;
3143 trie->lasttrans = tp + 1;
3147 Second Pass -- Flat Table Representation.
3149 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3150 each. We know that we will need Charcount+1 trans at most to store
3151 the data (one row per char at worst case) So we preallocate both
3152 structures assuming worst case.
3154 We then construct the trie using only the .next slots of the entry
3157 We use the .check field of the first entry of the node temporarily
3158 to make compression both faster and easier by keeping track of how
3159 many non zero fields are in the node.
3161 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3164 There are two terms at use here: state as a TRIE_NODEIDX() which is
3165 a number representing the first entry of the node, and state as a
3166 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3167 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3168 if there are 2 entrys per node. eg:
3176 The table is internally in the right hand, idx form. However as we
3177 also have to deal with the states array which is indexed by nodenum
3178 we have to use TRIE_NODENUM() to convert.
3181 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3184 trie->trans = (reg_trie_trans *)
3185 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3186 * trie->uniquecharcount + 1,
3187 sizeof(reg_trie_trans) );
3188 trie->states = (reg_trie_state *)
3189 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3190 sizeof(reg_trie_state) );
3191 next_alloc = trie->uniquecharcount + 1;
3194 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3196 regnode *noper = NEXTOPER( cur );
3198 U32 state = 1; /* required init */
3200 U16 charid = 0; /* sanity init */
3201 U32 accept_state = 0; /* sanity init */
3203 U32 wordlen = 0; /* required init */
3205 if (OP(noper) == NOTHING) {
3206 regnode *noper_next= regnext(noper);
3207 if (noper_next < tail)
3212 && ( OP(noper) == flags
3213 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
3214 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
3215 || OP(noper) == EXACTFUP))))
3217 const U8 *uc= (U8*)STRING(noper);
3218 const U8 *e= uc + STR_LEN(noper);
3220 for ( ; uc < e ; uc += len ) {
3225 charid = trie->charmap[ uvc ];
3227 SV* const * const svpp = hv_fetch( widecharmap,
3231 charid = svpp ? (U16)SvIV(*svpp) : 0;
3235 if ( !trie->trans[ state + charid ].next ) {
3236 trie->trans[ state + charid ].next = next_alloc;
3237 trie->trans[ state ].check++;
3238 prev_states[TRIE_NODENUM(next_alloc)]
3239 = TRIE_NODENUM(state);
3240 next_alloc += trie->uniquecharcount;
3242 state = trie->trans[ state + charid ].next;
3244 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3246 /* charid is now 0 if we dont know the char read, or
3247 * nonzero if we do */
3250 accept_state = TRIE_NODENUM( state );
3251 TRIE_HANDLE_WORD(accept_state);
3253 } /* end second pass */
3255 /* and now dump it out before we compress it */
3256 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3258 next_alloc, depth+1));
3262 * Inplace compress the table.*
3264 For sparse data sets the table constructed by the trie algorithm will
3265 be mostly 0/FAIL transitions or to put it another way mostly empty.
3266 (Note that leaf nodes will not contain any transitions.)
3268 This algorithm compresses the tables by eliminating most such
3269 transitions, at the cost of a modest bit of extra work during lookup:
3271 - Each states[] entry contains a .base field which indicates the
3272 index in the state[] array wheres its transition data is stored.
3274 - If .base is 0 there are no valid transitions from that node.
3276 - If .base is nonzero then charid is added to it to find an entry in
3279 -If trans[states[state].base+charid].check!=state then the
3280 transition is taken to be a 0/Fail transition. Thus if there are fail
3281 transitions at the front of the node then the .base offset will point
3282 somewhere inside the previous nodes data (or maybe even into a node
3283 even earlier), but the .check field determines if the transition is
3287 The following process inplace converts the table to the compressed
3288 table: We first do not compress the root node 1,and mark all its
3289 .check pointers as 1 and set its .base pointer as 1 as well. This
3290 allows us to do a DFA construction from the compressed table later,
3291 and ensures that any .base pointers we calculate later are greater
3294 - We set 'pos' to indicate the first entry of the second node.
3296 - We then iterate over the columns of the node, finding the first and
3297 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3298 and set the .check pointers accordingly, and advance pos
3299 appropriately and repreat for the next node. Note that when we copy
3300 the next pointers we have to convert them from the original
3301 NODEIDX form to NODENUM form as the former is not valid post
3304 - If a node has no transitions used we mark its base as 0 and do not
3305 advance the pos pointer.
3307 - If a node only has one transition we use a second pointer into the
3308 structure to fill in allocated fail transitions from other states.
3309 This pointer is independent of the main pointer and scans forward
3310 looking for null transitions that are allocated to a state. When it
3311 finds one it writes the single transition into the "hole". If the
3312 pointer doesnt find one the single transition is appended as normal.
3314 - Once compressed we can Renew/realloc the structures to release the
3317 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3318 specifically Fig 3.47 and the associated pseudocode.
3322 const U32 laststate = TRIE_NODENUM( next_alloc );
3325 trie->statecount = laststate;
3327 for ( state = 1 ; state < laststate ; state++ ) {
3329 const U32 stateidx = TRIE_NODEIDX( state );
3330 const U32 o_used = trie->trans[ stateidx ].check;
3331 U32 used = trie->trans[ stateidx ].check;
3332 trie->trans[ stateidx ].check = 0;
3335 used && charid < trie->uniquecharcount;
3338 if ( flag || trie->trans[ stateidx + charid ].next ) {
3339 if ( trie->trans[ stateidx + charid ].next ) {
3341 for ( ; zp < pos ; zp++ ) {
3342 if ( ! trie->trans[ zp ].next ) {
3346 trie->states[ state ].trans.base
3348 + trie->uniquecharcount
3350 trie->trans[ zp ].next
3351 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3353 trie->trans[ zp ].check = state;
3354 if ( ++zp > pos ) pos = zp;
3361 trie->states[ state ].trans.base
3362 = pos + trie->uniquecharcount - charid ;
3364 trie->trans[ pos ].next
3365 = SAFE_TRIE_NODENUM(
3366 trie->trans[ stateidx + charid ].next );
3367 trie->trans[ pos ].check = state;
3372 trie->lasttrans = pos + 1;
3373 trie->states = (reg_trie_state *)
3374 PerlMemShared_realloc( trie->states, laststate
3375 * sizeof(reg_trie_state) );
3376 DEBUG_TRIE_COMPILE_MORE_r(
3377 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3379 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3383 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3386 } /* end table compress */
3388 DEBUG_TRIE_COMPILE_MORE_r(
3389 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3391 (UV)trie->statecount,
3392 (UV)trie->lasttrans)
3394 /* resize the trans array to remove unused space */
3395 trie->trans = (reg_trie_trans *)
3396 PerlMemShared_realloc( trie->trans, trie->lasttrans
3397 * sizeof(reg_trie_trans) );
3399 { /* Modify the program and insert the new TRIE node */
3400 U8 nodetype =(U8)(flags & 0xFF);
3404 regnode *optimize = NULL;
3405 #ifdef RE_TRACK_PATTERN_OFFSETS
3408 U32 mjd_nodelen = 0;
3409 #endif /* RE_TRACK_PATTERN_OFFSETS */
3410 #endif /* DEBUGGING */
3412 This means we convert either the first branch or the first Exact,
3413 depending on whether the thing following (in 'last') is a branch
3414 or not and whther first is the startbranch (ie is it a sub part of
3415 the alternation or is it the whole thing.)
3416 Assuming its a sub part we convert the EXACT otherwise we convert
3417 the whole branch sequence, including the first.
3419 /* Find the node we are going to overwrite */
3420 if ( first != startbranch || OP( last ) == BRANCH ) {
3421 /* branch sub-chain */
3422 NEXT_OFF( first ) = (U16)(last - first);
3423 #ifdef RE_TRACK_PATTERN_OFFSETS
3425 mjd_offset= Node_Offset((convert));
3426 mjd_nodelen= Node_Length((convert));
3429 /* whole branch chain */
3431 #ifdef RE_TRACK_PATTERN_OFFSETS
3434 const regnode *nop = NEXTOPER( convert );
3435 mjd_offset= Node_Offset((nop));
3436 mjd_nodelen= Node_Length((nop));
3440 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3442 (UV)mjd_offset, (UV)mjd_nodelen)
3445 /* But first we check to see if there is a common prefix we can
3446 split out as an EXACT and put in front of the TRIE node. */
3447 trie->startstate= 1;
3448 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3449 /* we want to find the first state that has more than
3450 * one transition, if that state is not the first state
3451 * then we have a common prefix which we can remove.
3454 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3456 I32 first_ofs = -1; /* keeps track of the ofs of the first
3457 transition, -1 means none */
3459 const U32 base = trie->states[ state ].trans.base;
3461 /* does this state terminate an alternation? */
3462 if ( trie->states[state].wordnum )
3465 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3466 if ( ( base + ofs >= trie->uniquecharcount ) &&
3467 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3468 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3470 if ( ++count > 1 ) {
3471 /* we have more than one transition */
3474 /* if this is the first state there is no common prefix
3475 * to extract, so we can exit */
3476 if ( state == 1 ) break;
3477 tmp = av_fetch( revcharmap, ofs, 0);
3478 ch = (U8*)SvPV_nolen_const( *tmp );
3480 /* if we are on count 2 then we need to initialize the
3481 * bitmap, and store the previous char if there was one
3484 /* clear the bitmap */
3485 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3487 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3490 if (first_ofs >= 0) {
3491 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3492 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3494 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3496 Perl_re_printf( aTHX_ "%s", (char*)ch)
3500 /* store the current firstchar in the bitmap */
3501 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3502 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3508 /* This state has only one transition, its transition is part
3509 * of a common prefix - we need to concatenate the char it
3510 * represents to what we have so far. */
3511 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3513 char *ch = SvPV( *tmp, len );
3515 SV *sv=sv_newmortal();
3516 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3518 (UV)state, (UV)first_ofs,
3519 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3520 PL_colors[0], PL_colors[1],
3521 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3522 PERL_PV_ESCAPE_FIRSTCHAR
3527 OP( convert ) = nodetype;
3528 str=STRING(convert);
3531 STR_LEN(convert) += len;
3537 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3542 trie->prefixlen = (state-1);
3544 regnode *n = convert+NODE_SZ_STR(convert);
3545 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3546 trie->startstate = state;
3547 trie->minlen -= (state - 1);
3548 trie->maxlen -= (state - 1);
3550 /* At least the UNICOS C compiler choked on this
3551 * being argument to DEBUG_r(), so let's just have
3554 #ifdef PERL_EXT_RE_BUILD
3560 regnode *fix = convert;
3561 U32 word = trie->wordcount;
3562 #ifdef RE_TRACK_PATTERN_OFFSETS
3565 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3566 while( ++fix < n ) {
3567 Set_Node_Offset_Length(fix, 0, 0);
3570 SV ** const tmp = av_fetch( trie_words, word, 0 );
3572 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3573 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3575 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3583 NEXT_OFF(convert) = (U16)(tail - convert);
3584 DEBUG_r(optimize= n);
3590 if ( trie->maxlen ) {
3591 NEXT_OFF( convert ) = (U16)(tail - convert);
3592 ARG_SET( convert, data_slot );
3593 /* Store the offset to the first unabsorbed branch in
3594 jump[0], which is otherwise unused by the jump logic.
3595 We use this when dumping a trie and during optimisation. */
3597 trie->jump[0] = (U16)(nextbranch - convert);
3599 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3600 * and there is a bitmap
3601 * and the first "jump target" node we found leaves enough room
3602 * then convert the TRIE node into a TRIEC node, with the bitmap
3603 * embedded inline in the opcode - this is hypothetically faster.
3605 if ( !trie->states[trie->startstate].wordnum
3607 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3609 OP( convert ) = TRIEC;
3610 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3611 PerlMemShared_free(trie->bitmap);
3614 OP( convert ) = TRIE;
3616 /* store the type in the flags */
3617 convert->flags = nodetype;
3621 + regarglen[ OP( convert ) ];
3623 /* XXX We really should free up the resource in trie now,
3624 as we won't use them - (which resources?) dmq */
3626 /* needed for dumping*/
3627 DEBUG_r(if (optimize) {
3628 regnode *opt = convert;
3630 while ( ++opt < optimize) {
3631 Set_Node_Offset_Length(opt, 0, 0);
3634 Try to clean up some of the debris left after the
3637 while( optimize < jumper ) {
3638 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3639 OP( optimize ) = OPTIMIZED;
3640 Set_Node_Offset_Length(optimize, 0, 0);
3643 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3645 } /* end node insert */
3647 /* Finish populating the prev field of the wordinfo array. Walk back
3648 * from each accept state until we find another accept state, and if
3649 * so, point the first word's .prev field at the second word. If the
3650 * second already has a .prev field set, stop now. This will be the
3651 * case either if we've already processed that word's accept state,
3652 * or that state had multiple words, and the overspill words were
3653 * already linked up earlier.
3660 for (word=1; word <= trie->wordcount; word++) {
3662 if (trie->wordinfo[word].prev)
3664 state = trie->wordinfo[word].accept;
3666 state = prev_states[state];
3669 prev = trie->states[state].wordnum;
3673 trie->wordinfo[word].prev = prev;
3675 Safefree(prev_states);
3679 /* and now dump out the compressed format */
3680 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3682 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3684 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3685 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3687 SvREFCNT_dec_NN(revcharmap);
3691 : trie->startstate>1
3697 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3699 /* The Trie is constructed and compressed now so we can build a fail array if
3702 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3704 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3708 We find the fail state for each state in the trie, this state is the longest
3709 proper suffix of the current state's 'word' that is also a proper prefix of
3710 another word in our trie. State 1 represents the word '' and is thus the
3711 default fail state. This allows the DFA not to have to restart after its
3712 tried and failed a word at a given point, it simply continues as though it
3713 had been matching the other word in the first place.
3715 'abcdgu'=~/abcdefg|cdgu/
3716 When we get to 'd' we are still matching the first word, we would encounter
3717 'g' which would fail, which would bring us to the state representing 'd' in
3718 the second word where we would try 'g' and succeed, proceeding to match
3721 /* add a fail transition */
3722 const U32 trie_offset = ARG(source);
3723 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3725 const U32 ucharcount = trie->uniquecharcount;
3726 const U32 numstates = trie->statecount;
3727 const U32 ubound = trie->lasttrans + ucharcount;
3731 U32 base = trie->states[ 1 ].trans.base;
3734 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3736 GET_RE_DEBUG_FLAGS_DECL;
3738 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3739 PERL_UNUSED_CONTEXT;
3741 PERL_UNUSED_ARG(depth);
3744 if ( OP(source) == TRIE ) {
3745 struct regnode_1 *op = (struct regnode_1 *)
3746 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3747 StructCopy(source, op, struct regnode_1);
3748 stclass = (regnode *)op;
3750 struct regnode_charclass *op = (struct regnode_charclass *)
3751 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3752 StructCopy(source, op, struct regnode_charclass);
3753 stclass = (regnode *)op;
3755 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3757 ARG_SET( stclass, data_slot );
3758 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3759 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3760 aho->trie=trie_offset;
3761 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3762 Copy( trie->states, aho->states, numstates, reg_trie_state );
3763 Newx( q, numstates, U32);
3764 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3767 /* initialize fail[0..1] to be 1 so that we always have
3768 a valid final fail state */
3769 fail[ 0 ] = fail[ 1 ] = 1;
3771 for ( charid = 0; charid < ucharcount ; charid++ ) {
3772 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3774 q[ q_write ] = newstate;
3775 /* set to point at the root */
3776 fail[ q[ q_write++ ] ]=1;
3779 while ( q_read < q_write) {
3780 const U32 cur = q[ q_read++ % numstates ];
3781 base = trie->states[ cur ].trans.base;
3783 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3784 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3786 U32 fail_state = cur;
3789 fail_state = fail[ fail_state ];
3790 fail_base = aho->states[ fail_state ].trans.base;
3791 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3793 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3794 fail[ ch_state ] = fail_state;
3795 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3797 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3799 q[ q_write++ % numstates] = ch_state;
3803 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3804 when we fail in state 1, this allows us to use the
3805 charclass scan to find a valid start char. This is based on the principle
3806 that theres a good chance the string being searched contains lots of stuff
3807 that cant be a start char.
3809 fail[ 0 ] = fail[ 1 ] = 0;
3810 DEBUG_TRIE_COMPILE_r({
3811 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3812 depth, (UV)numstates
3814 for( q_read=1; q_read<numstates; q_read++ ) {
3815 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3817 Perl_re_printf( aTHX_ "\n");
3820 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3825 /* The below joins as many adjacent EXACTish nodes as possible into a single
3826 * one. The regop may be changed if the node(s) contain certain sequences that
3827 * require special handling. The joining is only done if:
3828 * 1) there is room in the current conglomerated node to entirely contain the
3830 * 2) they are compatible node types
3832 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3833 * these get optimized out
3835 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3836 * as possible, even if that means splitting an existing node so that its first
3837 * part is moved to the preceeding node. This would maximise the efficiency of
3838 * memEQ during matching.
3840 * If a node is to match under /i (folded), the number of characters it matches
3841 * can be different than its character length if it contains a multi-character
3842 * fold. *min_subtract is set to the total delta number of characters of the
3845 * And *unfolded_multi_char is set to indicate whether or not the node contains
3846 * an unfolded multi-char fold. This happens when it won't be known until
3847 * runtime whether the fold is valid or not; namely
3848 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3849 * target string being matched against turns out to be UTF-8 is that fold
3851 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3853 * (Multi-char folds whose components are all above the Latin1 range are not
3854 * run-time locale dependent, and have already been folded by the time this
3855 * function is called.)
3857 * This is as good a place as any to discuss the design of handling these
3858 * multi-character fold sequences. It's been wrong in Perl for a very long
3859 * time. There are three code points in Unicode whose multi-character folds
3860 * were long ago discovered to mess things up. The previous designs for
3861 * dealing with these involved assigning a special node for them. This
3862 * approach doesn't always work, as evidenced by this example:
3863 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3864 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3865 * would match just the \xDF, it won't be able to handle the case where a
3866 * successful match would have to cross the node's boundary. The new approach
3867 * that hopefully generally solves the problem generates an EXACTFUP node
3868 * that is "sss" in this case.
3870 * It turns out that there are problems with all multi-character folds, and not
3871 * just these three. Now the code is general, for all such cases. The
3872 * approach taken is:
3873 * 1) This routine examines each EXACTFish node that could contain multi-
3874 * character folded sequences. Since a single character can fold into
3875 * such a sequence, the minimum match length for this node is less than
3876 * the number of characters in the node. This routine returns in
3877 * *min_subtract how many characters to subtract from the the actual
3878 * length of the string to get a real minimum match length; it is 0 if
3879 * there are no multi-char foldeds. This delta is used by the caller to
3880 * adjust the min length of the match, and the delta between min and max,
3881 * so that the optimizer doesn't reject these possibilities based on size
3884 * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3885 * under /u, we fold it to 'ss' in regatom(), and in this routine, after
3886 * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3887 * EXACTFU nodes. The node type of such nodes is then changed to
3888 * EXACTFUP, indicating it is problematic, and needs careful handling.
3889 * (The procedures in step 1) above are sufficient to handle this case in
3890 * UTF-8 encoded nodes.) The reason this is problematic is that this is
3891 * the only case where there is a possible fold length change in non-UTF-8
3892 * patterns. By reserving a special node type for problematic cases, the
3893 * far more common regular EXACTFU nodes can be processed faster.
3894 * regexec.c takes advantage of this.
3896 * EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3897 * problematic cases. These all only occur when the pattern is not
3898 * UTF-8. In addition to the 'ss' sequence where there is a possible fold
3899 * length change, it handles the situation where the string cannot be
3900 * entirely folded. The strings in an EXACTFish node are folded as much
3901 * as possible during compilation in regcomp.c. This saves effort in
3902 * regex matching. By using an EXACTFUP node when it is not possible to
3903 * fully fold at compile time, regexec.c can know that everything in an
3904 * EXACTFU node is folded, so folding can be skipped at runtime. The only
3905 * case where folding in EXACTFU nodes can't be done at compile time is
3906 * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
3907 * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
3908 * handle two very different cases. Alternatively, there could have been
3909 * a node type where there are length changes, one for unfolded, and one
3910 * for both. If yet another special case needed to be created, the number
3911 * of required node types would have to go to 7. khw figures that even
3912 * though there are plenty of node types to spare, that the maintenance
3913 * cost wasn't worth the small speedup of doing it that way, especially
3914 * since he thinks the MICRO SIGN is rarely encountered in practice.
3916 * There are other cases where folding isn't done at compile time, but
3917 * none of them are under /u, and hence not for EXACTFU nodes. The folds
3918 * in EXACTFL nodes aren't known until runtime, and vary as the locale
3919 * changes. Some folds in EXACTF depend on if the runtime target string
3920 * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di
3921 * when no fold in it depends on the UTF-8ness of the target string.)
3923 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3924 * validity of the fold won't be known until runtime, and so must remain
3925 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
3926 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3927 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3928 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3929 * The reason this is a problem is that the optimizer part of regexec.c
3930 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3931 * that a character in the pattern corresponds to at most a single
3932 * character in the target string. (And I do mean character, and not byte
3933 * here, unlike other parts of the documentation that have never been
3934 * updated to account for multibyte Unicode.) Sharp s in EXACTF and
3935 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3936 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
3937 * EXACTFL nodes, violate the assumption, and they are the only instances
3938 * where it is violated. I'm reluctant to try to change the assumption,
3939 * as the code involved is impenetrable to me (khw), so instead the code
3940 * here punts. This routine examines EXACTFL nodes, and (when the pattern
3941 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3942 * boolean indicating whether or not the node contains such a fold. When
3943 * it is true, the caller sets a flag that later causes the optimizer in
3944 * this file to not set values for the floating and fixed string lengths,
3945 * and thus avoids the optimizer code in regexec.c that makes the invalid
3946 * assumption. Thus, there is no optimization based on string lengths for
3947 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3948 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
3949 * assumption is wrong only in these cases is that all other non-UTF-8
3950 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3951 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3952 * EXACTF nodes because we don't know at compile time if it actually
3953 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3954 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3955 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
3956 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3957 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3958 * string would require the pattern to be forced into UTF-8, the overhead
3959 * of which we want to avoid. Similarly the unfolded multi-char folds in
3960 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3963 * Similarly, the code that generates tries doesn't currently handle
3964 * not-already-folded multi-char folds, and it looks like a pain to change
3965 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
3966 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
3967 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
3968 * using /iaa matching will be doing so almost entirely with ASCII
3969 * strings, so this should rarely be encountered in practice */
3971 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3972 if (PL_regkind[OP(scan)] == EXACT) \
3973 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
3976 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3977 UV *min_subtract, bool *unfolded_multi_char,