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 "invlist_inline.h"
86 #include "unicode_constants.h"
88 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
89 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
90 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
91 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
92 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
93 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
99 /* this is a chain of data about sub patterns we are processing that
100 need to be handled separately/specially in study_chunk. Its so
101 we can simulate recursion without losing state. */
103 typedef struct scan_frame {
104 regnode *last_regnode; /* last node to process in this frame */
105 regnode *next_regnode; /* next node to process when last is reached */
106 U32 prev_recursed_depth;
107 I32 stopparen; /* what stopparen do we use */
109 struct scan_frame *this_prev_frame; /* this previous frame */
110 struct scan_frame *prev_frame; /* previous frame */
111 struct scan_frame *next_frame; /* next frame */
114 /* Certain characters are output as a sequence with the first being a
116 #define isBACKSLASHED_PUNCT(c) memCHRs("-[]\\^", c)
119 struct RExC_state_t {
120 U32 flags; /* RXf_* are we folding, multilining? */
121 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
122 char *precomp; /* uncompiled string. */
123 char *precomp_end; /* pointer to end of uncompiled string. */
124 REGEXP *rx_sv; /* The SV that is the regexp. */
125 regexp *rx; /* perl core regexp structure */
126 regexp_internal *rxi; /* internal data for regexp object
128 char *start; /* Start of input for compile */
129 char *end; /* End of input for compile */
130 char *parse; /* Input-scan pointer. */
131 char *copy_start; /* start of copy of input within
132 constructed parse string */
133 char *save_copy_start; /* Provides one level of saving
134 and restoring 'copy_start' */
135 char *copy_start_in_input; /* Position in input string
136 corresponding to copy_start */
137 SSize_t whilem_seen; /* number of WHILEM in this expr */
138 regnode *emit_start; /* Start of emitted-code area */
139 regnode_offset emit; /* Code-emit pointer */
140 I32 naughty; /* How bad is this pattern? */
141 I32 sawback; /* Did we see \1, ...? */
143 SSize_t size; /* Number of regnode equivalents in
145 Size_t sets_depth; /* Counts recursion depth of already-
146 compiled regex set patterns */
148 /* position beyond 'precomp' of the warning message furthest away from
149 * 'precomp'. During the parse, no warnings are raised for any problems
150 * earlier in the parse than this position. This works if warnings are
151 * raised the first time a given spot is parsed, and if only one
152 * independent warning is raised for any given spot */
153 Size_t latest_warn_offset;
155 I32 npar; /* Capture buffer count so far in the
156 parse, (OPEN) plus one. ("par" 0 is
158 I32 total_par; /* During initial parse, is either 0,
159 or -1; the latter indicating a
160 reparse is needed. After that pass,
161 it is what 'npar' became after the
162 pass. Hence, it being > 0 indicates
163 we are in a reparse situation */
164 I32 nestroot; /* root parens we are in - used by
167 regnode_offset *open_parens; /* offsets to open parens */
168 regnode_offset *close_parens; /* offsets to close parens */
169 I32 parens_buf_size; /* #slots malloced open/close_parens */
170 regnode *end_op; /* END node in program */
171 I32 utf8; /* whether the pattern is utf8 or not */
172 I32 orig_utf8; /* whether the pattern was originally in utf8 */
173 /* XXX use this for future optimisation of case
174 * where pattern must be upgraded to utf8. */
175 I32 uni_semantics; /* If a d charset modifier should use unicode
176 rules, even if the pattern is not in
178 HV *paren_names; /* Paren names */
180 regnode **recurse; /* Recurse regops */
181 I32 recurse_count; /* Number of recurse regops we have generated */
182 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
184 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
188 I32 override_recoding;
189 I32 recode_x_to_native;
190 I32 in_multi_char_class;
191 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
193 int code_index; /* next code_blocks[] slot */
194 SSize_t maxlen; /* mininum possible number of chars in string to match */
195 scan_frame *frame_head;
196 scan_frame *frame_last;
200 #ifdef ADD_TO_REGEXEC
201 char *starttry; /* -Dr: where regtry was called. */
202 #define RExC_starttry (pRExC_state->starttry)
204 SV *runtime_code_qr; /* qr with the runtime code blocks */
206 const char *lastparse;
208 AV *paren_name_list; /* idx -> name */
209 U32 study_chunk_recursed_count;
213 #define RExC_lastparse (pRExC_state->lastparse)
214 #define RExC_lastnum (pRExC_state->lastnum)
215 #define RExC_paren_name_list (pRExC_state->paren_name_list)
216 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
217 #define RExC_mysv (pRExC_state->mysv1)
218 #define RExC_mysv1 (pRExC_state->mysv1)
219 #define RExC_mysv2 (pRExC_state->mysv2)
229 #define RExC_flags (pRExC_state->flags)
230 #define RExC_pm_flags (pRExC_state->pm_flags)
231 #define RExC_precomp (pRExC_state->precomp)
232 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
233 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
234 #define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start)
235 #define RExC_precomp_end (pRExC_state->precomp_end)
236 #define RExC_rx_sv (pRExC_state->rx_sv)
237 #define RExC_rx (pRExC_state->rx)
238 #define RExC_rxi (pRExC_state->rxi)
239 #define RExC_start (pRExC_state->start)
240 #define RExC_end (pRExC_state->end)
241 #define RExC_parse (pRExC_state->parse)
242 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
243 #define RExC_whilem_seen (pRExC_state->whilem_seen)
244 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
245 under /d from /u ? */
247 #ifdef RE_TRACK_PATTERN_OFFSETS
248 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
251 #define RExC_emit (pRExC_state->emit)
252 #define RExC_emit_start (pRExC_state->emit_start)
253 #define RExC_sawback (pRExC_state->sawback)
254 #define RExC_seen (pRExC_state->seen)
255 #define RExC_size (pRExC_state->size)
256 #define RExC_maxlen (pRExC_state->maxlen)
257 #define RExC_npar (pRExC_state->npar)
258 #define RExC_total_parens (pRExC_state->total_par)
259 #define RExC_parens_buf_size (pRExC_state->parens_buf_size)
260 #define RExC_nestroot (pRExC_state->nestroot)
261 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
262 #define RExC_utf8 (pRExC_state->utf8)
263 #define RExC_uni_semantics (pRExC_state->uni_semantics)
264 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
265 #define RExC_open_parens (pRExC_state->open_parens)
266 #define RExC_close_parens (pRExC_state->close_parens)
267 #define RExC_end_op (pRExC_state->end_op)
268 #define RExC_paren_names (pRExC_state->paren_names)
269 #define RExC_recurse (pRExC_state->recurse)
270 #define RExC_recurse_count (pRExC_state->recurse_count)
271 #define RExC_sets_depth (pRExC_state->sets_depth)
272 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
273 #define RExC_study_chunk_recursed_bytes \
274 (pRExC_state->study_chunk_recursed_bytes)
275 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
276 #define RExC_in_lookahead (pRExC_state->in_lookahead)
277 #define RExC_contains_locale (pRExC_state->contains_locale)
278 #define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
281 # define SET_recode_x_to_native(x) \
282 STMT_START { RExC_recode_x_to_native = (x); } STMT_END
284 # define SET_recode_x_to_native(x) NOOP
287 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
288 #define RExC_frame_head (pRExC_state->frame_head)
289 #define RExC_frame_last (pRExC_state->frame_last)
290 #define RExC_frame_count (pRExC_state->frame_count)
291 #define RExC_strict (pRExC_state->strict)
292 #define RExC_study_started (pRExC_state->study_started)
293 #define RExC_warn_text (pRExC_state->warn_text)
294 #define RExC_in_script_run (pRExC_state->in_script_run)
295 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
296 #define RExC_unlexed_names (pRExC_state->unlexed_names)
298 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
299 * a flag to disable back-off on the fixed/floating substrings - if it's
300 * a high complexity pattern we assume the benefit of avoiding a full match
301 * is worth the cost of checking for the substrings even if they rarely help.
303 #define RExC_naughty (pRExC_state->naughty)
304 #define TOO_NAUGHTY (10)
305 #define MARK_NAUGHTY(add) \
306 if (RExC_naughty < TOO_NAUGHTY) \
307 RExC_naughty += (add)
308 #define MARK_NAUGHTY_EXP(exp, add) \
309 if (RExC_naughty < TOO_NAUGHTY) \
310 RExC_naughty += RExC_naughty / (exp) + (add)
312 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
313 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
314 ((*s) == '{' && regcurly(s)))
317 * Flags to be passed up and down.
319 #define WORST 0 /* Worst case. */
320 #define HASWIDTH 0x01 /* Known to not match null strings, could match
323 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
324 * character. (There needs to be a case: in the switch statement in regexec.c
325 * for any node marked SIMPLE.) Note that this is not the same thing as
328 #define SPSTART 0x04 /* Starts with * or + */
329 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
330 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
331 #define RESTART_PARSE 0x20 /* Need to redo the parse */
332 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
333 calcuate sizes as UTF-8 */
335 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
337 /* whether trie related optimizations are enabled */
338 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
339 #define TRIE_STUDY_OPT
340 #define FULL_TRIE_STUDY
346 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
347 #define PBITVAL(paren) (1 << ((paren) & 7))
348 #define PAREN_OFFSET(depth) \
349 (RExC_study_chunk_recursed + (depth) * RExC_study_chunk_recursed_bytes)
350 #define PAREN_TEST(depth, paren) \
351 (PBYTE(PAREN_OFFSET(depth), paren) & PBITVAL(paren))
352 #define PAREN_SET(depth, paren) \
353 (PBYTE(PAREN_OFFSET(depth), paren) |= PBITVAL(paren))
354 #define PAREN_UNSET(depth, paren) \
355 (PBYTE(PAREN_OFFSET(depth), paren) &= ~PBITVAL(paren))
357 #define REQUIRE_UTF8(flagp) STMT_START { \
359 *flagp = RESTART_PARSE|NEED_UTF8; \
364 /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
365 * a flag that indicates we need to override /d with /u as a result of
366 * something in the pattern. It should only be used in regards to calling
367 * set_regex_charset() or get_regex_charset() */
368 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
370 if (DEPENDS_SEMANTICS) { \
371 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
372 RExC_uni_semantics = 1; \
373 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \
374 /* No need to restart the parse if we haven't seen \
375 * anything that differs between /u and /d, and no need \
376 * to restart immediately if we're going to reparse \
377 * anyway to count parens */ \
378 *flagp |= RESTART_PARSE; \
379 return restart_retval; \
384 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
386 RExC_use_BRANCHJ = 1; \
387 *flagp |= RESTART_PARSE; \
388 return restart_retval; \
391 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
392 * less. After that, it must always be positive, because the whole re is
393 * considered to be surrounded by virtual parens. Setting it to negative
394 * indicates there is some construct that needs to know the actual number of
395 * parens to be properly handled. And that means an extra pass will be
396 * required after we've counted them all */
397 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
398 #define REQUIRE_PARENS_PASS \
399 STMT_START { /* No-op if have completed a pass */ \
400 if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \
402 #define IN_PARENS_PASS (RExC_total_parens < 0)
405 /* This is used to return failure (zero) early from the calling function if
406 * various flags in 'flags' are set. Two flags always cause a return:
407 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
408 * additional flags that should cause a return; 0 if none. If the return will
409 * be done, '*flagp' is first set to be all of the flags that caused the
411 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
413 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
414 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
419 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
421 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
422 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
423 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
424 if (MUST_RESTART(*(flagp))) return 0
426 /* This converts the named class defined in regcomp.h to its equivalent class
427 * number defined in handy.h. */
428 #define namedclass_to_classnum(class) ((int) ((class) / 2))
429 #define classnum_to_namedclass(classnum) ((classnum) * 2)
431 #define _invlist_union_complement_2nd(a, b, output) \
432 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
433 #define _invlist_intersection_complement_2nd(a, b, output) \
434 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
436 /* We add a marker if we are deferring expansion of a property that is both
437 * 1) potentiallly user-defined; and
438 * 2) could also be an official Unicode property.
440 * Without this marker, any deferred expansion can only be for a user-defined
441 * one. This marker shouldn't conflict with any that could be in a legal name,
442 * and is appended to its name to indicate this. There is a string and
444 #define DEFERRED_COULD_BE_OFFICIAL_MARKERs "~"
445 #define DEFERRED_COULD_BE_OFFICIAL_MARKERc '~'
447 /* About scan_data_t.
449 During optimisation we recurse through the regexp program performing
450 various inplace (keyhole style) optimisations. In addition study_chunk
451 and scan_commit populate this data structure with information about
452 what strings MUST appear in the pattern. We look for the longest
453 string that must appear at a fixed location, and we look for the
454 longest string that may appear at a floating location. So for instance
459 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
460 strings (because they follow a .* construct). study_chunk will identify
461 both FOO and BAR as being the longest fixed and floating strings respectively.
463 The strings can be composites, for instance
467 will result in a composite fixed substring 'foo'.
469 For each string some basic information is maintained:
472 This is the position the string must appear at, or not before.
473 It also implicitly (when combined with minlenp) tells us how many
474 characters must match before the string we are searching for.
475 Likewise when combined with minlenp and the length of the string it
476 tells us how many characters must appear after the string we have
480 Only used for floating strings. This is the rightmost point that
481 the string can appear at. If set to SSize_t_MAX it indicates that the
482 string can occur infinitely far to the right.
483 For fixed strings, it is equal to min_offset.
486 A pointer to the minimum number of characters of the pattern that the
487 string was found inside. This is important as in the case of positive
488 lookahead or positive lookbehind we can have multiple patterns
493 The minimum length of the pattern overall is 3, the minimum length
494 of the lookahead part is 3, but the minimum length of the part that
495 will actually match is 1. So 'FOO's minimum length is 3, but the
496 minimum length for the F is 1. This is important as the minimum length
497 is used to determine offsets in front of and behind the string being
498 looked for. Since strings can be composites this is the length of the
499 pattern at the time it was committed with a scan_commit. Note that
500 the length is calculated by study_chunk, so that the minimum lengths
501 are not known until the full pattern has been compiled, thus the
502 pointer to the value.
506 In the case of lookbehind the string being searched for can be
507 offset past the start point of the final matching string.
508 If this value was just blithely removed from the min_offset it would
509 invalidate some of the calculations for how many chars must match
510 before or after (as they are derived from min_offset and minlen and
511 the length of the string being searched for).
512 When the final pattern is compiled and the data is moved from the
513 scan_data_t structure into the regexp structure the information
514 about lookbehind is factored in, with the information that would
515 have been lost precalculated in the end_shift field for the
518 The fields pos_min and pos_delta are used to store the minimum offset
519 and the delta to the maximum offset at the current point in the pattern.
523 struct scan_data_substrs {
524 SV *str; /* longest substring found in pattern */
525 SSize_t min_offset; /* earliest point in string it can appear */
526 SSize_t max_offset; /* latest point in string it can appear */
527 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
528 SSize_t lookbehind; /* is the pos of the string modified by LB */
529 I32 flags; /* per substring SF_* and SCF_* flags */
532 typedef struct scan_data_t {
533 /*I32 len_min; unused */
534 /*I32 len_delta; unused */
538 SSize_t last_end; /* min value, <0 unless valid. */
539 SSize_t last_start_min;
540 SSize_t last_start_max;
541 U8 cur_is_floating; /* whether the last_* values should be set as
542 * the next fixed (0) or floating (1)
545 /* [0] is longest fixed substring so far, [1] is longest float so far */
546 struct scan_data_substrs substrs[2];
548 I32 flags; /* common SF_* and SCF_* flags */
550 SSize_t *last_closep;
551 regnode_ssc *start_class;
555 * Forward declarations for pregcomp()'s friends.
558 static const scan_data_t zero_scan_data = {
559 0, 0, NULL, 0, 0, 0, 0,
561 { NULL, 0, 0, 0, 0, 0 },
562 { NULL, 0, 0, 0, 0, 0 },
569 #define SF_BEFORE_SEOL 0x0001
570 #define SF_BEFORE_MEOL 0x0002
571 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
573 #define SF_IS_INF 0x0040
574 #define SF_HAS_PAR 0x0080
575 #define SF_IN_PAR 0x0100
576 #define SF_HAS_EVAL 0x0200
579 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
580 * longest substring in the pattern. When it is not set the optimiser keeps
581 * track of position, but does not keep track of the actual strings seen,
583 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
586 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
587 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
588 * turned off because of the alternation (BRANCH). */
589 #define SCF_DO_SUBSTR 0x0400
591 #define SCF_DO_STCLASS_AND 0x0800
592 #define SCF_DO_STCLASS_OR 0x1000
593 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
594 #define SCF_WHILEM_VISITED_POS 0x2000
596 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
597 #define SCF_SEEN_ACCEPT 0x8000
598 #define SCF_TRIE_DOING_RESTUDY 0x10000
599 #define SCF_IN_DEFINE 0x20000
604 #define UTF cBOOL(RExC_utf8)
606 /* The enums for all these are ordered so things work out correctly */
607 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
608 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
609 == REGEX_DEPENDS_CHARSET)
610 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
611 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
612 >= REGEX_UNICODE_CHARSET)
613 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
614 == REGEX_ASCII_RESTRICTED_CHARSET)
615 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
616 >= REGEX_ASCII_RESTRICTED_CHARSET)
617 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
618 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
620 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
622 /* For programs that want to be strictly Unicode compatible by dying if any
623 * attempt is made to match a non-Unicode code point against a Unicode
625 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
627 #define OOB_NAMEDCLASS -1
629 /* There is no code point that is out-of-bounds, so this is problematic. But
630 * its only current use is to initialize a variable that is always set before
632 #define OOB_UNICODE 0xDEADBEEF
634 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
637 /* length of regex to show in messages that don't mark a position within */
638 #define RegexLengthToShowInErrorMessages 127
641 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
642 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
643 * op/pragma/warn/regcomp.
645 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
646 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
648 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
649 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
651 /* The code in this file in places uses one level of recursion with parsing
652 * rebased to an alternate string constructed by us in memory. This can take
653 * the form of something that is completely different from the input, or
654 * something that uses the input as part of the alternate. In the first case,
655 * there should be no possibility of an error, as we are in complete control of
656 * the alternate string. But in the second case we don't completely control
657 * the input portion, so there may be errors in that. Here's an example:
659 * is handled specially because \x{df} folds to a sequence of more than one
660 * character: 'ss'. What is done is to create and parse an alternate string,
661 * which looks like this:
662 * /(?:\x{DF}|[abc\x{DF}def])/ui
663 * where it uses the input unchanged in the middle of something it constructs,
664 * which is a branch for the DF outside the character class, and clustering
665 * parens around the whole thing. (It knows enough to skip the DF inside the
666 * class while in this substitute parse.) 'abc' and 'def' may have errors that
667 * need to be reported. The general situation looks like this:
669 * |<------- identical ------>|
671 * Input: ---------------------------------------------------------------
672 * Constructed: ---------------------------------------------------
674 * |<------- identical ------>|
676 * sI..eI is the portion of the input pattern we are concerned with here.
677 * sC..EC is the constructed substitute parse string.
678 * sC..tC is constructed by us
679 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
680 * In the diagram, these are vertically aligned.
681 * eC..EC is also constructed by us.
682 * xC is the position in the substitute parse string where we found a
684 * xI is the position in the original pattern corresponding to xC.
686 * We want to display a message showing the real input string. Thus we need to
687 * translate from xC to xI. We know that xC >= tC, since the portion of the
688 * string sC..tC has been constructed by us, and so shouldn't have errors. We
690 * xI = tI + (xC - tC)
692 * When the substitute parse is constructed, the code needs to set:
695 * RExC_copy_start_in_input (tI)
696 * RExC_copy_start_in_constructed (tC)
697 * and restore them when done.
699 * During normal processing of the input pattern, both
700 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
701 * sI, so that xC equals xI.
704 #define sI RExC_precomp
705 #define eI RExC_precomp_end
706 #define sC RExC_start
708 #define tI RExC_copy_start_in_input
709 #define tC RExC_copy_start_in_constructed
710 #define xI(xC) (tI + (xC - tC))
711 #define xI_offset(xC) (xI(xC) - sI)
713 #define REPORT_LOCATION_ARGS(xC) \
715 (xI(xC) > eI) /* Don't run off end */ \
716 ? eI - sI /* Length before the <--HERE */ \
717 : ((xI_offset(xC) >= 0) \
719 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
720 IVdf " trying to output message for " \
722 __FILE__, __LINE__, (IV) xI_offset(xC), \
723 ((int) (eC - sC)), sC), 0)), \
724 sI), /* The input pattern printed up to the <--HERE */ \
726 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
727 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
729 /* Used to point after bad bytes for an error message, but avoid skipping
730 * past a nul byte. */
731 #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
733 /* Set up to clean up after our imminent demise */
734 #define PREPARE_TO_DIE \
737 SAVEFREESV(RExC_rx_sv); \
738 if (RExC_open_parens) \
739 SAVEFREEPV(RExC_open_parens); \
740 if (RExC_close_parens) \
741 SAVEFREEPV(RExC_close_parens); \
745 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
746 * arg. Show regex, up to a maximum length. If it's too long, chop and add
749 #define _FAIL(code) STMT_START { \
750 const char *ellipses = ""; \
751 IV len = RExC_precomp_end - RExC_precomp; \
754 if (len > RegexLengthToShowInErrorMessages) { \
755 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
756 len = RegexLengthToShowInErrorMessages - 10; \
762 #define FAIL(msg) _FAIL( \
763 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
764 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
766 #define FAIL2(msg,arg) _FAIL( \
767 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
768 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
770 #define FAIL3(msg,arg1,arg2) _FAIL( \
771 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
772 arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
775 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
777 #define Simple_vFAIL(m) STMT_START { \
778 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
779 m, REPORT_LOCATION_ARGS(RExC_parse)); \
783 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
785 #define vFAIL(m) STMT_START { \
791 * Like Simple_vFAIL(), but accepts two arguments.
793 #define Simple_vFAIL2(m,a1) STMT_START { \
794 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
795 REPORT_LOCATION_ARGS(RExC_parse)); \
799 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
801 #define vFAIL2(m,a1) STMT_START { \
803 Simple_vFAIL2(m, a1); \
808 * Like Simple_vFAIL(), but accepts three arguments.
810 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
811 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
812 REPORT_LOCATION_ARGS(RExC_parse)); \
816 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
818 #define vFAIL3(m,a1,a2) STMT_START { \
820 Simple_vFAIL3(m, a1, a2); \
824 * Like Simple_vFAIL(), but accepts four arguments.
826 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
827 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
828 REPORT_LOCATION_ARGS(RExC_parse)); \
831 #define vFAIL4(m,a1,a2,a3) STMT_START { \
833 Simple_vFAIL4(m, a1, a2, a3); \
836 /* A specialized version of vFAIL2 that works with UTF8f */
837 #define vFAIL2utf8f(m, a1) STMT_START { \
839 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
840 REPORT_LOCATION_ARGS(RExC_parse)); \
843 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
845 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
846 REPORT_LOCATION_ARGS(RExC_parse)); \
849 /* Setting this to NULL is a signal to not output warnings */
850 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \
852 RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\
853 RExC_copy_start_in_constructed = NULL; \
855 #define RESTORE_WARNINGS \
856 RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
858 /* Since a warning can be generated multiple times as the input is reparsed, we
859 * output it the first time we come to that point in the parse, but suppress it
860 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
861 * generate any warnings */
862 #define TO_OUTPUT_WARNINGS(loc) \
863 ( RExC_copy_start_in_constructed \
864 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
866 /* After we've emitted a warning, we save the position in the input so we don't
868 #define UPDATE_WARNINGS_LOC(loc) \
870 if (TO_OUTPUT_WARNINGS(loc)) { \
871 RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \
876 /* 'warns' is the output of the packWARNx macro used in 'code' */
877 #define _WARN_HELPER(loc, warns, code) \
879 if (! RExC_copy_start_in_constructed) { \
880 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
881 " expected at '%s'", \
882 __FILE__, __LINE__, loc); \
884 if (TO_OUTPUT_WARNINGS(loc)) { \
888 UPDATE_WARNINGS_LOC(loc); \
892 /* m is not necessarily a "literal string", in this macro */
893 #define warn_non_literal_string(loc, packed_warn, m) \
894 _WARN_HELPER(loc, packed_warn, \
895 Perl_warner(aTHX_ packed_warn, \
896 "%s" REPORT_LOCATION, \
897 m, REPORT_LOCATION_ARGS(loc)))
898 #define reg_warn_non_literal_string(loc, m) \
899 warn_non_literal_string(loc, packWARN(WARN_REGEXP), m)
901 #define ckWARN2_non_literal_string(loc, packwarn, m, a1) \
904 Size_t format_size = strlen(m) + strlen(REPORT_LOCATION)+ 1;\
905 Newx(format, format_size, char); \
906 my_strlcpy(format, m, format_size); \
907 my_strlcat(format, REPORT_LOCATION, format_size); \
908 SAVEFREEPV(format); \
909 _WARN_HELPER(loc, packwarn, \
910 Perl_ck_warner(aTHX_ packwarn, \
912 a1, REPORT_LOCATION_ARGS(loc))); \
915 #define ckWARNreg(loc,m) \
916 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
917 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
919 REPORT_LOCATION_ARGS(loc)))
921 #define vWARN(loc, m) \
922 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
923 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
925 REPORT_LOCATION_ARGS(loc))) \
927 #define vWARN_dep(loc, m) \
928 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
929 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
931 REPORT_LOCATION_ARGS(loc)))
933 #define ckWARNdep(loc,m) \
934 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
935 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
937 REPORT_LOCATION_ARGS(loc)))
939 #define ckWARNregdep(loc,m) \
940 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
941 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
944 REPORT_LOCATION_ARGS(loc)))
946 #define ckWARN2reg_d(loc,m, a1) \
947 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
948 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
950 a1, REPORT_LOCATION_ARGS(loc)))
952 #define ckWARN2reg(loc, m, a1) \
953 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
954 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
956 a1, REPORT_LOCATION_ARGS(loc)))
958 #define vWARN3(loc, m, a1, a2) \
959 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
960 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
962 a1, a2, REPORT_LOCATION_ARGS(loc)))
964 #define ckWARN3reg(loc, m, a1, a2) \
965 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
966 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
969 REPORT_LOCATION_ARGS(loc)))
971 #define vWARN4(loc, m, a1, a2, a3) \
972 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
973 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
976 REPORT_LOCATION_ARGS(loc)))
978 #define ckWARN4reg(loc, m, a1, a2, a3) \
979 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
980 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
983 REPORT_LOCATION_ARGS(loc)))
985 #define vWARN5(loc, m, a1, a2, a3, a4) \
986 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
987 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
990 REPORT_LOCATION_ARGS(loc)))
992 #define ckWARNexperimental(loc, class, m) \
993 _WARN_HELPER(loc, packWARN(class), \
994 Perl_ck_warner_d(aTHX_ packWARN(class), \
996 REPORT_LOCATION_ARGS(loc)))
998 /* Convert between a pointer to a node and its offset from the beginning of the
1000 #define REGNODE_p(offset) (RExC_emit_start + (offset))
1001 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
1003 /* Macros for recording node offsets. 20001227 mjd@plover.com
1004 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
1005 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
1006 * Element 0 holds the number n.
1007 * Position is 1 indexed.
1009 #ifndef RE_TRACK_PATTERN_OFFSETS
1010 #define Set_Node_Offset_To_R(offset,byte)
1011 #define Set_Node_Offset(node,byte)
1012 #define Set_Cur_Node_Offset
1013 #define Set_Node_Length_To_R(node,len)
1014 #define Set_Node_Length(node,len)
1015 #define Set_Node_Cur_Length(node,start)
1016 #define Node_Offset(n)
1017 #define Node_Length(n)
1018 #define Set_Node_Offset_Length(node,offset,len)
1019 #define ProgLen(ri) ri->u.proglen
1020 #define SetProgLen(ri,x) ri->u.proglen = x
1021 #define Track_Code(code)
1023 #define ProgLen(ri) ri->u.offsets[0]
1024 #define SetProgLen(ri,x) ri->u.offsets[0] = x
1025 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
1026 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
1027 __LINE__, (int)(offset), (int)(byte))); \
1028 if((offset) < 0) { \
1029 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
1032 RExC_offsets[2*(offset)-1] = (byte); \
1036 #define Set_Node_Offset(node,byte) \
1037 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1038 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1040 #define Set_Node_Length_To_R(node,len) STMT_START { \
1041 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
1042 __LINE__, (int)(node), (int)(len))); \
1044 Perl_croak(aTHX_ "value of node is %d in Length macro", \
1047 RExC_offsets[2*(node)] = (len); \
1051 #define Set_Node_Length(node,len) \
1052 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1053 #define Set_Node_Cur_Length(node, start) \
1054 Set_Node_Length(node, RExC_parse - start)
1056 /* Get offsets and lengths */
1057 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1058 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1060 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1061 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1062 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1065 #define Track_Code(code) STMT_START { code } STMT_END
1068 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1069 #define EXPERIMENTAL_INPLACESCAN
1070 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1074 Perl_re_printf(pTHX_ const char *fmt, ...)
1078 PerlIO *f= Perl_debug_log;
1079 PERL_ARGS_ASSERT_RE_PRINTF;
1081 result = PerlIO_vprintf(f, fmt, ap);
1087 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1091 PerlIO *f= Perl_debug_log;
1092 PERL_ARGS_ASSERT_RE_INDENTF;
1093 va_start(ap, depth);
1094 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1095 result = PerlIO_vprintf(f, fmt, ap);
1099 #endif /* DEBUGGING */
1101 #define DEBUG_RExC_seen() \
1102 DEBUG_OPTIMISE_MORE_r({ \
1103 Perl_re_printf( aTHX_ "RExC_seen: "); \
1105 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1106 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1108 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1109 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1111 if (RExC_seen & REG_GPOS_SEEN) \
1112 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1114 if (RExC_seen & REG_RECURSE_SEEN) \
1115 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1117 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1118 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1120 if (RExC_seen & REG_VERBARG_SEEN) \
1121 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1123 if (RExC_seen & REG_CUTGROUP_SEEN) \
1124 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1126 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1127 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1129 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1130 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1132 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1133 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1135 Perl_re_printf( aTHX_ "\n"); \
1138 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1139 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1144 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1145 const char *close_str)
1150 Perl_re_printf( aTHX_ "%s", open_str);
1151 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1152 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1153 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1154 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1155 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1156 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1157 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1158 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1159 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1160 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1161 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1162 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1163 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1164 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1165 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1166 Perl_re_printf( aTHX_ "%s", close_str);
1171 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1172 U32 depth, int is_inf)
1174 GET_RE_DEBUG_FLAGS_DECL;
1176 DEBUG_OPTIMISE_MORE_r({
1179 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1183 (IV)data->pos_delta,
1187 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1189 Perl_re_printf( aTHX_
1190 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1192 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1193 is_inf ? "INF " : ""
1196 if (data->last_found) {
1198 Perl_re_printf(aTHX_
1199 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1200 SvPVX_const(data->last_found),
1202 (IV)data->last_start_min,
1203 (IV)data->last_start_max
1206 for (i = 0; i < 2; i++) {
1207 Perl_re_printf(aTHX_
1208 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1209 data->cur_is_floating == i ? "*" : "",
1210 i ? "Float" : "Fixed",
1211 SvPVX_const(data->substrs[i].str),
1212 (IV)data->substrs[i].min_offset,
1213 (IV)data->substrs[i].max_offset
1215 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1219 Perl_re_printf( aTHX_ "\n");
1225 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1226 regnode *scan, U32 depth, U32 flags)
1228 GET_RE_DEBUG_FLAGS_DECL;
1235 Next = regnext(scan);
1236 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1237 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1240 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1241 Next ? (REG_NODE_NUM(Next)) : 0 );
1242 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1243 Perl_re_printf( aTHX_ "\n");
1248 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1249 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1251 # define DEBUG_PEEP(str, scan, depth, flags) \
1252 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1255 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1256 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1260 /* =========================================================
1261 * BEGIN edit_distance stuff.
1263 * This calculates how many single character changes of any type are needed to
1264 * transform a string into another one. It is taken from version 3.1 of
1266 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1269 /* Our unsorted dictionary linked list. */
1270 /* Note we use UVs, not chars. */
1275 struct dictionary* next;
1277 typedef struct dictionary item;
1280 PERL_STATIC_INLINE item*
1281 push(UV key, item* curr)
1284 Newx(head, 1, item);
1292 PERL_STATIC_INLINE item*
1293 find(item* head, UV key)
1295 item* iterator = head;
1297 if (iterator->key == key){
1300 iterator = iterator->next;
1306 PERL_STATIC_INLINE item*
1307 uniquePush(item* head, UV key)
1309 item* iterator = head;
1312 if (iterator->key == key) {
1315 iterator = iterator->next;
1318 return push(key, head);
1321 PERL_STATIC_INLINE void
1322 dict_free(item* head)
1324 item* iterator = head;
1327 item* temp = iterator;
1328 iterator = iterator->next;
1335 /* End of Dictionary Stuff */
1337 /* All calculations/work are done here */
1339 S_edit_distance(const UV* src,
1341 const STRLEN x, /* length of src[] */
1342 const STRLEN y, /* length of tgt[] */
1343 const SSize_t maxDistance
1347 UV swapCount, swapScore, targetCharCount, i, j;
1349 UV score_ceil = x + y;
1351 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1353 /* intialize matrix start values */
1354 Newx(scores, ( (x + 2) * (y + 2)), UV);
1355 scores[0] = score_ceil;
1356 scores[1 * (y + 2) + 0] = score_ceil;
1357 scores[0 * (y + 2) + 1] = score_ceil;
1358 scores[1 * (y + 2) + 1] = 0;
1359 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1364 for (i=1;i<=x;i++) {
1366 head = uniquePush(head, src[i]);
1367 scores[(i+1) * (y + 2) + 1] = i;
1368 scores[(i+1) * (y + 2) + 0] = score_ceil;
1371 for (j=1;j<=y;j++) {
1374 head = uniquePush(head, tgt[j]);
1375 scores[1 * (y + 2) + (j + 1)] = j;
1376 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1379 targetCharCount = find(head, tgt[j-1])->value;
1380 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1382 if (src[i-1] != tgt[j-1]){
1383 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));
1387 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1391 find(head, src[i-1])->value = i;
1395 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1398 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1402 /* END of edit_distance() stuff
1403 * ========================================================= */
1405 /* Mark that we cannot extend a found fixed substring at this point.
1406 Update the longest found anchored substring or the longest found
1407 floating substrings if needed. */
1410 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1411 SSize_t *minlenp, int is_inf)
1413 const STRLEN l = CHR_SVLEN(data->last_found);
1414 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1415 const STRLEN old_l = CHR_SVLEN(longest_sv);
1416 GET_RE_DEBUG_FLAGS_DECL;
1418 PERL_ARGS_ASSERT_SCAN_COMMIT;
1420 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1421 const U8 i = data->cur_is_floating;
1422 SvSetMagicSV(longest_sv, data->last_found);
1423 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1426 data->substrs[0].max_offset = data->substrs[0].min_offset;
1428 data->substrs[1].max_offset = (l
1429 ? data->last_start_max
1430 : (data->pos_delta > SSize_t_MAX - data->pos_min
1432 : data->pos_min + data->pos_delta));
1434 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1435 data->substrs[1].max_offset = SSize_t_MAX;
1438 if (data->flags & SF_BEFORE_EOL)
1439 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1441 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1442 data->substrs[i].minlenp = minlenp;
1443 data->substrs[i].lookbehind = 0;
1446 SvCUR_set(data->last_found, 0);
1448 SV * const sv = data->last_found;
1449 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1450 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1455 data->last_end = -1;
1456 data->flags &= ~SF_BEFORE_EOL;
1457 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1460 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1461 * list that describes which code points it matches */
1464 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1466 /* Set the SSC 'ssc' to match an empty string or any code point */
1468 PERL_ARGS_ASSERT_SSC_ANYTHING;
1470 assert(is_ANYOF_SYNTHETIC(ssc));
1472 /* mortalize so won't leak */
1473 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1474 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1478 S_ssc_is_anything(const regnode_ssc *ssc)
1480 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1481 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1482 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1483 * in any way, so there's no point in using it */
1488 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1490 assert(is_ANYOF_SYNTHETIC(ssc));
1492 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1496 /* See if the list consists solely of the range 0 - Infinity */
1497 invlist_iterinit(ssc->invlist);
1498 ret = invlist_iternext(ssc->invlist, &start, &end)
1502 invlist_iterfinish(ssc->invlist);
1508 /* If e.g., both \w and \W are set, matches everything */
1509 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1511 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1512 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1522 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1524 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1525 * string, any code point, or any posix class under locale */
1527 PERL_ARGS_ASSERT_SSC_INIT;
1529 Zero(ssc, 1, regnode_ssc);
1530 set_ANYOF_SYNTHETIC(ssc);
1531 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1534 /* If any portion of the regex is to operate under locale rules that aren't
1535 * fully known at compile time, initialization includes it. The reason
1536 * this isn't done for all regexes is that the optimizer was written under
1537 * the assumption that locale was all-or-nothing. Given the complexity and
1538 * lack of documentation in the optimizer, and that there are inadequate
1539 * test cases for locale, many parts of it may not work properly, it is
1540 * safest to avoid locale unless necessary. */
1541 if (RExC_contains_locale) {
1542 ANYOF_POSIXL_SETALL(ssc);
1545 ANYOF_POSIXL_ZERO(ssc);
1550 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1551 const regnode_ssc *ssc)
1553 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1554 * to the list of code points matched, and locale posix classes; hence does
1555 * not check its flags) */
1560 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1562 assert(is_ANYOF_SYNTHETIC(ssc));
1564 invlist_iterinit(ssc->invlist);
1565 ret = invlist_iternext(ssc->invlist, &start, &end)
1569 invlist_iterfinish(ssc->invlist);
1575 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1582 #define INVLIST_INDEX 0
1583 #define ONLY_LOCALE_MATCHES_INDEX 1
1584 #define DEFERRED_USER_DEFINED_INDEX 2
1587 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1588 const regnode_charclass* const node)
1590 /* Returns a mortal inversion list defining which code points are matched
1591 * by 'node', which is of type ANYOF. Handles complementing the result if
1592 * appropriate. If some code points aren't knowable at this time, the
1593 * returned list must, and will, contain every code point that is a
1598 SV* only_utf8_locale_invlist = NULL;
1600 const U32 n = ARG(node);
1601 bool new_node_has_latin1 = FALSE;
1602 const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1604 : ANYOF_FLAGS(node);
1606 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1608 /* Look at the data structure created by S_set_ANYOF_arg() */
1609 if (n != ANYOF_ONLY_HAS_BITMAP) {
1610 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1611 AV * const av = MUTABLE_AV(SvRV(rv));
1612 SV **const ary = AvARRAY(av);
1613 assert(RExC_rxi->data->what[n] == 's');
1615 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1617 /* Here there are things that won't be known until runtime -- we
1618 * have to assume it could be anything */
1619 invlist = sv_2mortal(_new_invlist(1));
1620 return _add_range_to_invlist(invlist, 0, UV_MAX);
1622 else if (ary[INVLIST_INDEX]) {
1624 /* Use the node's inversion list */
1625 invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1628 /* Get the code points valid only under UTF-8 locales */
1629 if ( (flags & ANYOFL_FOLD)
1630 && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1632 only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1637 invlist = sv_2mortal(_new_invlist(0));
1640 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1641 * code points, and an inversion list for the others, but if there are code
1642 * points that should match only conditionally on the target string being
1643 * UTF-8, those are placed in the inversion list, and not the bitmap.
1644 * Since there are circumstances under which they could match, they are
1645 * included in the SSC. But if the ANYOF node is to be inverted, we have
1646 * to exclude them here, so that when we invert below, the end result
1647 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1648 * have to do this here before we add the unconditionally matched code
1650 if (flags & ANYOF_INVERT) {
1651 _invlist_intersection_complement_2nd(invlist,
1656 /* Add in the points from the bit map */
1657 if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1658 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1659 if (ANYOF_BITMAP_TEST(node, i)) {
1660 unsigned int start = i++;
1662 for (; i < NUM_ANYOF_CODE_POINTS
1663 && ANYOF_BITMAP_TEST(node, i); ++i)
1667 invlist = _add_range_to_invlist(invlist, start, i-1);
1668 new_node_has_latin1 = TRUE;
1673 /* If this can match all upper Latin1 code points, have to add them
1674 * as well. But don't add them if inverting, as when that gets done below,
1675 * it would exclude all these characters, including the ones it shouldn't
1676 * that were added just above */
1677 if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1678 && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1680 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1683 /* Similarly for these */
1684 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1685 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1688 if (flags & ANYOF_INVERT) {
1689 _invlist_invert(invlist);
1691 else if (flags & ANYOFL_FOLD) {
1692 if (new_node_has_latin1) {
1694 /* Under /li, any 0-255 could fold to any other 0-255, depending on
1695 * the locale. We can skip this if there are no 0-255 at all. */
1696 _invlist_union(invlist, PL_Latin1, &invlist);
1698 invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1699 invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1702 if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1703 invlist = add_cp_to_invlist(invlist, 'I');
1705 if (_invlist_contains_cp(invlist,
1706 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1708 invlist = add_cp_to_invlist(invlist, 'i');
1713 /* Similarly add the UTF-8 locale possible matches. These have to be
1714 * deferred until after the non-UTF-8 locale ones are taken care of just
1715 * above, or it leads to wrong results under ANYOF_INVERT */
1716 if (only_utf8_locale_invlist) {
1717 _invlist_union_maybe_complement_2nd(invlist,
1718 only_utf8_locale_invlist,
1719 flags & ANYOF_INVERT,
1726 /* These two functions currently do the exact same thing */
1727 #define ssc_init_zero ssc_init
1729 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1730 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1732 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1733 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1734 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1737 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1738 const regnode_charclass *and_with)
1740 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1741 * another SSC or a regular ANYOF class. Can create false positives. */
1744 U8 and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1746 : ANYOF_FLAGS(and_with);
1749 PERL_ARGS_ASSERT_SSC_AND;
1751 assert(is_ANYOF_SYNTHETIC(ssc));
1753 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1754 * the code point inversion list and just the relevant flags */
1755 if (is_ANYOF_SYNTHETIC(and_with)) {
1756 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1757 anded_flags = and_with_flags;
1759 /* XXX This is a kludge around what appears to be deficiencies in the
1760 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1761 * there are paths through the optimizer where it doesn't get weeded
1762 * out when it should. And if we don't make some extra provision for
1763 * it like the code just below, it doesn't get added when it should.
1764 * This solution is to add it only when AND'ing, which is here, and
1765 * only when what is being AND'ed is the pristine, original node
1766 * matching anything. Thus it is like adding it to ssc_anything() but
1767 * only when the result is to be AND'ed. Probably the same solution
1768 * could be adopted for the same problem we have with /l matching,
1769 * which is solved differently in S_ssc_init(), and that would lead to
1770 * fewer false positives than that solution has. But if this solution
1771 * creates bugs, the consequences are only that a warning isn't raised
1772 * that should be; while the consequences for having /l bugs is
1773 * incorrect matches */
1774 if (ssc_is_anything((regnode_ssc *)and_with)) {
1775 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1779 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1780 if (OP(and_with) == ANYOFD) {
1781 anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1784 anded_flags = and_with_flags
1785 &( ANYOF_COMMON_FLAGS
1786 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1787 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1788 if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1790 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1795 ANYOF_FLAGS(ssc) &= anded_flags;
1797 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1798 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1799 * 'and_with' may be inverted. When not inverted, we have the situation of
1801 * (C1 | P1) & (C2 | P2)
1802 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1803 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1804 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1805 * <= ((C1 & C2) | P1 | P2)
1806 * Alternatively, the last few steps could be:
1807 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1808 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1809 * <= (C1 | C2 | (P1 & P2))
1810 * We favor the second approach if either P1 or P2 is non-empty. This is
1811 * because these components are a barrier to doing optimizations, as what
1812 * they match cannot be known until the moment of matching as they are
1813 * dependent on the current locale, 'AND"ing them likely will reduce or
1815 * But we can do better if we know that C1,P1 are in their initial state (a
1816 * frequent occurrence), each matching everything:
1817 * (<everything>) & (C2 | P2) = C2 | P2
1818 * Similarly, if C2,P2 are in their initial state (again a frequent
1819 * occurrence), the result is a no-op
1820 * (C1 | P1) & (<everything>) = C1 | P1
1823 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1824 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1825 * <= (C1 & ~C2) | (P1 & ~P2)
1828 if ((and_with_flags & ANYOF_INVERT)
1829 && ! is_ANYOF_SYNTHETIC(and_with))
1833 ssc_intersection(ssc,
1835 FALSE /* Has already been inverted */
1838 /* If either P1 or P2 is empty, the intersection will be also; can skip
1840 if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1841 ANYOF_POSIXL_ZERO(ssc);
1843 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1845 /* Note that the Posix class component P from 'and_with' actually
1847 * P = Pa | Pb | ... | Pn
1848 * where each component is one posix class, such as in [\w\s].
1850 * ~P = ~(Pa | Pb | ... | Pn)
1851 * = ~Pa & ~Pb & ... & ~Pn
1852 * <= ~Pa | ~Pb | ... | ~Pn
1853 * The last is something we can easily calculate, but unfortunately
1854 * is likely to have many false positives. We could do better
1855 * in some (but certainly not all) instances if two classes in
1856 * P have known relationships. For example
1857 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1859 * :lower: & :print: = :lower:
1860 * And similarly for classes that must be disjoint. For example,
1861 * since \s and \w can have no elements in common based on rules in
1862 * the POSIX standard,
1863 * \w & ^\S = nothing
1864 * Unfortunately, some vendor locales do not meet the Posix
1865 * standard, in particular almost everything by Microsoft.
1866 * The loop below just changes e.g., \w into \W and vice versa */
1868 regnode_charclass_posixl temp;
1869 int add = 1; /* To calculate the index of the complement */
1871 Zero(&temp, 1, regnode_charclass_posixl);
1872 ANYOF_POSIXL_ZERO(&temp);
1873 for (i = 0; i < ANYOF_MAX; i++) {
1875 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1876 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1878 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1879 ANYOF_POSIXL_SET(&temp, i + add);
1881 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1883 ANYOF_POSIXL_AND(&temp, ssc);
1885 } /* else ssc already has no posixes */
1886 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1887 in its initial state */
1888 else if (! is_ANYOF_SYNTHETIC(and_with)
1889 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1891 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1892 * copy it over 'ssc' */
1893 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1894 if (is_ANYOF_SYNTHETIC(and_with)) {
1895 StructCopy(and_with, ssc, regnode_ssc);
1898 ssc->invlist = anded_cp_list;
1899 ANYOF_POSIXL_ZERO(ssc);
1900 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1901 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1905 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1906 || (and_with_flags & ANYOF_MATCHES_POSIXL))
1908 /* One or the other of P1, P2 is non-empty. */
1909 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1910 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1912 ssc_union(ssc, anded_cp_list, FALSE);
1914 else { /* P1 = P2 = empty */
1915 ssc_intersection(ssc, anded_cp_list, FALSE);
1921 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1922 const regnode_charclass *or_with)
1924 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1925 * another SSC or a regular ANYOF class. Can create false positives if
1926 * 'or_with' is to be inverted. */
1930 U8 or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
1932 : ANYOF_FLAGS(or_with);
1934 PERL_ARGS_ASSERT_SSC_OR;
1936 assert(is_ANYOF_SYNTHETIC(ssc));
1938 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1939 * the code point inversion list and just the relevant flags */
1940 if (is_ANYOF_SYNTHETIC(or_with)) {
1941 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1942 ored_flags = or_with_flags;
1945 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1946 ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
1947 if (OP(or_with) != ANYOFD) {
1950 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1951 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1952 if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
1954 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1959 ANYOF_FLAGS(ssc) |= ored_flags;
1961 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1962 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1963 * 'or_with' may be inverted. When not inverted, we have the simple
1964 * situation of computing:
1965 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1966 * If P1|P2 yields a situation with both a class and its complement are
1967 * set, like having both \w and \W, this matches all code points, and we
1968 * can delete these from the P component of the ssc going forward. XXX We
1969 * might be able to delete all the P components, but I (khw) am not certain
1970 * about this, and it is better to be safe.
1973 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1974 * <= (C1 | P1) | ~C2
1975 * <= (C1 | ~C2) | P1
1976 * (which results in actually simpler code than the non-inverted case)
1979 if ((or_with_flags & ANYOF_INVERT)
1980 && ! is_ANYOF_SYNTHETIC(or_with))
1982 /* We ignore P2, leaving P1 going forward */
1983 } /* else Not inverted */
1984 else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
1985 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1986 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1988 for (i = 0; i < ANYOF_MAX; i += 2) {
1989 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1991 ssc_match_all_cp(ssc);
1992 ANYOF_POSIXL_CLEAR(ssc, i);
1993 ANYOF_POSIXL_CLEAR(ssc, i+1);
2001 FALSE /* Already has been inverted */
2005 PERL_STATIC_INLINE void
2006 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2008 PERL_ARGS_ASSERT_SSC_UNION;
2010 assert(is_ANYOF_SYNTHETIC(ssc));
2012 _invlist_union_maybe_complement_2nd(ssc->invlist,
2018 PERL_STATIC_INLINE void
2019 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2021 const bool invert2nd)
2023 PERL_ARGS_ASSERT_SSC_INTERSECTION;
2025 assert(is_ANYOF_SYNTHETIC(ssc));
2027 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2033 PERL_STATIC_INLINE void
2034 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2036 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2038 assert(is_ANYOF_SYNTHETIC(ssc));
2040 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2043 PERL_STATIC_INLINE void
2044 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2046 /* AND just the single code point 'cp' into the SSC 'ssc' */
2048 SV* cp_list = _new_invlist(2);
2050 PERL_ARGS_ASSERT_SSC_CP_AND;
2052 assert(is_ANYOF_SYNTHETIC(ssc));
2054 cp_list = add_cp_to_invlist(cp_list, cp);
2055 ssc_intersection(ssc, cp_list,
2056 FALSE /* Not inverted */
2058 SvREFCNT_dec_NN(cp_list);
2061 PERL_STATIC_INLINE void
2062 S_ssc_clear_locale(regnode_ssc *ssc)
2064 /* Set the SSC 'ssc' to not match any locale things */
2065 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2067 assert(is_ANYOF_SYNTHETIC(ssc));
2069 ANYOF_POSIXL_ZERO(ssc);
2070 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2073 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2076 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2078 /* The synthetic start class is used to hopefully quickly winnow down
2079 * places where a pattern could start a match in the target string. If it
2080 * doesn't really narrow things down that much, there isn't much point to
2081 * having the overhead of using it. This function uses some very crude
2082 * heuristics to decide if to use the ssc or not.
2084 * It returns TRUE if 'ssc' rules out more than half what it considers to
2085 * be the "likely" possible matches, but of course it doesn't know what the
2086 * actual things being matched are going to be; these are only guesses
2088 * For /l matches, it assumes that the only likely matches are going to be
2089 * in the 0-255 range, uniformly distributed, so half of that is 127
2090 * For /a and /d matches, it assumes that the likely matches will be just
2091 * the ASCII range, so half of that is 63
2092 * For /u and there isn't anything matching above the Latin1 range, it
2093 * assumes that that is the only range likely to be matched, and uses
2094 * half that as the cut-off: 127. If anything matches above Latin1,
2095 * it assumes that all of Unicode could match (uniformly), except for
2096 * non-Unicode code points and things in the General Category "Other"
2097 * (unassigned, private use, surrogates, controls and formats). This
2098 * is a much large number. */
2100 U32 count = 0; /* Running total of number of code points matched by
2102 UV start, end; /* Start and end points of current range in inversion
2103 XXX outdated. UTF-8 locales are common, what about invert? list */
2104 const U32 max_code_points = (LOC)
2106 : (( ! UNI_SEMANTICS
2107 || invlist_highest(ssc->invlist) < 256)
2110 const U32 max_match = max_code_points / 2;
2112 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2114 invlist_iterinit(ssc->invlist);
2115 while (invlist_iternext(ssc->invlist, &start, &end)) {
2116 if (start >= max_code_points) {
2119 end = MIN(end, max_code_points - 1);
2120 count += end - start + 1;
2121 if (count >= max_match) {
2122 invlist_iterfinish(ssc->invlist);
2132 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2134 /* The inversion list in the SSC is marked mortal; now we need a more
2135 * permanent copy, which is stored the same way that is done in a regular
2136 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2139 SV* invlist = invlist_clone(ssc->invlist, NULL);
2141 PERL_ARGS_ASSERT_SSC_FINALIZE;
2143 assert(is_ANYOF_SYNTHETIC(ssc));
2145 /* The code in this file assumes that all but these flags aren't relevant
2146 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2147 * by the time we reach here */
2148 assert(! (ANYOF_FLAGS(ssc)
2149 & ~( ANYOF_COMMON_FLAGS
2150 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2151 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2153 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2155 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2156 SvREFCNT_dec(invlist);
2158 /* Make sure is clone-safe */
2159 ssc->invlist = NULL;
2161 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2162 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2163 OP(ssc) = ANYOFPOSIXL;
2165 else if (RExC_contains_locale) {
2169 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2172 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2173 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2174 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2175 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2176 ? (TRIE_LIST_CUR( idx ) - 1) \
2182 dump_trie(trie,widecharmap,revcharmap)
2183 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2184 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2186 These routines dump out a trie in a somewhat readable format.
2187 The _interim_ variants are used for debugging the interim
2188 tables that are used to generate the final compressed
2189 representation which is what dump_trie expects.
2191 Part of the reason for their existence is to provide a form
2192 of documentation as to how the different representations function.
2197 Dumps the final compressed table form of the trie to Perl_debug_log.
2198 Used for debugging make_trie().
2202 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2203 AV *revcharmap, U32 depth)
2206 SV *sv=sv_newmortal();
2207 int colwidth= widecharmap ? 6 : 4;
2209 GET_RE_DEBUG_FLAGS_DECL;
2211 PERL_ARGS_ASSERT_DUMP_TRIE;
2213 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2214 depth+1, "Match","Base","Ofs" );
2216 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2217 SV ** const tmp = av_fetch( revcharmap, state, 0);
2219 Perl_re_printf( aTHX_ "%*s",
2221 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2222 PL_colors[0], PL_colors[1],
2223 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2224 PERL_PV_ESCAPE_FIRSTCHAR
2229 Perl_re_printf( aTHX_ "\n");
2230 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2232 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2233 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2234 Perl_re_printf( aTHX_ "\n");
2236 for( state = 1 ; state < trie->statecount ; state++ ) {
2237 const U32 base = trie->states[ state ].trans.base;
2239 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2241 if ( trie->states[ state ].wordnum ) {
2242 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2244 Perl_re_printf( aTHX_ "%6s", "" );
2247 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2252 while( ( base + ofs < trie->uniquecharcount ) ||
2253 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2254 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2258 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2260 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2261 if ( ( base + ofs >= trie->uniquecharcount )
2262 && ( base + ofs - trie->uniquecharcount
2264 && trie->trans[ base + ofs
2265 - trie->uniquecharcount ].check == state )
2267 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2268 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2271 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2275 Perl_re_printf( aTHX_ "]");
2278 Perl_re_printf( aTHX_ "\n" );
2280 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2282 for (word=1; word <= trie->wordcount; word++) {
2283 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2284 (int)word, (int)(trie->wordinfo[word].prev),
2285 (int)(trie->wordinfo[word].len));
2287 Perl_re_printf( aTHX_ "\n" );
2290 Dumps a fully constructed but uncompressed trie in list form.
2291 List tries normally only are used for construction when the number of
2292 possible chars (trie->uniquecharcount) is very high.
2293 Used for debugging make_trie().
2296 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2297 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2301 SV *sv=sv_newmortal();
2302 int colwidth= widecharmap ? 6 : 4;
2303 GET_RE_DEBUG_FLAGS_DECL;
2305 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2307 /* print out the table precompression. */
2308 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2310 Perl_re_indentf( aTHX_ "%s",
2311 depth+1, "------:-----+-----------------\n" );
2313 for( state=1 ; state < next_alloc ; state ++ ) {
2316 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2317 depth+1, (UV)state );
2318 if ( ! trie->states[ state ].wordnum ) {
2319 Perl_re_printf( aTHX_ "%5s| ","");
2321 Perl_re_printf( aTHX_ "W%4x| ",
2322 trie->states[ state ].wordnum
2325 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2326 SV ** const tmp = av_fetch( revcharmap,
2327 TRIE_LIST_ITEM(state, charid).forid, 0);
2329 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2331 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2333 PL_colors[0], PL_colors[1],
2334 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2335 | PERL_PV_ESCAPE_FIRSTCHAR
2337 TRIE_LIST_ITEM(state, charid).forid,
2338 (UV)TRIE_LIST_ITEM(state, charid).newstate
2341 Perl_re_printf( aTHX_ "\n%*s| ",
2342 (int)((depth * 2) + 14), "");
2345 Perl_re_printf( aTHX_ "\n");
2350 Dumps a fully constructed but uncompressed trie in table form.
2351 This is the normal DFA style state transition table, with a few
2352 twists to facilitate compression later.
2353 Used for debugging make_trie().
2356 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2357 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2362 SV *sv=sv_newmortal();
2363 int colwidth= widecharmap ? 6 : 4;
2364 GET_RE_DEBUG_FLAGS_DECL;
2366 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2369 print out the table precompression so that we can do a visual check
2370 that they are identical.
2373 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2375 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2376 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2378 Perl_re_printf( aTHX_ "%*s",
2380 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2381 PL_colors[0], PL_colors[1],
2382 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2383 PERL_PV_ESCAPE_FIRSTCHAR
2389 Perl_re_printf( aTHX_ "\n");
2390 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2392 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2393 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2396 Perl_re_printf( aTHX_ "\n" );
2398 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2400 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2402 (UV)TRIE_NODENUM( state ) );
2404 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2405 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2407 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2409 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2411 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2412 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2413 (UV)trie->trans[ state ].check );
2415 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2416 (UV)trie->trans[ state ].check,
2417 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2425 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2426 startbranch: the first branch in the whole branch sequence
2427 first : start branch of sequence of branch-exact nodes.
2428 May be the same as startbranch
2429 last : Thing following the last branch.
2430 May be the same as tail.
2431 tail : item following the branch sequence
2432 count : words in the sequence
2433 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2434 depth : indent depth
2436 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2438 A trie is an N'ary tree where the branches are determined by digital
2439 decomposition of the key. IE, at the root node you look up the 1st character and
2440 follow that branch repeat until you find the end of the branches. Nodes can be
2441 marked as "accepting" meaning they represent a complete word. Eg:
2445 would convert into the following structure. Numbers represent states, letters
2446 following numbers represent valid transitions on the letter from that state, if
2447 the number is in square brackets it represents an accepting state, otherwise it
2448 will be in parenthesis.
2450 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2454 (1) +-i->(6)-+-s->[7]
2456 +-s->(3)-+-h->(4)-+-e->[5]
2458 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2460 This shows that when matching against the string 'hers' we will begin at state 1
2461 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2462 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2463 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2464 single traverse. We store a mapping from accepting to state to which word was
2465 matched, and then when we have multiple possibilities we try to complete the
2466 rest of the regex in the order in which they occurred in the alternation.
2468 The only prior NFA like behaviour that would be changed by the TRIE support is
2469 the silent ignoring of duplicate alternations which are of the form:
2471 / (DUPE|DUPE) X? (?{ ... }) Y /x
2473 Thus EVAL blocks following a trie may be called a different number of times with
2474 and without the optimisation. With the optimisations dupes will be silently
2475 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2476 the following demonstrates:
2478 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2480 which prints out 'word' three times, but
2482 'words'=~/(word|word|word)(?{ print $1 })S/
2484 which doesnt print it out at all. This is due to other optimisations kicking in.
2486 Example of what happens on a structural level:
2488 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2490 1: CURLYM[1] {1,32767}(18)
2501 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2502 and should turn into:
2504 1: CURLYM[1] {1,32767}(18)
2506 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2514 Cases where tail != last would be like /(?foo|bar)baz/:
2524 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2525 and would end up looking like:
2528 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2535 d = uvchr_to_utf8_flags(d, uv, 0);
2537 is the recommended Unicode-aware way of saying
2542 #define TRIE_STORE_REVCHAR(val) \
2545 SV *zlopp = newSV(UTF8_MAXBYTES); \
2546 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2547 unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2549 SvCUR_set(zlopp, kapow - flrbbbbb); \
2552 av_push(revcharmap, zlopp); \
2554 char ooooff = (char)val; \
2555 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2559 /* This gets the next character from the input, folding it if not already
2561 #define TRIE_READ_CHAR STMT_START { \
2564 /* if it is UTF then it is either already folded, or does not need \
2566 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2568 else if (folder == PL_fold_latin1) { \
2569 /* This folder implies Unicode rules, which in the range expressible \
2570 * by not UTF is the lower case, with the two exceptions, one of \
2571 * which should have been taken care of before calling this */ \
2572 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2573 uvc = toLOWER_L1(*uc); \
2574 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2577 /* raw data, will be folded later if needed */ \
2585 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2586 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2587 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2588 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2589 TRIE_LIST_LEN( state ) = ging; \
2591 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2592 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2593 TRIE_LIST_CUR( state )++; \
2596 #define TRIE_LIST_NEW(state) STMT_START { \
2597 Newx( trie->states[ state ].trans.list, \
2598 4, reg_trie_trans_le ); \
2599 TRIE_LIST_CUR( state ) = 1; \
2600 TRIE_LIST_LEN( state ) = 4; \
2603 #define TRIE_HANDLE_WORD(state) STMT_START { \
2604 U16 dupe= trie->states[ state ].wordnum; \
2605 regnode * const noper_next = regnext( noper ); \
2608 /* store the word for dumping */ \
2610 if (OP(noper) != NOTHING) \
2611 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2613 tmp = newSVpvn_utf8( "", 0, UTF ); \
2614 av_push( trie_words, tmp ); \
2618 trie->wordinfo[curword].prev = 0; \
2619 trie->wordinfo[curword].len = wordlen; \
2620 trie->wordinfo[curword].accept = state; \
2622 if ( noper_next < tail ) { \
2624 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2626 trie->jump[curword] = (U16)(noper_next - convert); \
2628 jumper = noper_next; \
2630 nextbranch= regnext(cur); \
2634 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2635 /* chain, so that when the bits of chain are later */\
2636 /* linked together, the dups appear in the chain */\
2637 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2638 trie->wordinfo[dupe].prev = curword; \
2640 /* we haven't inserted this word yet. */ \
2641 trie->states[ state ].wordnum = curword; \
2646 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2647 ( ( base + charid >= ucharcount \
2648 && base + charid < ubound \
2649 && state == trie->trans[ base - ucharcount + charid ].check \
2650 && trie->trans[ base - ucharcount + charid ].next ) \
2651 ? trie->trans[ base - ucharcount + charid ].next \
2652 : ( state==1 ? special : 0 ) \
2655 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2657 TRIE_BITMAP_SET(trie, uvc); \
2658 /* store the folded codepoint */ \
2660 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2663 /* store first byte of utf8 representation of */ \
2664 /* variant codepoints */ \
2665 if (! UVCHR_IS_INVARIANT(uvc)) { \
2666 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2671 #define MADE_JUMP_TRIE 2
2672 #define MADE_EXACT_TRIE 4
2675 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2676 regnode *first, regnode *last, regnode *tail,
2677 U32 word_count, U32 flags, U32 depth)
2679 /* first pass, loop through and scan words */
2680 reg_trie_data *trie;
2681 HV *widecharmap = NULL;
2682 AV *revcharmap = newAV();
2688 regnode *jumper = NULL;
2689 regnode *nextbranch = NULL;
2690 regnode *convert = NULL;
2691 U32 *prev_states; /* temp array mapping each state to previous one */
2692 /* we just use folder as a flag in utf8 */
2693 const U8 * folder = NULL;
2695 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2696 * which stands for one trie structure, one hash, optionally followed
2699 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2700 AV *trie_words = NULL;
2701 /* along with revcharmap, this only used during construction but both are
2702 * useful during debugging so we store them in the struct when debugging.
2705 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2706 STRLEN trie_charcount=0;
2708 SV *re_trie_maxbuff;
2709 GET_RE_DEBUG_FLAGS_DECL;
2711 PERL_ARGS_ASSERT_MAKE_TRIE;
2713 PERL_UNUSED_ARG(depth);
2717 case EXACT: case EXACT_REQ8: case EXACTL: break;
2721 case EXACTFLU8: folder = PL_fold_latin1; break;
2722 case EXACTF: folder = PL_fold; break;
2723 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2726 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2728 trie->startstate = 1;
2729 trie->wordcount = word_count;
2730 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2731 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2732 if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2733 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2734 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2735 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2738 trie_words = newAV();
2741 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2742 assert(re_trie_maxbuff);
2743 if (!SvIOK(re_trie_maxbuff)) {
2744 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2746 DEBUG_TRIE_COMPILE_r({
2747 Perl_re_indentf( aTHX_
2748 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2750 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2751 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2754 /* Find the node we are going to overwrite */
2755 if ( first == startbranch && OP( last ) != BRANCH ) {
2756 /* whole branch chain */
2759 /* branch sub-chain */
2760 convert = NEXTOPER( first );
2763 /* -- First loop and Setup --
2765 We first traverse the branches and scan each word to determine if it
2766 contains widechars, and how many unique chars there are, this is
2767 important as we have to build a table with at least as many columns as we
2770 We use an array of integers to represent the character codes 0..255
2771 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2772 the native representation of the character value as the key and IV's for
2775 *TODO* If we keep track of how many times each character is used we can
2776 remap the columns so that the table compression later on is more
2777 efficient in terms of memory by ensuring the most common value is in the
2778 middle and the least common are on the outside. IMO this would be better
2779 than a most to least common mapping as theres a decent chance the most
2780 common letter will share a node with the least common, meaning the node
2781 will not be compressible. With a middle is most common approach the worst
2782 case is when we have the least common nodes twice.
2786 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2787 regnode *noper = NEXTOPER( cur );
2791 U32 wordlen = 0; /* required init */
2792 STRLEN minchars = 0;
2793 STRLEN maxchars = 0;
2794 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2797 if (OP(noper) == NOTHING) {
2798 /* skip past a NOTHING at the start of an alternation
2799 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2801 * If the next node is not something we are supposed to process
2802 * we will just ignore it due to the condition guarding the
2806 regnode *noper_next= regnext(noper);
2807 if (noper_next < tail)
2812 && ( OP(noper) == flags
2813 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2814 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
2815 || OP(noper) == EXACTFUP))))
2817 uc= (U8*)STRING(noper);
2818 e= uc + STR_LEN(noper);
2825 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2826 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2827 regardless of encoding */
2828 if (OP( noper ) == EXACTFUP) {
2829 /* false positives are ok, so just set this */
2830 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2834 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2836 TRIE_CHARCOUNT(trie)++;
2839 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2840 * is in effect. Under /i, this character can match itself, or
2841 * anything that folds to it. If not under /i, it can match just
2842 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2843 * all fold to k, and all are single characters. But some folds
2844 * expand to more than one character, so for example LATIN SMALL
2845 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2846 * the string beginning at 'uc' is 'ffi', it could be matched by
2847 * three characters, or just by the one ligature character. (It
2848 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2849 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2850 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2851 * match.) The trie needs to know the minimum and maximum number
2852 * of characters that could match so that it can use size alone to
2853 * quickly reject many match attempts. The max is simple: it is
2854 * the number of folded characters in this branch (since a fold is
2855 * never shorter than what folds to it. */
2859 /* And the min is equal to the max if not under /i (indicated by
2860 * 'folder' being NULL), or there are no multi-character folds. If
2861 * there is a multi-character fold, the min is incremented just
2862 * once, for the character that folds to the sequence. Each
2863 * character in the sequence needs to be added to the list below of
2864 * characters in the trie, but we count only the first towards the
2865 * min number of characters needed. This is done through the
2866 * variable 'foldlen', which is returned by the macros that look
2867 * for these sequences as the number of bytes the sequence
2868 * occupies. Each time through the loop, we decrement 'foldlen' by
2869 * how many bytes the current char occupies. Only when it reaches
2870 * 0 do we increment 'minchars' or look for another multi-character
2872 if (folder == NULL) {
2875 else if (foldlen > 0) {
2876 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2881 /* See if *uc is the beginning of a multi-character fold. If
2882 * so, we decrement the length remaining to look at, to account
2883 * for the current character this iteration. (We can use 'uc'
2884 * instead of the fold returned by TRIE_READ_CHAR because for
2885 * non-UTF, the latin1_safe macro is smart enough to account
2886 * for all the unfolded characters, and because for UTF, the
2887 * string will already have been folded earlier in the
2888 * compilation process */
2890 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2891 foldlen -= UTF8SKIP(uc);
2894 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2899 /* The current character (and any potential folds) should be added
2900 * to the possible matching characters for this position in this
2904 U8 folded= folder[ (U8) uvc ];
2905 if ( !trie->charmap[ folded ] ) {
2906 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2907 TRIE_STORE_REVCHAR( folded );
2910 if ( !trie->charmap[ uvc ] ) {
2911 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2912 TRIE_STORE_REVCHAR( uvc );
2915 /* store the codepoint in the bitmap, and its folded
2917 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2918 set_bit = 0; /* We've done our bit :-) */
2922 /* XXX We could come up with the list of code points that fold
2923 * to this using PL_utf8_foldclosures, except not for
2924 * multi-char folds, as there may be multiple combinations
2925 * there that could work, which needs to wait until runtime to
2926 * resolve (The comment about LIGATURE FFI above is such an
2931 widecharmap = newHV();
2933 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2936 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2938 if ( !SvTRUE( *svpp ) ) {
2939 sv_setiv( *svpp, ++trie->uniquecharcount );
2940 TRIE_STORE_REVCHAR(uvc);
2943 } /* end loop through characters in this branch of the trie */
2945 /* We take the min and max for this branch and combine to find the min
2946 * and max for all branches processed so far */
2947 if( cur == first ) {
2948 trie->minlen = minchars;
2949 trie->maxlen = maxchars;
2950 } else if (minchars < trie->minlen) {
2951 trie->minlen = minchars;
2952 } else if (maxchars > trie->maxlen) {
2953 trie->maxlen = maxchars;
2955 } /* end first pass */
2956 DEBUG_TRIE_COMPILE_r(
2957 Perl_re_indentf( aTHX_
2958 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2960 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2961 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2962 (int)trie->minlen, (int)trie->maxlen )
2966 We now know what we are dealing with in terms of unique chars and
2967 string sizes so we can calculate how much memory a naive
2968 representation using a flat table will take. If it's over a reasonable
2969 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2970 conservative but potentially much slower representation using an array
2973 At the end we convert both representations into the same compressed
2974 form that will be used in regexec.c for matching with. The latter
2975 is a form that cannot be used to construct with but has memory
2976 properties similar to the list form and access properties similar
2977 to the table form making it both suitable for fast searches and
2978 small enough that its feasable to store for the duration of a program.
2980 See the comment in the code where the compressed table is produced
2981 inplace from the flat tabe representation for an explanation of how
2982 the compression works.
2987 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2990 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2991 > SvIV(re_trie_maxbuff) )
2994 Second Pass -- Array Of Lists Representation
2996 Each state will be represented by a list of charid:state records
2997 (reg_trie_trans_le) the first such element holds the CUR and LEN
2998 points of the allocated array. (See defines above).
3000 We build the initial structure using the lists, and then convert
3001 it into the compressed table form which allows faster lookups
3002 (but cant be modified once converted).
3005 STRLEN transcount = 1;
3007 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
3010 trie->states = (reg_trie_state *)
3011 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3012 sizeof(reg_trie_state) );
3016 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3018 regnode *noper = NEXTOPER( cur );
3019 U32 state = 1; /* required init */
3020 U16 charid = 0; /* sanity init */
3021 U32 wordlen = 0; /* required init */
3023 if (OP(noper) == NOTHING) {
3024 regnode *noper_next= regnext(noper);
3025 if (noper_next < tail)
3027 /* we will undo this assignment if noper does not
3028 * point at a trieable type in the else clause of
3029 * the following statement. */
3033 && ( OP(noper) == flags
3034 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3035 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3036 || OP(noper) == EXACTFUP))))
3038 const U8 *uc= (U8*)STRING(noper);
3039 const U8 *e= uc + STR_LEN(noper);
3041 for ( ; uc < e ; uc += len ) {
3046 charid = trie->charmap[ uvc ];
3048 SV** const svpp = hv_fetch( widecharmap,
3055 charid=(U16)SvIV( *svpp );
3058 /* charid is now 0 if we dont know the char read, or
3059 * nonzero if we do */
3066 if ( !trie->states[ state ].trans.list ) {
3067 TRIE_LIST_NEW( state );
3070 check <= TRIE_LIST_USED( state );
3073 if ( TRIE_LIST_ITEM( state, check ).forid
3076 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3081 newstate = next_alloc++;
3082 prev_states[newstate] = state;
3083 TRIE_LIST_PUSH( state, charid, newstate );
3088 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3092 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3093 * on a trieable type. So we need to reset noper back to point at the first regop
3094 * in the branch before we call TRIE_HANDLE_WORD()
3096 noper= NEXTOPER(cur);
3098 TRIE_HANDLE_WORD(state);
3100 } /* end second pass */
3102 /* next alloc is the NEXT state to be allocated */
3103 trie->statecount = next_alloc;
3104 trie->states = (reg_trie_state *)
3105 PerlMemShared_realloc( trie->states,
3107 * sizeof(reg_trie_state) );
3109 /* and now dump it out before we compress it */
3110 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3111 revcharmap, next_alloc,
3115 trie->trans = (reg_trie_trans *)
3116 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3123 for( state=1 ; state < next_alloc ; state ++ ) {
3127 DEBUG_TRIE_COMPILE_MORE_r(
3128 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3132 if (trie->states[state].trans.list) {
3133 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3137 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3138 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3139 if ( forid < minid ) {
3141 } else if ( forid > maxid ) {
3145 if ( transcount < tp + maxid - minid + 1) {
3147 trie->trans = (reg_trie_trans *)
3148 PerlMemShared_realloc( trie->trans,
3150 * sizeof(reg_trie_trans) );
3151 Zero( trie->trans + (transcount / 2),
3155 base = trie->uniquecharcount + tp - minid;
3156 if ( maxid == minid ) {
3158 for ( ; zp < tp ; zp++ ) {
3159 if ( ! trie->trans[ zp ].next ) {
3160 base = trie->uniquecharcount + zp - minid;
3161 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3163 trie->trans[ zp ].check = state;
3169 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3171 trie->trans[ tp ].check = state;
3176 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3177 const U32 tid = base
3178 - trie->uniquecharcount
3179 + TRIE_LIST_ITEM( state, idx ).forid;
3180 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3182 trie->trans[ tid ].check = state;
3184 tp += ( maxid - minid + 1 );
3186 Safefree(trie->states[ state ].trans.list);
3189 DEBUG_TRIE_COMPILE_MORE_r(
3190 Perl_re_printf( aTHX_ " base: %d\n",base);
3193 trie->states[ state ].trans.base=base;
3195 trie->lasttrans = tp + 1;
3199 Second Pass -- Flat Table Representation.
3201 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3202 each. We know that we will need Charcount+1 trans at most to store
3203 the data (one row per char at worst case) So we preallocate both
3204 structures assuming worst case.
3206 We then construct the trie using only the .next slots of the entry
3209 We use the .check field of the first entry of the node temporarily
3210 to make compression both faster and easier by keeping track of how
3211 many non zero fields are in the node.
3213 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3216 There are two terms at use here: state as a TRIE_NODEIDX() which is
3217 a number representing the first entry of the node, and state as a
3218 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3219 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3220 if there are 2 entrys per node. eg:
3228 The table is internally in the right hand, idx form. However as we
3229 also have to deal with the states array which is indexed by nodenum
3230 we have to use TRIE_NODENUM() to convert.
3233 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3236 trie->trans = (reg_trie_trans *)
3237 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3238 * trie->uniquecharcount + 1,
3239 sizeof(reg_trie_trans) );
3240 trie->states = (reg_trie_state *)
3241 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3242 sizeof(reg_trie_state) );
3243 next_alloc = trie->uniquecharcount + 1;
3246 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3248 regnode *noper = NEXTOPER( cur );
3250 U32 state = 1; /* required init */
3252 U16 charid = 0; /* sanity init */
3253 U32 accept_state = 0; /* sanity init */
3255 U32 wordlen = 0; /* required init */
3257 if (OP(noper) == NOTHING) {
3258 regnode *noper_next= regnext(noper);
3259 if (noper_next < tail)
3261 /* we will undo this assignment if noper does not
3262 * point at a trieable type in the else clause of
3263 * the following statement. */
3267 && ( OP(noper) == flags
3268 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3269 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3270 || OP(noper) == EXACTFUP))))
3272 const U8 *uc= (U8*)STRING(noper);
3273 const U8 *e= uc + STR_LEN(noper);
3275 for ( ; uc < e ; uc += len ) {
3280 charid = trie->charmap[ uvc ];
3282 SV* const * const svpp = hv_fetch( widecharmap,
3286 charid = svpp ? (U16)SvIV(*svpp) : 0;
3290 if ( !trie->trans[ state + charid ].next ) {
3291 trie->trans[ state + charid ].next = next_alloc;
3292 trie->trans[ state ].check++;
3293 prev_states[TRIE_NODENUM(next_alloc)]
3294 = TRIE_NODENUM(state);
3295 next_alloc += trie->uniquecharcount;
3297 state = trie->trans[ state + charid ].next;
3299 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3301 /* charid is now 0 if we dont know the char read, or
3302 * nonzero if we do */
3305 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3306 * on a trieable type. So we need to reset noper back to point at the first regop
3307 * in the branch before we call TRIE_HANDLE_WORD().
3309 noper= NEXTOPER(cur);
3311 accept_state = TRIE_NODENUM( state );
3312 TRIE_HANDLE_WORD(accept_state);
3314 } /* end second pass */
3316 /* and now dump it out before we compress it */
3317 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3319 next_alloc, depth+1));
3323 * Inplace compress the table.*
3325 For sparse data sets the table constructed by the trie algorithm will
3326 be mostly 0/FAIL transitions or to put it another way mostly empty.
3327 (Note that leaf nodes will not contain any transitions.)
3329 This algorithm compresses the tables by eliminating most such
3330 transitions, at the cost of a modest bit of extra work during lookup:
3332 - Each states[] entry contains a .base field which indicates the
3333 index in the state[] array wheres its transition data is stored.
3335 - If .base is 0 there are no valid transitions from that node.
3337 - If .base is nonzero then charid is added to it to find an entry in
3340 -If trans[states[state].base+charid].check!=state then the
3341 transition is taken to be a 0/Fail transition. Thus if there are fail
3342 transitions at the front of the node then the .base offset will point
3343 somewhere inside the previous nodes data (or maybe even into a node
3344 even earlier), but the .check field determines if the transition is
3348 The following process inplace converts the table to the compressed
3349 table: We first do not compress the root node 1,and mark all its
3350 .check pointers as 1 and set its .base pointer as 1 as well. This
3351 allows us to do a DFA construction from the compressed table later,
3352 and ensures that any .base pointers we calculate later are greater
3355 - We set 'pos' to indicate the first entry of the second node.
3357 - We then iterate over the columns of the node, finding the first and
3358 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3359 and set the .check pointers accordingly, and advance pos
3360 appropriately and repreat for the next node. Note that when we copy
3361 the next pointers we have to convert them from the original
3362 NODEIDX form to NODENUM form as the former is not valid post
3365 - If a node has no transitions used we mark its base as 0 and do not
3366 advance the pos pointer.
3368 - If a node only has one transition we use a second pointer into the
3369 structure to fill in allocated fail transitions from other states.
3370 This pointer is independent of the main pointer and scans forward
3371 looking for null transitions that are allocated to a state. When it
3372 finds one it writes the single transition into the "hole". If the
3373 pointer doesnt find one the single transition is appended as normal.
3375 - Once compressed we can Renew/realloc the structures to release the
3378 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3379 specifically Fig 3.47 and the associated pseudocode.
3383 const U32 laststate = TRIE_NODENUM( next_alloc );
3386 trie->statecount = laststate;
3388 for ( state = 1 ; state < laststate ; state++ ) {
3390 const U32 stateidx = TRIE_NODEIDX( state );
3391 const U32 o_used = trie->trans[ stateidx ].check;
3392 U32 used = trie->trans[ stateidx ].check;
3393 trie->trans[ stateidx ].check = 0;
3396 used && charid < trie->uniquecharcount;
3399 if ( flag || trie->trans[ stateidx + charid ].next ) {
3400 if ( trie->trans[ stateidx + charid ].next ) {
3402 for ( ; zp < pos ; zp++ ) {
3403 if ( ! trie->trans[ zp ].next ) {
3407 trie->states[ state ].trans.base
3409 + trie->uniquecharcount
3411 trie->trans[ zp ].next
3412 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3414 trie->trans[ zp ].check = state;
3415 if ( ++zp > pos ) pos = zp;
3422 trie->states[ state ].trans.base
3423 = pos + trie->uniquecharcount - charid ;
3425 trie->trans[ pos ].next
3426 = SAFE_TRIE_NODENUM(
3427 trie->trans[ stateidx + charid ].next );
3428 trie->trans[ pos ].check = state;
3433 trie->lasttrans = pos + 1;
3434 trie->states = (reg_trie_state *)
3435 PerlMemShared_realloc( trie->states, laststate
3436 * sizeof(reg_trie_state) );
3437 DEBUG_TRIE_COMPILE_MORE_r(
3438 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3440 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3444 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3447 } /* end table compress */
3449 DEBUG_TRIE_COMPILE_MORE_r(
3450 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3452 (UV)trie->statecount,
3453 (UV)trie->lasttrans)
3455 /* resize the trans array to remove unused space */
3456 trie->trans = (reg_trie_trans *)
3457 PerlMemShared_realloc( trie->trans, trie->lasttrans
3458 * sizeof(reg_trie_trans) );
3460 { /* Modify the program and insert the new TRIE node */
3461 U8 nodetype =(U8)(flags & 0xFF);
3465 regnode *optimize = NULL;
3466 #ifdef RE_TRACK_PATTERN_OFFSETS
3469 U32 mjd_nodelen = 0;
3470 #endif /* RE_TRACK_PATTERN_OFFSETS */
3471 #endif /* DEBUGGING */
3473 This means we convert either the first branch or the first Exact,
3474 depending on whether the thing following (in 'last') is a branch
3475 or not and whther first is the startbranch (ie is it a sub part of
3476 the alternation or is it the whole thing.)
3477 Assuming its a sub part we convert the EXACT otherwise we convert
3478 the whole branch sequence, including the first.
3480 /* Find the node we are going to overwrite */
3481 if ( first != startbranch || OP( last ) == BRANCH ) {
3482 /* branch sub-chain */
3483 NEXT_OFF( first ) = (U16)(last - first);
3484 #ifdef RE_TRACK_PATTERN_OFFSETS
3486 mjd_offset= Node_Offset((convert));
3487 mjd_nodelen= Node_Length((convert));
3490 /* whole branch chain */
3492 #ifdef RE_TRACK_PATTERN_OFFSETS
3495 const regnode *nop = NEXTOPER( convert );
3496 mjd_offset= Node_Offset((nop));
3497 mjd_nodelen= Node_Length((nop));
3501 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3503 (UV)mjd_offset, (UV)mjd_nodelen)
3506 /* But first we check to see if there is a common prefix we can
3507 split out as an EXACT and put in front of the TRIE node. */
3508 trie->startstate= 1;
3509 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3510 /* we want to find the first state that has more than
3511 * one transition, if that state is not the first state
3512 * then we have a common prefix which we can remove.
3515 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3517 I32 first_ofs = -1; /* keeps track of the ofs of the first
3518 transition, -1 means none */
3520 const U32 base = trie->states[ state ].trans.base;
3522 /* does this state terminate an alternation? */
3523 if ( trie->states[state].wordnum )
3526 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3527 if ( ( base + ofs >= trie->uniquecharcount ) &&
3528 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3529 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3531 if ( ++count > 1 ) {
3532 /* we have more than one transition */
3535 /* if this is the first state there is no common prefix
3536 * to extract, so we can exit */
3537 if ( state == 1 ) break;
3538 tmp = av_fetch( revcharmap, ofs, 0);
3539 ch = (U8*)SvPV_nolen_const( *tmp );
3541 /* if we are on count 2 then we need to initialize the
3542 * bitmap, and store the previous char if there was one
3545 /* clear the bitmap */
3546 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3548 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3551 if (first_ofs >= 0) {
3552 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3553 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3555 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3557 Perl_re_printf( aTHX_ "%s", (char*)ch)
3561 /* store the current firstchar in the bitmap */
3562 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3563 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3569 /* This state has only one transition, its transition is part
3570 * of a common prefix - we need to concatenate the char it
3571 * represents to what we have so far. */
3572 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3574 char *ch = SvPV( *tmp, len );
3576 SV *sv=sv_newmortal();
3577 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3579 (UV)state, (UV)first_ofs,
3580 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3581 PL_colors[0], PL_colors[1],
3582 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3583 PERL_PV_ESCAPE_FIRSTCHAR
3588 OP( convert ) = nodetype;
3589 str=STRING(convert);
3590 setSTR_LEN(convert, 0);
3592 assert( ( STR_LEN(convert) + len ) < 256 );
3593 setSTR_LEN(convert, (U8)(STR_LEN(convert) + len));
3599 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3604 trie->prefixlen = (state-1);
3606 regnode *n = convert+NODE_SZ_STR(convert);
3607 assert( NODE_SZ_STR(convert) <= U16_MAX );
3608 NEXT_OFF(convert) = (U16)(NODE_SZ_STR(convert));
3609 trie->startstate = state;
3610 trie->minlen -= (state - 1);
3611 trie->maxlen -= (state - 1);
3613 /* At least the UNICOS C compiler choked on this
3614 * being argument to DEBUG_r(), so let's just have
3617 #ifdef PERL_EXT_RE_BUILD
3623 regnode *fix = convert;
3624 U32 word = trie->wordcount;
3625 #ifdef RE_TRACK_PATTERN_OFFSETS
3628 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3629 while( ++fix < n ) {
3630 Set_Node_Offset_Length(fix, 0, 0);
3633 SV ** const tmp = av_fetch( trie_words, word, 0 );
3635 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3636 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3638 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3646 NEXT_OFF(convert) = (U16)(tail - convert);
3647 DEBUG_r(optimize= n);
3653 if ( trie->maxlen ) {
3654 NEXT_OFF( convert ) = (U16)(tail - convert);
3655 ARG_SET( convert, data_slot );
3656 /* Store the offset to the first unabsorbed branch in
3657 jump[0], which is otherwise unused by the jump logic.
3658 We use this when dumping a trie and during optimisation. */
3660 trie->jump[0] = (U16)(nextbranch - convert);
3662 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3663 * and there is a bitmap
3664 * and the first "jump target" node we found leaves enough room
3665 * then convert the TRIE node into a TRIEC node, with the bitmap
3666 * embedded inline in the opcode - this is hypothetically faster.
3668 if ( !trie->states[trie->startstate].wordnum
3670 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3672 OP( convert ) = TRIEC;
3673 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3674 PerlMemShared_free(trie->bitmap);
3677 OP( convert ) = TRIE;
3679 /* store the type in the flags */
3680 convert->flags = nodetype;
3684 + regarglen[ OP( convert ) ];
3686 /* XXX We really should free up the resource in trie now,
3687 as we won't use them - (which resources?) dmq */
3689 /* needed for dumping*/
3690 DEBUG_r(if (optimize) {
3691 regnode *opt = convert;
3693 while ( ++opt < optimize) {
3694 Set_Node_Offset_Length(opt, 0, 0);
3697 Try to clean up some of the debris left after the
3700 while( optimize < jumper ) {
3701 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3702 OP( optimize ) = OPTIMIZED;
3703 Set_Node_Offset_Length(optimize, 0, 0);
3706 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3708 } /* end node insert */
3710 /* Finish populating the prev field of the wordinfo array. Walk back
3711 * from each accept state until we find another accept state, and if
3712 * so, point the first word's .prev field at the second word. If the
3713 * second already has a .prev field set, stop now. This will be the
3714 * case either if we've already processed that word's accept state,
3715 * or that state had multiple words, and the overspill words were
3716 * already linked up earlier.
3723 for (word=1; word <= trie->wordcount; word++) {
3725 if (trie->wordinfo[word].prev)
3727 state = trie->wordinfo[word].accept;
3729 state = prev_states[state];
3732 prev = trie->states[state].wordnum;
3736 trie->wordinfo[word].prev = prev;
3738 Safefree(prev_states);
3742 /* and now dump out the compressed format */
3743 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3745 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3747 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3748 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3750 SvREFCNT_dec_NN(revcharmap);
3754 : trie->startstate>1
3760 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3762 /* The Trie is constructed and compressed now so we can build a fail array if
3765 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3767 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3771 We find the fail state for each state in the trie, this state is the longest
3772 proper suffix of the current state's 'word' that is also a proper prefix of
3773 another word in our trie. State 1 represents the word '' and is thus the
3774 default fail state. This allows the DFA not to have to restart after its
3775 tried and failed a word at a given point, it simply continues as though it
3776 had been matching the other word in the first place.
3778 'abcdgu'=~/abcdefg|cdgu/
3779 When we get to 'd' we are still matching the first word, we would encounter
3780 'g' which would fail, which would bring us to the state representing 'd' in
3781 the second word where we would try 'g' and succeed, proceeding to match
3784 /* add a fail transition */
3785 const U32 trie_offset = ARG(source);
3786 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3788 const U32 ucharcount = trie->uniquecharcount;
3789 const U32 numstates = trie->statecount;
3790 const U32 ubound = trie->lasttrans + ucharcount;
3794 U32 base = trie->states[ 1 ].trans.base;
3797 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3799 GET_RE_DEBUG_FLAGS_DECL;
3801 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3802 PERL_UNUSED_CONTEXT;
3804 PERL_UNUSED_ARG(depth);
3807 if ( OP(source) == TRIE ) {
3808 struct regnode_1 *op = (struct regnode_1 *)
3809 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3810 StructCopy(source, op, struct regnode_1);
3811 stclass = (regnode *)op;
3813 struct regnode_charclass *op = (struct regnode_charclass *)
3814 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3815 StructCopy(source, op, struct regnode_charclass);
3816 stclass = (regnode *)op;
3818 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3820 ARG_SET( stclass, data_slot );
3821 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3822 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3823 aho->trie=trie_offset;
3824 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3825 Copy( trie->states, aho->states, numstates, reg_trie_state );
3826 Newx( q, numstates, U32);
3827 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3830 /* initialize fail[0..1] to be 1 so that we always have
3831 a valid final fail state */
3832 fail[ 0 ] = fail[ 1 ] = 1;
3834 for ( charid = 0; charid < ucharcount ; charid++ ) {
3835 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3837 q[ q_write ] = newstate;
3838 /* set to point at the root */
3839 fail[ q[ q_write++ ] ]=1;
3842 while ( q_read < q_write) {
3843 const U32 cur = q[ q_read++ % numstates ];
3844 base = trie->states[ cur ].trans.base;
3846 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3847 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3849 U32 fail_state = cur;
3852 fail_state = fail[ fail_state ];
3853 fail_base = aho->states[ fail_state ].trans.base;
3854 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3856 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3857 fail[ ch_state ] = fail_state;
3858 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3860 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3862 q[ q_write++ % numstates] = ch_state;
3866 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3867 when we fail in state 1, this allows us to use the
3868 charclass scan to find a valid start char. This is based on the principle
3869 that theres a good chance the string being searched contains lots of stuff
3870 that cant be a start char.
3872 fail[ 0 ] = fail[ 1 ] = 0;
3873 DEBUG_TRIE_COMPILE_r({
3874 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3875 depth, (UV)numstates
3877 for( q_read=1; q_read<numstates; q_read++ ) {
3878 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3880 Perl_re_printf( aTHX_ "\n");
3883 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3888 /* The below joins as many adjacent EXACTish nodes as possible into a single
3889 * one. The regop may be changed if the node(s) contain certain sequences that
3890 * require special handling. The joining is only done if:
3891 * 1) there is room in the current conglomerated node to entirely contain the
3893 * 2) they are compatible node types
3895 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3896 * these get optimized out
3898 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3899 * as possible, even if that means splitting an existing node so that its first
3900 * part is moved to the preceeding node. This would maximise the efficiency of
3901 * memEQ during matching.
3903 * If a node is to match under /i (folded), the number of characters it matches
3904 * can be different than its character length if it contains a multi-character
3905 * fold. *min_subtract is set to the total delta number of characters of the
3908 * And *unfolded_multi_char is set to indicate whether or not the node contains
3909 * an unfolded multi-char fold. This happens when it won't be known until
3910 * runtime whether the fold is valid or not; namely
3911 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3912 * target string being matched against turns out to be UTF-8 is that fold
3914 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3916 * (Multi-char folds whose components are all above the Latin1 range are not
3917 * run-time locale dependent, and have already been folded by the time this
3918 * function is called.)
3920 * This is as good a place as any to discuss the design of handling these
3921 * multi-character fold sequences. It's been wrong in Perl for a very long
3922 * time. There are three code points in Unicode whose multi-character folds
3923 * were long ago discovered to mess things up. The previous designs for
3924 * dealing with these involved assigning a special node for them. This
3925 * approach doesn't always work, as evidenced by this example:
3926 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3927 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3928 * would match just the \xDF, it won't be able to handle the case where a
3929 * successful match would have to cross the node's boundary. The new approach
3930 * that hopefully generally solves the problem generates an EXACTFUP node
3931 * that is "sss" in this case.
3933 * It turns out that there are problems with all multi-character folds, and not
3934 * just these three. Now the code is general, for all such cases. The
3935 * approach taken is:
3936 * 1) This routine examines each EXACTFish node that could contain multi-
3937 * character folded sequences. Since a single character can fold into
3938 * such a sequence, the minimum match length for this node is less than
3939 * the number of characters in the node. This routine returns in
3940 * *min_subtract how many characters to subtract from the the actual
3941 * length of the string to get a real minimum match length; it is 0 if
3942 * there are no multi-char foldeds. This delta is used by the caller to
3943 * adjust the min length of the match, and the delta between min and max,
3944 * so that the optimizer doesn't reject these possibilities based on size
3947 * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3948 * under /u, we fold it to 'ss' in regatom(), and in this routine, after
3949 * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3950 * EXACTFU nodes. The node type of such nodes is then changed to
3951 * EXACTFUP, indicating it is problematic, and needs careful handling.
3952 * (The procedures in step 1) above are sufficient to handle this case in
3953 * UTF-8 encoded nodes.) The reason this is problematic is that this is
3954 * the only case where there is a possible fold length change in non-UTF-8
3955 * patterns. By reserving a special node type for problematic cases, the
3956 * far more common regular EXACTFU nodes can be processed faster.
3957 * regexec.c takes advantage of this.
3959 * EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3960 * problematic cases. These all only occur when the pattern is not
3961 * UTF-8. In addition to the 'ss' sequence where there is a possible fold
3962 * length change, it handles the situation where the string cannot be
3963 * entirely folded. The strings in an EXACTFish node are folded as much
3964 * as possible during compilation in regcomp.c. This saves effort in
3965 * regex matching. By using an EXACTFUP node when it is not possible to
3966 * fully fold at compile time, regexec.c can know that everything in an
3967 * EXACTFU node is folded, so folding can be skipped at runtime. The only
3968 * case where folding in EXACTFU nodes can't be done at compile time is
3969 * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
3970 * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
3971 * handle two very different cases. Alternatively, there could have been
3972 * a node type where there are length changes, one for unfolded, and one
3973 * for both. If yet another special case needed to be created, the number
3974 * of required node types would have to go to 7. khw figures that even
3975 * though there are plenty of node types to spare, that the maintenance
3976 * cost wasn't worth the small speedup of doing it that way, especially