5 * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
7 * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
10 /* This file contains functions for compiling a regular expression. See
11 * also regexec.c which funnily enough, contains functions for executing
12 * a regular expression.
14 * This file is also copied at build time to ext/re/re_comp.c, where
15 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16 * This causes the main functions to be compiled under new names and with
17 * debugging support added, which makes "use re 'debug'" work.
20 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
21 * confused with the original package (see point 3 below). Thanks, Henry!
24 /* Additional note: this code is very heavily munged from Henry's version
25 * in places. In some spots I've traded clarity for efficiency, so don't
26 * blame Henry for some of the lack of readability.
29 /* The names of the functions have been changed from regcomp and
30 * regexec to pregcomp and pregexec in order to avoid conflicts
31 * with the POSIX routines of the same names.
34 #ifdef PERL_EXT_RE_BUILD
39 * pregcomp and pregexec -- regsub and regerror are not used in perl
41 * Copyright (c) 1986 by University of Toronto.
42 * Written by Henry Spencer. Not derived from licensed software.
44 * Permission is granted to anyone to use this software for any
45 * purpose on any computer system, and to redistribute it freely,
46 * subject to the following restrictions:
48 * 1. The author is not responsible for the consequences of use of
49 * this software, no matter how awful, even if they arise
52 * 2. The origin of this software must not be misrepresented, either
53 * by explicit claim or by omission.
55 * 3. Altered versions must be plainly marked as such, and must not
56 * be misrepresented as being the original software.
59 **** Alterations to Henry's code are...
61 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63 **** by Larry Wall and others
65 **** You may distribute under the terms of either the GNU General Public
66 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGCOMP_C
77 #ifndef PERL_IN_XSUB_RE
82 #ifdef PERL_IN_XSUB_RE
84 EXTERN_C const struct regexp_engine my_reg_engine;
89 #include "dquote_static.c"
90 #include "inline_invlist.c"
91 #include "unicode_constants.h"
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
95 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
96 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
97 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
98 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
101 #define STATIC static
105 #define MIN(a,b) ((a) < (b) ? (a) : (b))
108 /* this is a chain of data about sub patterns we are processing that
109 need to be handled separately/specially in study_chunk. Its so
110 we can simulate recursion without losing state. */
112 typedef struct scan_frame {
113 regnode *last_regnode; /* last node to process in this frame */
114 regnode *next_regnode; /* next node to process when last is reached */
115 U32 prev_recursed_depth;
116 I32 stopparen; /* what stopparen do we use */
117 U32 is_top_frame; /* what flags do we use? */
119 struct scan_frame *this_prev_frame; /* this previous frame */
120 struct scan_frame *prev_frame; /* previous frame */
121 struct scan_frame *next_frame; /* next frame */
124 /* Certain characters are output as a sequence with the first being a
126 #define isBACKSLASHED_PUNCT(c) \
127 ((c) == '-' || (c) == ']' || (c) == '\\' || (c) == '^')
130 struct RExC_state_t {
131 U32 flags; /* RXf_* are we folding, multilining? */
132 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
133 char *precomp; /* uncompiled string. */
134 REGEXP *rx_sv; /* The SV that is the regexp. */
135 regexp *rx; /* perl core regexp structure */
136 regexp_internal *rxi; /* internal data for regexp object
138 char *start; /* Start of input for compile */
139 char *end; /* End of input for compile */
140 char *parse; /* Input-scan pointer. */
141 SSize_t whilem_seen; /* number of WHILEM in this expr */
142 regnode *emit_start; /* Start of emitted-code area */
143 regnode *emit_bound; /* First regnode outside of the
145 regnode *emit; /* Code-emit pointer; if = &emit_dummy,
146 implies compiling, so don't emit */
147 regnode_ssc emit_dummy; /* placeholder for emit to point to;
148 large enough for the largest
149 non-EXACTish node, so can use it as
151 I32 naughty; /* How bad is this pattern? */
152 I32 sawback; /* Did we see \1, ...? */
154 SSize_t size; /* Code size. */
155 I32 npar; /* Capture buffer count, (OPEN) plus
156 one. ("par" 0 is the whole
158 I32 nestroot; /* root parens we are in - used by
162 regnode **open_parens; /* pointers to open parens */
163 regnode **close_parens; /* pointers to close parens */
164 regnode *opend; /* END node in program */
165 I32 utf8; /* whether the pattern is utf8 or not */
166 I32 orig_utf8; /* whether the pattern was originally in utf8 */
167 /* XXX use this for future optimisation of case
168 * where pattern must be upgraded to utf8. */
169 I32 uni_semantics; /* If a d charset modifier should use unicode
170 rules, even if the pattern is not in
172 HV *paren_names; /* Paren names */
174 regnode **recurse; /* Recurse regops */
175 I32 recurse_count; /* Number of recurse regops */
176 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
178 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
182 I32 override_recoding;
183 I32 in_multi_char_class;
184 struct reg_code_block *code_blocks; /* positions of literal (?{})
186 int num_code_blocks; /* size of code_blocks[] */
187 int code_index; /* next code_blocks[] slot */
188 SSize_t maxlen; /* mininum possible number of chars in string to match */
189 scan_frame *frame_head;
190 scan_frame *frame_last;
193 #ifdef ADD_TO_REGEXEC
194 char *starttry; /* -Dr: where regtry was called. */
195 #define RExC_starttry (pRExC_state->starttry)
197 SV *runtime_code_qr; /* qr with the runtime code blocks */
199 const char *lastparse;
201 AV *paren_name_list; /* idx -> name */
202 U32 study_chunk_recursed_count;
205 #define RExC_lastparse (pRExC_state->lastparse)
206 #define RExC_lastnum (pRExC_state->lastnum)
207 #define RExC_paren_name_list (pRExC_state->paren_name_list)
208 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
209 #define RExC_mysv (pRExC_state->mysv1)
210 #define RExC_mysv1 (pRExC_state->mysv1)
211 #define RExC_mysv2 (pRExC_state->mysv2)
216 #define RExC_flags (pRExC_state->flags)
217 #define RExC_pm_flags (pRExC_state->pm_flags)
218 #define RExC_precomp (pRExC_state->precomp)
219 #define RExC_rx_sv (pRExC_state->rx_sv)
220 #define RExC_rx (pRExC_state->rx)
221 #define RExC_rxi (pRExC_state->rxi)
222 #define RExC_start (pRExC_state->start)
223 #define RExC_end (pRExC_state->end)
224 #define RExC_parse (pRExC_state->parse)
225 #define RExC_whilem_seen (pRExC_state->whilem_seen)
226 #ifdef RE_TRACK_PATTERN_OFFSETS
227 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the
230 #define RExC_emit (pRExC_state->emit)
231 #define RExC_emit_dummy (pRExC_state->emit_dummy)
232 #define RExC_emit_start (pRExC_state->emit_start)
233 #define RExC_emit_bound (pRExC_state->emit_bound)
234 #define RExC_sawback (pRExC_state->sawback)
235 #define RExC_seen (pRExC_state->seen)
236 #define RExC_size (pRExC_state->size)
237 #define RExC_maxlen (pRExC_state->maxlen)
238 #define RExC_npar (pRExC_state->npar)
239 #define RExC_nestroot (pRExC_state->nestroot)
240 #define RExC_extralen (pRExC_state->extralen)
241 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
242 #define RExC_utf8 (pRExC_state->utf8)
243 #define RExC_uni_semantics (pRExC_state->uni_semantics)
244 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
245 #define RExC_open_parens (pRExC_state->open_parens)
246 #define RExC_close_parens (pRExC_state->close_parens)
247 #define RExC_opend (pRExC_state->opend)
248 #define RExC_paren_names (pRExC_state->paren_names)
249 #define RExC_recurse (pRExC_state->recurse)
250 #define RExC_recurse_count (pRExC_state->recurse_count)
251 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
252 #define RExC_study_chunk_recursed_bytes \
253 (pRExC_state->study_chunk_recursed_bytes)
254 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
255 #define RExC_contains_locale (pRExC_state->contains_locale)
256 #define RExC_contains_i (pRExC_state->contains_i)
257 #define RExC_override_recoding (pRExC_state->override_recoding)
258 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
259 #define RExC_frame_head (pRExC_state->frame_head)
260 #define RExC_frame_last (pRExC_state->frame_last)
261 #define RExC_frame_count (pRExC_state->frame_count)
262 #define RExC_strict (pRExC_state->strict)
264 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
265 * a flag to disable back-off on the fixed/floating substrings - if it's
266 * a high complexity pattern we assume the benefit of avoiding a full match
267 * is worth the cost of checking for the substrings even if they rarely help.
269 #define RExC_naughty (pRExC_state->naughty)
270 #define TOO_NAUGHTY (10)
271 #define MARK_NAUGHTY(add) \
272 if (RExC_naughty < TOO_NAUGHTY) \
273 RExC_naughty += (add)
274 #define MARK_NAUGHTY_EXP(exp, add) \
275 if (RExC_naughty < TOO_NAUGHTY) \
276 RExC_naughty += RExC_naughty / (exp) + (add)
278 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
279 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
280 ((*s) == '{' && regcurly(s)))
283 * Flags to be passed up and down.
285 #define WORST 0 /* Worst case. */
286 #define HASWIDTH 0x01 /* Known to match non-null strings. */
288 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
289 * character. (There needs to be a case: in the switch statement in regexec.c
290 * for any node marked SIMPLE.) Note that this is not the same thing as
293 #define SPSTART 0x04 /* Starts with * or + */
294 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
295 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
296 #define RESTART_UTF8 0x20 /* Restart, need to calcuate sizes as UTF-8 */
298 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
300 /* whether trie related optimizations are enabled */
301 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
302 #define TRIE_STUDY_OPT
303 #define FULL_TRIE_STUDY
309 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
310 #define PBITVAL(paren) (1 << ((paren) & 7))
311 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
312 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
313 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
315 #define REQUIRE_UTF8 STMT_START { \
317 *flagp = RESTART_UTF8; \
322 /* This converts the named class defined in regcomp.h to its equivalent class
323 * number defined in handy.h. */
324 #define namedclass_to_classnum(class) ((int) ((class) / 2))
325 #define classnum_to_namedclass(classnum) ((classnum) * 2)
327 #define _invlist_union_complement_2nd(a, b, output) \
328 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
329 #define _invlist_intersection_complement_2nd(a, b, output) \
330 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
332 /* About scan_data_t.
334 During optimisation we recurse through the regexp program performing
335 various inplace (keyhole style) optimisations. In addition study_chunk
336 and scan_commit populate this data structure with information about
337 what strings MUST appear in the pattern. We look for the longest
338 string that must appear at a fixed location, and we look for the
339 longest string that may appear at a floating location. So for instance
344 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
345 strings (because they follow a .* construct). study_chunk will identify
346 both FOO and BAR as being the longest fixed and floating strings respectively.
348 The strings can be composites, for instance
352 will result in a composite fixed substring 'foo'.
354 For each string some basic information is maintained:
356 - offset or min_offset
357 This is the position the string must appear at, or not before.
358 It also implicitly (when combined with minlenp) tells us how many
359 characters must match before the string we are searching for.
360 Likewise when combined with minlenp and the length of the string it
361 tells us how many characters must appear after the string we have
365 Only used for floating strings. This is the rightmost point that
366 the string can appear at. If set to SSize_t_MAX it indicates that the
367 string can occur infinitely far to the right.
370 A pointer to the minimum number of characters of the pattern that the
371 string was found inside. This is important as in the case of positive
372 lookahead or positive lookbehind we can have multiple patterns
377 The minimum length of the pattern overall is 3, the minimum length
378 of the lookahead part is 3, but the minimum length of the part that
379 will actually match is 1. So 'FOO's minimum length is 3, but the
380 minimum length for the F is 1. This is important as the minimum length
381 is used to determine offsets in front of and behind the string being
382 looked for. Since strings can be composites this is the length of the
383 pattern at the time it was committed with a scan_commit. Note that
384 the length is calculated by study_chunk, so that the minimum lengths
385 are not known until the full pattern has been compiled, thus the
386 pointer to the value.
390 In the case of lookbehind the string being searched for can be
391 offset past the start point of the final matching string.
392 If this value was just blithely removed from the min_offset it would
393 invalidate some of the calculations for how many chars must match
394 before or after (as they are derived from min_offset and minlen and
395 the length of the string being searched for).
396 When the final pattern is compiled and the data is moved from the
397 scan_data_t structure into the regexp structure the information
398 about lookbehind is factored in, with the information that would
399 have been lost precalculated in the end_shift field for the
402 The fields pos_min and pos_delta are used to store the minimum offset
403 and the delta to the maximum offset at the current point in the pattern.
407 typedef struct scan_data_t {
408 /*I32 len_min; unused */
409 /*I32 len_delta; unused */
413 SSize_t last_end; /* min value, <0 unless valid. */
414 SSize_t last_start_min;
415 SSize_t last_start_max;
416 SV **longest; /* Either &l_fixed, or &l_float. */
417 SV *longest_fixed; /* longest fixed string found in pattern */
418 SSize_t offset_fixed; /* offset where it starts */
419 SSize_t *minlen_fixed; /* pointer to the minlen relevant to the string */
420 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
421 SV *longest_float; /* longest floating string found in pattern */
422 SSize_t offset_float_min; /* earliest point in string it can appear */
423 SSize_t offset_float_max; /* latest point in string it can appear */
424 SSize_t *minlen_float; /* pointer to the minlen relevant to the string */
425 SSize_t lookbehind_float; /* is the pos of the string modified by LB */
428 SSize_t *last_closep;
429 regnode_ssc *start_class;
433 * Forward declarations for pregcomp()'s friends.
436 static const scan_data_t zero_scan_data =
437 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
439 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
440 #define SF_BEFORE_SEOL 0x0001
441 #define SF_BEFORE_MEOL 0x0002
442 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
443 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
445 #define SF_FIX_SHIFT_EOL (+2)
446 #define SF_FL_SHIFT_EOL (+4)
448 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
449 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
451 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
452 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
453 #define SF_IS_INF 0x0040
454 #define SF_HAS_PAR 0x0080
455 #define SF_IN_PAR 0x0100
456 #define SF_HAS_EVAL 0x0200
457 #define SCF_DO_SUBSTR 0x0400
458 #define SCF_DO_STCLASS_AND 0x0800
459 #define SCF_DO_STCLASS_OR 0x1000
460 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
461 #define SCF_WHILEM_VISITED_POS 0x2000
463 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
464 #define SCF_SEEN_ACCEPT 0x8000
465 #define SCF_TRIE_DOING_RESTUDY 0x10000
466 #define SCF_IN_DEFINE 0x20000
471 #define UTF cBOOL(RExC_utf8)
473 /* The enums for all these are ordered so things work out correctly */
474 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
475 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
476 == REGEX_DEPENDS_CHARSET)
477 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
478 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
479 >= REGEX_UNICODE_CHARSET)
480 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
481 == REGEX_ASCII_RESTRICTED_CHARSET)
482 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
483 >= REGEX_ASCII_RESTRICTED_CHARSET)
484 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
485 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
487 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
489 /* For programs that want to be strictly Unicode compatible by dying if any
490 * attempt is made to match a non-Unicode code point against a Unicode
492 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
494 #define OOB_NAMEDCLASS -1
496 /* There is no code point that is out-of-bounds, so this is problematic. But
497 * its only current use is to initialize a variable that is always set before
499 #define OOB_UNICODE 0xDEADBEEF
501 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
502 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
505 /* length of regex to show in messages that don't mark a position within */
506 #define RegexLengthToShowInErrorMessages 127
509 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
510 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
511 * op/pragma/warn/regcomp.
513 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
514 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
516 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
517 " in m/%"UTF8f MARKER2 "%"UTF8f"/"
519 #define REPORT_LOCATION_ARGS(offset) \
520 UTF8fARG(UTF, offset, RExC_precomp), \
521 UTF8fARG(UTF, RExC_end - RExC_precomp - offset, RExC_precomp + offset)
523 /* Used to point after bad bytes for an error message, but avoid skipping
524 * past a nul byte. */
525 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
528 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
529 * arg. Show regex, up to a maximum length. If it's too long, chop and add
532 #define _FAIL(code) STMT_START { \
533 const char *ellipses = ""; \
534 IV len = RExC_end - RExC_precomp; \
537 SAVEFREESV(RExC_rx_sv); \
538 if (len > RegexLengthToShowInErrorMessages) { \
539 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
540 len = RegexLengthToShowInErrorMessages - 10; \
546 #define FAIL(msg) _FAIL( \
547 Perl_croak(aTHX_ "%s in regex m/%"UTF8f"%s/", \
548 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
550 #define FAIL2(msg,arg) _FAIL( \
551 Perl_croak(aTHX_ msg " in regex m/%"UTF8f"%s/", \
552 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
555 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
557 #define Simple_vFAIL(m) STMT_START { \
559 (RExC_parse > RExC_end ? RExC_end : RExC_parse) - RExC_precomp; \
560 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
561 m, REPORT_LOCATION_ARGS(offset)); \
565 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
567 #define vFAIL(m) STMT_START { \
569 SAVEFREESV(RExC_rx_sv); \
574 * Like Simple_vFAIL(), but accepts two arguments.
576 #define Simple_vFAIL2(m,a1) STMT_START { \
577 const IV offset = RExC_parse - RExC_precomp; \
578 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
579 REPORT_LOCATION_ARGS(offset)); \
583 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
585 #define vFAIL2(m,a1) STMT_START { \
587 SAVEFREESV(RExC_rx_sv); \
588 Simple_vFAIL2(m, a1); \
593 * Like Simple_vFAIL(), but accepts three arguments.
595 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
596 const IV offset = RExC_parse - RExC_precomp; \
597 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
598 REPORT_LOCATION_ARGS(offset)); \
602 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
604 #define vFAIL3(m,a1,a2) STMT_START { \
606 SAVEFREESV(RExC_rx_sv); \
607 Simple_vFAIL3(m, a1, a2); \
611 * Like Simple_vFAIL(), but accepts four arguments.
613 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
614 const IV offset = RExC_parse - RExC_precomp; \
615 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
616 REPORT_LOCATION_ARGS(offset)); \
619 #define vFAIL4(m,a1,a2,a3) STMT_START { \
621 SAVEFREESV(RExC_rx_sv); \
622 Simple_vFAIL4(m, a1, a2, a3); \
625 /* A specialized version of vFAIL2 that works with UTF8f */
626 #define vFAIL2utf8f(m, a1) STMT_START { \
627 const IV offset = RExC_parse - RExC_precomp; \
629 SAVEFREESV(RExC_rx_sv); \
630 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
631 REPORT_LOCATION_ARGS(offset)); \
634 /* These have asserts in them because of [perl #122671] Many warnings in
635 * regcomp.c can occur twice. If they get output in pass1 and later in that
636 * pass, the pattern has to be converted to UTF-8 and the pass restarted, they
637 * would get output again. So they should be output in pass2, and these
638 * asserts make sure new warnings follow that paradigm. */
640 /* m is not necessarily a "literal string", in this macro */
641 #define reg_warn_non_literal_string(loc, m) STMT_START { \
642 const IV offset = loc - RExC_precomp; \
643 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
644 m, REPORT_LOCATION_ARGS(offset)); \
647 #define ckWARNreg(loc,m) STMT_START { \
648 const IV offset = loc - RExC_precomp; \
649 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
650 REPORT_LOCATION_ARGS(offset)); \
653 #define vWARN(loc, m) STMT_START { \
654 const IV offset = loc - RExC_precomp; \
655 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
656 REPORT_LOCATION_ARGS(offset)); \
659 #define vWARN_dep(loc, m) STMT_START { \
660 const IV offset = loc - RExC_precomp; \
661 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), m REPORT_LOCATION, \
662 REPORT_LOCATION_ARGS(offset)); \
665 #define ckWARNdep(loc,m) STMT_START { \
666 const IV offset = loc - RExC_precomp; \
667 __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
669 REPORT_LOCATION_ARGS(offset)); \
672 #define ckWARNregdep(loc,m) STMT_START { \
673 const IV offset = loc - RExC_precomp; \
674 __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
676 REPORT_LOCATION_ARGS(offset)); \
679 #define ckWARN2reg_d(loc,m, a1) STMT_START { \
680 const IV offset = loc - RExC_precomp; \
681 __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
683 a1, REPORT_LOCATION_ARGS(offset)); \
686 #define ckWARN2reg(loc, m, a1) STMT_START { \
687 const IV offset = loc - RExC_precomp; \
688 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
689 a1, REPORT_LOCATION_ARGS(offset)); \
692 #define vWARN3(loc, m, a1, a2) STMT_START { \
693 const IV offset = loc - RExC_precomp; \
694 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
695 a1, a2, REPORT_LOCATION_ARGS(offset)); \
698 #define ckWARN3reg(loc, m, a1, a2) STMT_START { \
699 const IV offset = loc - RExC_precomp; \
700 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
701 a1, a2, REPORT_LOCATION_ARGS(offset)); \
704 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
705 const IV offset = loc - RExC_precomp; \
706 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
707 a1, a2, a3, REPORT_LOCATION_ARGS(offset)); \
710 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
711 const IV offset = loc - RExC_precomp; \
712 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
713 a1, a2, a3, REPORT_LOCATION_ARGS(offset)); \
716 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
717 const IV offset = loc - RExC_precomp; \
718 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
719 a1, a2, a3, a4, REPORT_LOCATION_ARGS(offset)); \
722 /* Macros for recording node offsets. 20001227 mjd@plover.com
723 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
724 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
725 * Element 0 holds the number n.
726 * Position is 1 indexed.
728 #ifndef RE_TRACK_PATTERN_OFFSETS
729 #define Set_Node_Offset_To_R(node,byte)
730 #define Set_Node_Offset(node,byte)
731 #define Set_Cur_Node_Offset
732 #define Set_Node_Length_To_R(node,len)
733 #define Set_Node_Length(node,len)
734 #define Set_Node_Cur_Length(node,start)
735 #define Node_Offset(n)
736 #define Node_Length(n)
737 #define Set_Node_Offset_Length(node,offset,len)
738 #define ProgLen(ri) ri->u.proglen
739 #define SetProgLen(ri,x) ri->u.proglen = x
741 #define ProgLen(ri) ri->u.offsets[0]
742 #define SetProgLen(ri,x) ri->u.offsets[0] = x
743 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
745 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
746 __LINE__, (int)(node), (int)(byte))); \
748 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
751 RExC_offsets[2*(node)-1] = (byte); \
756 #define Set_Node_Offset(node,byte) \
757 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
758 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
760 #define Set_Node_Length_To_R(node,len) STMT_START { \
762 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
763 __LINE__, (int)(node), (int)(len))); \
765 Perl_croak(aTHX_ "value of node is %d in Length macro", \
768 RExC_offsets[2*(node)] = (len); \
773 #define Set_Node_Length(node,len) \
774 Set_Node_Length_To_R((node)-RExC_emit_start, len)
775 #define Set_Node_Cur_Length(node, start) \
776 Set_Node_Length(node, RExC_parse - start)
778 /* Get offsets and lengths */
779 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
780 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
782 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
783 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
784 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
788 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
789 #define EXPERIMENTAL_INPLACESCAN
790 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
792 #define DEBUG_RExC_seen() \
793 DEBUG_OPTIMISE_MORE_r({ \
794 PerlIO_printf(Perl_debug_log,"RExC_seen: "); \
796 if (RExC_seen & REG_ZERO_LEN_SEEN) \
797 PerlIO_printf(Perl_debug_log,"REG_ZERO_LEN_SEEN "); \
799 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
800 PerlIO_printf(Perl_debug_log,"REG_LOOKBEHIND_SEEN "); \
802 if (RExC_seen & REG_GPOS_SEEN) \
803 PerlIO_printf(Perl_debug_log,"REG_GPOS_SEEN "); \
805 if (RExC_seen & REG_CANY_SEEN) \
806 PerlIO_printf(Perl_debug_log,"REG_CANY_SEEN "); \
808 if (RExC_seen & REG_RECURSE_SEEN) \
809 PerlIO_printf(Perl_debug_log,"REG_RECURSE_SEEN "); \
811 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
812 PerlIO_printf(Perl_debug_log,"REG_TOP_LEVEL_BRANCHES_SEEN "); \
814 if (RExC_seen & REG_VERBARG_SEEN) \
815 PerlIO_printf(Perl_debug_log,"REG_VERBARG_SEEN "); \
817 if (RExC_seen & REG_CUTGROUP_SEEN) \
818 PerlIO_printf(Perl_debug_log,"REG_CUTGROUP_SEEN "); \
820 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
821 PerlIO_printf(Perl_debug_log,"REG_RUN_ON_COMMENT_SEEN "); \
823 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
824 PerlIO_printf(Perl_debug_log,"REG_UNFOLDED_MULTI_SEEN "); \
826 if (RExC_seen & REG_GOSTART_SEEN) \
827 PerlIO_printf(Perl_debug_log,"REG_GOSTART_SEEN "); \
829 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
830 PerlIO_printf(Perl_debug_log,"REG_UNBOUNDED_QUANTIFIER_SEEN "); \
832 PerlIO_printf(Perl_debug_log,"\n"); \
835 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
836 if ((flags) & flag) PerlIO_printf(Perl_debug_log, "%s ", #flag)
838 #define DEBUG_SHOW_STUDY_FLAGS(flags,open_str,close_str) \
840 PerlIO_printf(Perl_debug_log, "%s", open_str); \
841 DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_SEOL); \
842 DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_MEOL); \
843 DEBUG_SHOW_STUDY_FLAG(flags,SF_IS_INF); \
844 DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_PAR); \
845 DEBUG_SHOW_STUDY_FLAG(flags,SF_IN_PAR); \
846 DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_EVAL); \
847 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_SUBSTR); \
848 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_AND); \
849 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_OR); \
850 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS); \
851 DEBUG_SHOW_STUDY_FLAG(flags,SCF_WHILEM_VISITED_POS); \
852 DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_RESTUDY); \
853 DEBUG_SHOW_STUDY_FLAG(flags,SCF_SEEN_ACCEPT); \
854 DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_DOING_RESTUDY); \
855 DEBUG_SHOW_STUDY_FLAG(flags,SCF_IN_DEFINE); \
856 PerlIO_printf(Perl_debug_log, "%s", close_str); \
860 #define DEBUG_STUDYDATA(str,data,depth) \
861 DEBUG_OPTIMISE_MORE_r(if(data){ \
862 PerlIO_printf(Perl_debug_log, \
863 "%*s" str "Pos:%"IVdf"/%"IVdf \
865 (int)(depth)*2, "", \
866 (IV)((data)->pos_min), \
867 (IV)((data)->pos_delta), \
868 (UV)((data)->flags) \
870 DEBUG_SHOW_STUDY_FLAGS((data)->flags," [ ","]"); \
871 PerlIO_printf(Perl_debug_log, \
872 " Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
873 (IV)((data)->whilem_c), \
874 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
875 is_inf ? "INF " : "" \
877 if ((data)->last_found) \
878 PerlIO_printf(Perl_debug_log, \
879 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
880 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
881 SvPVX_const((data)->last_found), \
882 (IV)((data)->last_end), \
883 (IV)((data)->last_start_min), \
884 (IV)((data)->last_start_max), \
885 ((data)->longest && \
886 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
887 SvPVX_const((data)->longest_fixed), \
888 (IV)((data)->offset_fixed), \
889 ((data)->longest && \
890 (data)->longest==&((data)->longest_float)) ? "*" : "", \
891 SvPVX_const((data)->longest_float), \
892 (IV)((data)->offset_float_min), \
893 (IV)((data)->offset_float_max) \
895 PerlIO_printf(Perl_debug_log,"\n"); \
898 /* is c a control character for which we have a mnemonic? */
899 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
902 S_cntrl_to_mnemonic(const U8 c)
904 /* Returns the mnemonic string that represents character 'c', if one
905 * exists; NULL otherwise. The only ones that exist for the purposes of
906 * this routine are a few control characters */
909 case '\a': return "\\a";
910 case '\b': return "\\b";
911 case ESC_NATIVE: return "\\e";
912 case '\f': return "\\f";
913 case '\n': return "\\n";
914 case '\r': return "\\r";
915 case '\t': return "\\t";
921 /* Mark that we cannot extend a found fixed substring at this point.
922 Update the longest found anchored substring and the longest found
923 floating substrings if needed. */
926 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
927 SSize_t *minlenp, int is_inf)
929 const STRLEN l = CHR_SVLEN(data->last_found);
930 const STRLEN old_l = CHR_SVLEN(*data->longest);
931 GET_RE_DEBUG_FLAGS_DECL;
933 PERL_ARGS_ASSERT_SCAN_COMMIT;
935 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
936 SvSetMagicSV(*data->longest, data->last_found);
937 if (*data->longest == data->longest_fixed) {
938 data->offset_fixed = l ? data->last_start_min : data->pos_min;
939 if (data->flags & SF_BEFORE_EOL)
941 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
943 data->flags &= ~SF_FIX_BEFORE_EOL;
944 data->minlen_fixed=minlenp;
945 data->lookbehind_fixed=0;
947 else { /* *data->longest == data->longest_float */
948 data->offset_float_min = l ? data->last_start_min : data->pos_min;
949 data->offset_float_max = (l
950 ? data->last_start_max
951 : (data->pos_delta > SSize_t_MAX - data->pos_min
953 : data->pos_min + data->pos_delta));
955 || (STRLEN)data->offset_float_max > (STRLEN)SSize_t_MAX)
956 data->offset_float_max = SSize_t_MAX;
957 if (data->flags & SF_BEFORE_EOL)
959 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
961 data->flags &= ~SF_FL_BEFORE_EOL;
962 data->minlen_float=minlenp;
963 data->lookbehind_float=0;
966 SvCUR_set(data->last_found, 0);
968 SV * const sv = data->last_found;
969 if (SvUTF8(sv) && SvMAGICAL(sv)) {
970 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
976 data->flags &= ~SF_BEFORE_EOL;
977 DEBUG_STUDYDATA("commit: ",data,0);
980 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
981 * list that describes which code points it matches */
984 S_ssc_anything(pTHX_ regnode_ssc *ssc)
986 /* Set the SSC 'ssc' to match an empty string or any code point */
988 PERL_ARGS_ASSERT_SSC_ANYTHING;
990 assert(is_ANYOF_SYNTHETIC(ssc));
992 ssc->invlist = sv_2mortal(_new_invlist(2)); /* mortalize so won't leak */
993 _append_range_to_invlist(ssc->invlist, 0, UV_MAX);
994 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
998 S_ssc_is_anything(const regnode_ssc *ssc)
1000 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1001 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1002 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1003 * in any way, so there's no point in using it */
1008 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1010 assert(is_ANYOF_SYNTHETIC(ssc));
1012 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1016 /* See if the list consists solely of the range 0 - Infinity */
1017 invlist_iterinit(ssc->invlist);
1018 ret = invlist_iternext(ssc->invlist, &start, &end)
1022 invlist_iterfinish(ssc->invlist);
1028 /* If e.g., both \w and \W are set, matches everything */
1029 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1031 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1032 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1042 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1044 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1045 * string, any code point, or any posix class under locale */
1047 PERL_ARGS_ASSERT_SSC_INIT;
1049 Zero(ssc, 1, regnode_ssc);
1050 set_ANYOF_SYNTHETIC(ssc);
1051 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1054 /* If any portion of the regex is to operate under locale rules that aren't
1055 * fully known at compile time, initialization includes it. The reason
1056 * this isn't done for all regexes is that the optimizer was written under
1057 * the assumption that locale was all-or-nothing. Given the complexity and
1058 * lack of documentation in the optimizer, and that there are inadequate
1059 * test cases for locale, many parts of it may not work properly, it is
1060 * safest to avoid locale unless necessary. */
1061 if (RExC_contains_locale) {
1062 ANYOF_POSIXL_SETALL(ssc);
1065 ANYOF_POSIXL_ZERO(ssc);
1070 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1071 const regnode_ssc *ssc)
1073 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1074 * to the list of code points matched, and locale posix classes; hence does
1075 * not check its flags) */
1080 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1082 assert(is_ANYOF_SYNTHETIC(ssc));
1084 invlist_iterinit(ssc->invlist);
1085 ret = invlist_iternext(ssc->invlist, &start, &end)
1089 invlist_iterfinish(ssc->invlist);
1095 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1103 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1104 const regnode_charclass* const node)
1106 /* Returns a mortal inversion list defining which code points are matched
1107 * by 'node', which is of type ANYOF. Handles complementing the result if
1108 * appropriate. If some code points aren't knowable at this time, the
1109 * returned list must, and will, contain every code point that is a
1112 SV* invlist = sv_2mortal(_new_invlist(0));
1113 SV* only_utf8_locale_invlist = NULL;
1115 const U32 n = ARG(node);
1116 bool new_node_has_latin1 = FALSE;
1118 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1120 /* Look at the data structure created by S_set_ANYOF_arg() */
1121 if (n != ANYOF_ONLY_HAS_BITMAP) {
1122 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1123 AV * const av = MUTABLE_AV(SvRV(rv));
1124 SV **const ary = AvARRAY(av);
1125 assert(RExC_rxi->data->what[n] == 's');
1127 if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1128 invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1])));
1130 else if (ary[0] && ary[0] != &PL_sv_undef) {
1132 /* Here, no compile-time swash, and there are things that won't be
1133 * known until runtime -- we have to assume it could be anything */
1134 return _add_range_to_invlist(invlist, 0, UV_MAX);
1136 else if (ary[3] && ary[3] != &PL_sv_undef) {
1138 /* Here no compile-time swash, and no run-time only data. Use the
1139 * node's inversion list */
1140 invlist = sv_2mortal(invlist_clone(ary[3]));
1143 /* Get the code points valid only under UTF-8 locales */
1144 if ((ANYOF_FLAGS(node) & ANYOF_LOC_FOLD)
1145 && ary[2] && ary[2] != &PL_sv_undef)
1147 only_utf8_locale_invlist = ary[2];
1151 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1152 * code points, and an inversion list for the others, but if there are code
1153 * points that should match only conditionally on the target string being
1154 * UTF-8, those are placed in the inversion list, and not the bitmap.
1155 * Since there are circumstances under which they could match, they are
1156 * included in the SSC. But if the ANYOF node is to be inverted, we have
1157 * to exclude them here, so that when we invert below, the end result
1158 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1159 * have to do this here before we add the unconditionally matched code
1161 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1162 _invlist_intersection_complement_2nd(invlist,
1167 /* Add in the points from the bit map */
1168 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1169 if (ANYOF_BITMAP_TEST(node, i)) {
1170 invlist = add_cp_to_invlist(invlist, i);
1171 new_node_has_latin1 = TRUE;
1175 /* If this can match all upper Latin1 code points, have to add them
1177 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_NON_UTF8_NON_ASCII) {
1178 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1181 /* Similarly for these */
1182 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1183 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1186 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1187 _invlist_invert(invlist);
1189 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOF_LOC_FOLD) {
1191 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1192 * locale. We can skip this if there are no 0-255 at all. */
1193 _invlist_union(invlist, PL_Latin1, &invlist);
1196 /* Similarly add the UTF-8 locale possible matches. These have to be
1197 * deferred until after the non-UTF-8 locale ones are taken care of just
1198 * above, or it leads to wrong results under ANYOF_INVERT */
1199 if (only_utf8_locale_invlist) {
1200 _invlist_union_maybe_complement_2nd(invlist,
1201 only_utf8_locale_invlist,
1202 ANYOF_FLAGS(node) & ANYOF_INVERT,
1209 /* These two functions currently do the exact same thing */
1210 #define ssc_init_zero ssc_init
1212 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1213 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1215 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1216 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1217 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1220 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1221 const regnode_charclass *and_with)
1223 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1224 * another SSC or a regular ANYOF class. Can create false positives. */
1229 PERL_ARGS_ASSERT_SSC_AND;
1231 assert(is_ANYOF_SYNTHETIC(ssc));
1233 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1234 * the code point inversion list and just the relevant flags */
1235 if (is_ANYOF_SYNTHETIC(and_with)) {
1236 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1237 anded_flags = ANYOF_FLAGS(and_with);
1239 /* XXX This is a kludge around what appears to be deficiencies in the
1240 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1241 * there are paths through the optimizer where it doesn't get weeded
1242 * out when it should. And if we don't make some extra provision for
1243 * it like the code just below, it doesn't get added when it should.
1244 * This solution is to add it only when AND'ing, which is here, and
1245 * only when what is being AND'ed is the pristine, original node
1246 * matching anything. Thus it is like adding it to ssc_anything() but
1247 * only when the result is to be AND'ed. Probably the same solution
1248 * could be adopted for the same problem we have with /l matching,
1249 * which is solved differently in S_ssc_init(), and that would lead to
1250 * fewer false positives than that solution has. But if this solution
1251 * creates bugs, the consequences are only that a warning isn't raised
1252 * that should be; while the consequences for having /l bugs is
1253 * incorrect matches */
1254 if (ssc_is_anything((regnode_ssc *)and_with)) {
1255 anded_flags |= ANYOF_WARN_SUPER;
1259 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1260 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1263 ANYOF_FLAGS(ssc) &= anded_flags;
1265 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1266 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1267 * 'and_with' may be inverted. When not inverted, we have the situation of
1269 * (C1 | P1) & (C2 | P2)
1270 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1271 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1272 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1273 * <= ((C1 & C2) | P1 | P2)
1274 * Alternatively, the last few steps could be:
1275 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1276 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1277 * <= (C1 | C2 | (P1 & P2))
1278 * We favor the second approach if either P1 or P2 is non-empty. This is
1279 * because these components are a barrier to doing optimizations, as what
1280 * they match cannot be known until the moment of matching as they are
1281 * dependent on the current locale, 'AND"ing them likely will reduce or
1283 * But we can do better if we know that C1,P1 are in their initial state (a
1284 * frequent occurrence), each matching everything:
1285 * (<everything>) & (C2 | P2) = C2 | P2
1286 * Similarly, if C2,P2 are in their initial state (again a frequent
1287 * occurrence), the result is a no-op
1288 * (C1 | P1) & (<everything>) = C1 | P1
1291 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1292 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1293 * <= (C1 & ~C2) | (P1 & ~P2)
1296 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1297 && ! is_ANYOF_SYNTHETIC(and_with))
1301 ssc_intersection(ssc,
1303 FALSE /* Has already been inverted */
1306 /* If either P1 or P2 is empty, the intersection will be also; can skip
1308 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1309 ANYOF_POSIXL_ZERO(ssc);
1311 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1313 /* Note that the Posix class component P from 'and_with' actually
1315 * P = Pa | Pb | ... | Pn
1316 * where each component is one posix class, such as in [\w\s].
1318 * ~P = ~(Pa | Pb | ... | Pn)
1319 * = ~Pa & ~Pb & ... & ~Pn
1320 * <= ~Pa | ~Pb | ... | ~Pn
1321 * The last is something we can easily calculate, but unfortunately
1322 * is likely to have many false positives. We could do better
1323 * in some (but certainly not all) instances if two classes in
1324 * P have known relationships. For example
1325 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1327 * :lower: & :print: = :lower:
1328 * And similarly for classes that must be disjoint. For example,
1329 * since \s and \w can have no elements in common based on rules in
1330 * the POSIX standard,
1331 * \w & ^\S = nothing
1332 * Unfortunately, some vendor locales do not meet the Posix
1333 * standard, in particular almost everything by Microsoft.
1334 * The loop below just changes e.g., \w into \W and vice versa */
1336 regnode_charclass_posixl temp;
1337 int add = 1; /* To calculate the index of the complement */
1339 ANYOF_POSIXL_ZERO(&temp);
1340 for (i = 0; i < ANYOF_MAX; i++) {
1342 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1343 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1345 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1346 ANYOF_POSIXL_SET(&temp, i + add);
1348 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1350 ANYOF_POSIXL_AND(&temp, ssc);
1352 } /* else ssc already has no posixes */
1353 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1354 in its initial state */
1355 else if (! is_ANYOF_SYNTHETIC(and_with)
1356 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1358 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1359 * copy it over 'ssc' */
1360 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1361 if (is_ANYOF_SYNTHETIC(and_with)) {
1362 StructCopy(and_with, ssc, regnode_ssc);
1365 ssc->invlist = anded_cp_list;
1366 ANYOF_POSIXL_ZERO(ssc);
1367 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1368 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1372 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1373 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1375 /* One or the other of P1, P2 is non-empty. */
1376 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1377 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1379 ssc_union(ssc, anded_cp_list, FALSE);
1381 else { /* P1 = P2 = empty */
1382 ssc_intersection(ssc, anded_cp_list, FALSE);
1388 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1389 const regnode_charclass *or_with)
1391 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1392 * another SSC or a regular ANYOF class. Can create false positives if
1393 * 'or_with' is to be inverted. */
1398 PERL_ARGS_ASSERT_SSC_OR;
1400 assert(is_ANYOF_SYNTHETIC(ssc));
1402 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1403 * the code point inversion list and just the relevant flags */
1404 if (is_ANYOF_SYNTHETIC(or_with)) {
1405 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1406 ored_flags = ANYOF_FLAGS(or_with);
1409 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1410 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1413 ANYOF_FLAGS(ssc) |= ored_flags;
1415 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1416 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1417 * 'or_with' may be inverted. When not inverted, we have the simple
1418 * situation of computing:
1419 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1420 * If P1|P2 yields a situation with both a class and its complement are
1421 * set, like having both \w and \W, this matches all code points, and we
1422 * can delete these from the P component of the ssc going forward. XXX We
1423 * might be able to delete all the P components, but I (khw) am not certain
1424 * about this, and it is better to be safe.
1427 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1428 * <= (C1 | P1) | ~C2
1429 * <= (C1 | ~C2) | P1
1430 * (which results in actually simpler code than the non-inverted case)
1433 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1434 && ! is_ANYOF_SYNTHETIC(or_with))
1436 /* We ignore P2, leaving P1 going forward */
1437 } /* else Not inverted */
1438 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1439 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1440 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1442 for (i = 0; i < ANYOF_MAX; i += 2) {
1443 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1445 ssc_match_all_cp(ssc);
1446 ANYOF_POSIXL_CLEAR(ssc, i);
1447 ANYOF_POSIXL_CLEAR(ssc, i+1);
1455 FALSE /* Already has been inverted */
1459 PERL_STATIC_INLINE void
1460 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1462 PERL_ARGS_ASSERT_SSC_UNION;
1464 assert(is_ANYOF_SYNTHETIC(ssc));
1466 _invlist_union_maybe_complement_2nd(ssc->invlist,
1472 PERL_STATIC_INLINE void
1473 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1475 const bool invert2nd)
1477 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1479 assert(is_ANYOF_SYNTHETIC(ssc));
1481 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1487 PERL_STATIC_INLINE void
1488 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1490 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1492 assert(is_ANYOF_SYNTHETIC(ssc));
1494 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1497 PERL_STATIC_INLINE void
1498 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1500 /* AND just the single code point 'cp' into the SSC 'ssc' */
1502 SV* cp_list = _new_invlist(2);
1504 PERL_ARGS_ASSERT_SSC_CP_AND;
1506 assert(is_ANYOF_SYNTHETIC(ssc));
1508 cp_list = add_cp_to_invlist(cp_list, cp);
1509 ssc_intersection(ssc, cp_list,
1510 FALSE /* Not inverted */
1512 SvREFCNT_dec_NN(cp_list);
1515 PERL_STATIC_INLINE void
1516 S_ssc_clear_locale(regnode_ssc *ssc)
1518 /* Set the SSC 'ssc' to not match any locale things */
1519 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1521 assert(is_ANYOF_SYNTHETIC(ssc));
1523 ANYOF_POSIXL_ZERO(ssc);
1524 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1527 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
1530 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
1532 /* The synthetic start class is used to hopefully quickly winnow down
1533 * places where a pattern could start a match in the target string. If it
1534 * doesn't really narrow things down that much, there isn't much point to
1535 * having the overhead of using it. This function uses some very crude
1536 * heuristics to decide if to use the ssc or not.
1538 * It returns TRUE if 'ssc' rules out more than half what it considers to
1539 * be the "likely" possible matches, but of course it doesn't know what the
1540 * actual things being matched are going to be; these are only guesses
1542 * For /l matches, it assumes that the only likely matches are going to be
1543 * in the 0-255 range, uniformly distributed, so half of that is 127
1544 * For /a and /d matches, it assumes that the likely matches will be just
1545 * the ASCII range, so half of that is 63
1546 * For /u and there isn't anything matching above the Latin1 range, it
1547 * assumes that that is the only range likely to be matched, and uses
1548 * half that as the cut-off: 127. If anything matches above Latin1,
1549 * it assumes that all of Unicode could match (uniformly), except for
1550 * non-Unicode code points and things in the General Category "Other"
1551 * (unassigned, private use, surrogates, controls and formats). This
1552 * is a much large number. */
1554 const U32 max_match = (LOC)
1558 : (invlist_highest(ssc->invlist) < 256)
1560 : ((NON_OTHER_COUNT + 1) / 2) - 1;
1561 U32 count = 0; /* Running total of number of code points matched by
1563 UV start, end; /* Start and end points of current range in inversion
1566 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
1568 invlist_iterinit(ssc->invlist);
1569 while (invlist_iternext(ssc->invlist, &start, &end)) {
1571 /* /u is the only thing that we expect to match above 255; so if not /u
1572 * and even if there are matches above 255, ignore them. This catches
1573 * things like \d under /d which does match the digits above 255, but
1574 * since the pattern is /d, it is not likely to be expecting them */
1575 if (! UNI_SEMANTICS) {
1579 end = MIN(end, 255);
1581 count += end - start + 1;
1582 if (count > max_match) {
1583 invlist_iterfinish(ssc->invlist);
1593 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1595 /* The inversion list in the SSC is marked mortal; now we need a more
1596 * permanent copy, which is stored the same way that is done in a regular
1597 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
1600 SV* invlist = invlist_clone(ssc->invlist);
1602 PERL_ARGS_ASSERT_SSC_FINALIZE;
1604 assert(is_ANYOF_SYNTHETIC(ssc));
1606 /* The code in this file assumes that all but these flags aren't relevant
1607 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
1608 * by the time we reach here */
1609 assert(! (ANYOF_FLAGS(ssc) & ~ANYOF_COMMON_FLAGS));
1611 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1613 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
1614 NULL, NULL, NULL, FALSE);
1616 /* Make sure is clone-safe */
1617 ssc->invlist = NULL;
1619 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1620 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
1623 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
1626 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1627 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
1628 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1629 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
1630 ? (TRIE_LIST_CUR( idx ) - 1) \
1636 dump_trie(trie,widecharmap,revcharmap)
1637 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1638 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1640 These routines dump out a trie in a somewhat readable format.
1641 The _interim_ variants are used for debugging the interim
1642 tables that are used to generate the final compressed
1643 representation which is what dump_trie expects.
1645 Part of the reason for their existence is to provide a form
1646 of documentation as to how the different representations function.
1651 Dumps the final compressed table form of the trie to Perl_debug_log.
1652 Used for debugging make_trie().
1656 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1657 AV *revcharmap, U32 depth)
1660 SV *sv=sv_newmortal();
1661 int colwidth= widecharmap ? 6 : 4;
1663 GET_RE_DEBUG_FLAGS_DECL;
1665 PERL_ARGS_ASSERT_DUMP_TRIE;
1667 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1668 (int)depth * 2 + 2,"",
1669 "Match","Base","Ofs" );
1671 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1672 SV ** const tmp = av_fetch( revcharmap, state, 0);
1674 PerlIO_printf( Perl_debug_log, "%*s",
1676 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1677 PL_colors[0], PL_colors[1],
1678 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1679 PERL_PV_ESCAPE_FIRSTCHAR
1684 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1685 (int)depth * 2 + 2,"");
1687 for( state = 0 ; state < trie->uniquecharcount ; state++ )
1688 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1689 PerlIO_printf( Perl_debug_log, "\n");
1691 for( state = 1 ; state < trie->statecount ; state++ ) {
1692 const U32 base = trie->states[ state ].trans.base;
1694 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1695 (int)depth * 2 + 2,"", (UV)state);
1697 if ( trie->states[ state ].wordnum ) {
1698 PerlIO_printf( Perl_debug_log, " W%4X",
1699 trie->states[ state ].wordnum );
1701 PerlIO_printf( Perl_debug_log, "%6s", "" );
1704 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1709 while( ( base + ofs < trie->uniquecharcount ) ||
1710 ( base + ofs - trie->uniquecharcount < trie->lasttrans
1711 && trie->trans[ base + ofs - trie->uniquecharcount ].check
1715 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1717 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1718 if ( ( base + ofs >= trie->uniquecharcount )
1719 && ( base + ofs - trie->uniquecharcount
1721 && trie->trans[ base + ofs
1722 - trie->uniquecharcount ].check == state )
1724 PerlIO_printf( Perl_debug_log, "%*"UVXf,
1726 (UV)trie->trans[ base + ofs
1727 - trie->uniquecharcount ].next );
1729 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
1733 PerlIO_printf( Perl_debug_log, "]");
1736 PerlIO_printf( Perl_debug_log, "\n" );
1738 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
1740 for (word=1; word <= trie->wordcount; word++) {
1741 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1742 (int)word, (int)(trie->wordinfo[word].prev),
1743 (int)(trie->wordinfo[word].len));
1745 PerlIO_printf(Perl_debug_log, "\n" );
1748 Dumps a fully constructed but uncompressed trie in list form.
1749 List tries normally only are used for construction when the number of
1750 possible chars (trie->uniquecharcount) is very high.
1751 Used for debugging make_trie().
1754 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
1755 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1759 SV *sv=sv_newmortal();
1760 int colwidth= widecharmap ? 6 : 4;
1761 GET_RE_DEBUG_FLAGS_DECL;
1763 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1765 /* print out the table precompression. */
1766 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1767 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1768 "------:-----+-----------------\n" );
1770 for( state=1 ; state < next_alloc ; state ++ ) {
1773 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
1774 (int)depth * 2 + 2,"", (UV)state );
1775 if ( ! trie->states[ state ].wordnum ) {
1776 PerlIO_printf( Perl_debug_log, "%5s| ","");
1778 PerlIO_printf( Perl_debug_log, "W%4x| ",
1779 trie->states[ state ].wordnum
1782 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1783 SV ** const tmp = av_fetch( revcharmap,
1784 TRIE_LIST_ITEM(state,charid).forid, 0);
1786 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1788 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
1790 PL_colors[0], PL_colors[1],
1791 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
1792 | PERL_PV_ESCAPE_FIRSTCHAR
1794 TRIE_LIST_ITEM(state,charid).forid,
1795 (UV)TRIE_LIST_ITEM(state,charid).newstate
1798 PerlIO_printf(Perl_debug_log, "\n%*s| ",
1799 (int)((depth * 2) + 14), "");
1802 PerlIO_printf( Perl_debug_log, "\n");
1807 Dumps a fully constructed but uncompressed trie in table form.
1808 This is the normal DFA style state transition table, with a few
1809 twists to facilitate compression later.
1810 Used for debugging make_trie().
1813 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1814 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1819 SV *sv=sv_newmortal();
1820 int colwidth= widecharmap ? 6 : 4;
1821 GET_RE_DEBUG_FLAGS_DECL;
1823 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1826 print out the table precompression so that we can do a visual check
1827 that they are identical.
1830 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1832 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1833 SV ** const tmp = av_fetch( revcharmap, charid, 0);
1835 PerlIO_printf( Perl_debug_log, "%*s",
1837 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1838 PL_colors[0], PL_colors[1],
1839 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1840 PERL_PV_ESCAPE_FIRSTCHAR
1846 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1848 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1849 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1852 PerlIO_printf( Perl_debug_log, "\n" );
1854 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1856 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1857 (int)depth * 2 + 2,"",
1858 (UV)TRIE_NODENUM( state ) );
1860 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1861 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1863 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1865 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1867 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1868 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
1869 (UV)trie->trans[ state ].check );
1871 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
1872 (UV)trie->trans[ state ].check,
1873 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1881 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1882 startbranch: the first branch in the whole branch sequence
1883 first : start branch of sequence of branch-exact nodes.
1884 May be the same as startbranch
1885 last : Thing following the last branch.
1886 May be the same as tail.
1887 tail : item following the branch sequence
1888 count : words in the sequence
1889 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
1890 depth : indent depth
1892 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1894 A trie is an N'ary tree where the branches are determined by digital
1895 decomposition of the key. IE, at the root node you look up the 1st character and
1896 follow that branch repeat until you find the end of the branches. Nodes can be
1897 marked as "accepting" meaning they represent a complete word. Eg:
1901 would convert into the following structure. Numbers represent states, letters
1902 following numbers represent valid transitions on the letter from that state, if
1903 the number is in square brackets it represents an accepting state, otherwise it
1904 will be in parenthesis.
1906 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1910 (1) +-i->(6)-+-s->[7]
1912 +-s->(3)-+-h->(4)-+-e->[5]
1914 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1916 This shows that when matching against the string 'hers' we will begin at state 1
1917 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1918 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1919 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1920 single traverse. We store a mapping from accepting to state to which word was
1921 matched, and then when we have multiple possibilities we try to complete the
1922 rest of the regex in the order in which they occurred in the alternation.
1924 The only prior NFA like behaviour that would be changed by the TRIE support is
1925 the silent ignoring of duplicate alternations which are of the form:
1927 / (DUPE|DUPE) X? (?{ ... }) Y /x
1929 Thus EVAL blocks following a trie may be called a different number of times with
1930 and without the optimisation. With the optimisations dupes will be silently
1931 ignored. This inconsistent behaviour of EVAL type nodes is well established as
1932 the following demonstrates:
1934 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1936 which prints out 'word' three times, but
1938 'words'=~/(word|word|word)(?{ print $1 })S/
1940 which doesnt print it out at all. This is due to other optimisations kicking in.
1942 Example of what happens on a structural level:
1944 The regexp /(ac|ad|ab)+/ will produce the following debug output:
1946 1: CURLYM[1] {1,32767}(18)
1957 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1958 and should turn into:
1960 1: CURLYM[1] {1,32767}(18)
1962 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1970 Cases where tail != last would be like /(?foo|bar)baz/:
1980 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1981 and would end up looking like:
1984 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1991 d = uvchr_to_utf8_flags(d, uv, 0);
1993 is the recommended Unicode-aware way of saying
1998 #define TRIE_STORE_REVCHAR(val) \
2001 SV *zlopp = newSV(7); /* XXX: optimize me */ \
2002 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2003 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2004 SvCUR_set(zlopp, kapow - flrbbbbb); \
2007 av_push(revcharmap, zlopp); \
2009 char ooooff = (char)val; \
2010 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2014 /* This gets the next character from the input, folding it if not already
2016 #define TRIE_READ_CHAR STMT_START { \
2019 /* if it is UTF then it is either already folded, or does not need \
2021 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2023 else if (folder == PL_fold_latin1) { \
2024 /* This folder implies Unicode rules, which in the range expressible \
2025 * by not UTF is the lower case, with the two exceptions, one of \
2026 * which should have been taken care of before calling this */ \
2027 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2028 uvc = toLOWER_L1(*uc); \
2029 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2032 /* raw data, will be folded later if needed */ \
2040 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2041 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2042 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
2043 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2045 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2046 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2047 TRIE_LIST_CUR( state )++; \
2050 #define TRIE_LIST_NEW(state) STMT_START { \
2051 Newxz( trie->states[ state ].trans.list, \
2052 4, reg_trie_trans_le ); \
2053 TRIE_LIST_CUR( state ) = 1; \
2054 TRIE_LIST_LEN( state ) = 4; \
2057 #define TRIE_HANDLE_WORD(state) STMT_START { \
2058 U16 dupe= trie->states[ state ].wordnum; \
2059 regnode * const noper_next = regnext( noper ); \
2062 /* store the word for dumping */ \
2064 if (OP(noper) != NOTHING) \
2065 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2067 tmp = newSVpvn_utf8( "", 0, UTF ); \
2068 av_push( trie_words, tmp ); \
2072 trie->wordinfo[curword].prev = 0; \
2073 trie->wordinfo[curword].len = wordlen; \
2074 trie->wordinfo[curword].accept = state; \
2076 if ( noper_next < tail ) { \
2078 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2080 trie->jump[curword] = (U16)(noper_next - convert); \
2082 jumper = noper_next; \
2084 nextbranch= regnext(cur); \
2088 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2089 /* chain, so that when the bits of chain are later */\
2090 /* linked together, the dups appear in the chain */\
2091 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2092 trie->wordinfo[dupe].prev = curword; \
2094 /* we haven't inserted this word yet. */ \
2095 trie->states[ state ].wordnum = curword; \
2100 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2101 ( ( base + charid >= ucharcount \
2102 && base + charid < ubound \
2103 && state == trie->trans[ base - ucharcount + charid ].check \
2104 && trie->trans[ base - ucharcount + charid ].next ) \
2105 ? trie->trans[ base - ucharcount + charid ].next \
2106 : ( state==1 ? special : 0 ) \
2110 #define MADE_JUMP_TRIE 2
2111 #define MADE_EXACT_TRIE 4
2114 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2115 regnode *first, regnode *last, regnode *tail,
2116 U32 word_count, U32 flags, U32 depth)
2118 /* first pass, loop through and scan words */
2119 reg_trie_data *trie;
2120 HV *widecharmap = NULL;
2121 AV *revcharmap = newAV();
2127 regnode *jumper = NULL;
2128 regnode *nextbranch = NULL;
2129 regnode *convert = NULL;
2130 U32 *prev_states; /* temp array mapping each state to previous one */
2131 /* we just use folder as a flag in utf8 */
2132 const U8 * folder = NULL;
2135 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2136 AV *trie_words = NULL;
2137 /* along with revcharmap, this only used during construction but both are
2138 * useful during debugging so we store them in the struct when debugging.
2141 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2142 STRLEN trie_charcount=0;
2144 SV *re_trie_maxbuff;
2145 GET_RE_DEBUG_FLAGS_DECL;
2147 PERL_ARGS_ASSERT_MAKE_TRIE;
2149 PERL_UNUSED_ARG(depth);
2153 case EXACT: case EXACTL: break;
2157 case EXACTFLU8: folder = PL_fold_latin1; break;
2158 case EXACTF: folder = PL_fold; break;
2159 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2162 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2164 trie->startstate = 1;
2165 trie->wordcount = word_count;
2166 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2167 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2168 if (flags == EXACT || flags == EXACTL)
2169 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2170 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2171 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2174 trie_words = newAV();
2177 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2178 assert(re_trie_maxbuff);
2179 if (!SvIOK(re_trie_maxbuff)) {
2180 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2182 DEBUG_TRIE_COMPILE_r({
2183 PerlIO_printf( Perl_debug_log,
2184 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2185 (int)depth * 2 + 2, "",
2186 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2187 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2190 /* Find the node we are going to overwrite */
2191 if ( first == startbranch && OP( last ) != BRANCH ) {
2192 /* whole branch chain */
2195 /* branch sub-chain */
2196 convert = NEXTOPER( first );
2199 /* -- First loop and Setup --
2201 We first traverse the branches and scan each word to determine if it
2202 contains widechars, and how many unique chars there are, this is
2203 important as we have to build a table with at least as many columns as we
2206 We use an array of integers to represent the character codes 0..255
2207 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2208 the native representation of the character value as the key and IV's for
2211 *TODO* If we keep track of how many times each character is used we can
2212 remap the columns so that the table compression later on is more
2213 efficient in terms of memory by ensuring the most common value is in the
2214 middle and the least common are on the outside. IMO this would be better
2215 than a most to least common mapping as theres a decent chance the most
2216 common letter will share a node with the least common, meaning the node
2217 will not be compressible. With a middle is most common approach the worst
2218 case is when we have the least common nodes twice.
2222 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2223 regnode *noper = NEXTOPER( cur );
2224 const U8 *uc = (U8*)STRING( noper );
2225 const U8 *e = uc + STR_LEN( noper );
2227 U32 wordlen = 0; /* required init */
2228 STRLEN minchars = 0;
2229 STRLEN maxchars = 0;
2230 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2233 if (OP(noper) == NOTHING) {
2234 regnode *noper_next= regnext(noper);
2235 if (noper_next != tail && OP(noper_next) == flags) {
2237 uc= (U8*)STRING(noper);
2238 e= uc + STR_LEN(noper);
2239 trie->minlen= STR_LEN(noper);
2246 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2247 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2248 regardless of encoding */
2249 if (OP( noper ) == EXACTFU_SS) {
2250 /* false positives are ok, so just set this */
2251 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2254 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2256 TRIE_CHARCOUNT(trie)++;
2259 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2260 * is in effect. Under /i, this character can match itself, or
2261 * anything that folds to it. If not under /i, it can match just
2262 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2263 * all fold to k, and all are single characters. But some folds
2264 * expand to more than one character, so for example LATIN SMALL
2265 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2266 * the string beginning at 'uc' is 'ffi', it could be matched by
2267 * three characters, or just by the one ligature character. (It
2268 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2269 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2270 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2271 * match.) The trie needs to know the minimum and maximum number
2272 * of characters that could match so that it can use size alone to
2273 * quickly reject many match attempts. The max is simple: it is
2274 * the number of folded characters in this branch (since a fold is
2275 * never shorter than what folds to it. */
2279 /* And the min is equal to the max if not under /i (indicated by
2280 * 'folder' being NULL), or there are no multi-character folds. If
2281 * there is a multi-character fold, the min is incremented just
2282 * once, for the character that folds to the sequence. Each
2283 * character in the sequence needs to be added to the list below of
2284 * characters in the trie, but we count only the first towards the
2285 * min number of characters needed. This is done through the
2286 * variable 'foldlen', which is returned by the macros that look
2287 * for these sequences as the number of bytes the sequence
2288 * occupies. Each time through the loop, we decrement 'foldlen' by
2289 * how many bytes the current char occupies. Only when it reaches
2290 * 0 do we increment 'minchars' or look for another multi-character
2292 if (folder == NULL) {
2295 else if (foldlen > 0) {
2296 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2301 /* See if *uc is the beginning of a multi-character fold. If
2302 * so, we decrement the length remaining to look at, to account
2303 * for the current character this iteration. (We can use 'uc'
2304 * instead of the fold returned by TRIE_READ_CHAR because for
2305 * non-UTF, the latin1_safe macro is smart enough to account
2306 * for all the unfolded characters, and because for UTF, the
2307 * string will already have been folded earlier in the
2308 * compilation process */
2310 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2311 foldlen -= UTF8SKIP(uc);
2314 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2319 /* The current character (and any potential folds) should be added
2320 * to the possible matching characters for this position in this
2324 U8 folded= folder[ (U8) uvc ];
2325 if ( !trie->charmap[ folded ] ) {
2326 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2327 TRIE_STORE_REVCHAR( folded );
2330 if ( !trie->charmap[ uvc ] ) {
2331 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2332 TRIE_STORE_REVCHAR( uvc );
2335 /* store the codepoint in the bitmap, and its folded
2337 TRIE_BITMAP_SET(trie, uvc);
2339 /* store the folded codepoint */
2340 if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
2343 /* store first byte of utf8 representation of
2344 variant codepoints */
2345 if (! UVCHR_IS_INVARIANT(uvc)) {
2346 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
2349 set_bit = 0; /* We've done our bit :-) */
2353 /* XXX We could come up with the list of code points that fold
2354 * to this using PL_utf8_foldclosures, except not for
2355 * multi-char folds, as there may be multiple combinations
2356 * there that could work, which needs to wait until runtime to
2357 * resolve (The comment about LIGATURE FFI above is such an
2362 widecharmap = newHV();
2364 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2367 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
2369 if ( !SvTRUE( *svpp ) ) {
2370 sv_setiv( *svpp, ++trie->uniquecharcount );
2371 TRIE_STORE_REVCHAR(uvc);
2374 } /* end loop through characters in this branch of the trie */
2376 /* We take the min and max for this branch and combine to find the min
2377 * and max for all branches processed so far */
2378 if( cur == first ) {
2379 trie->minlen = minchars;
2380 trie->maxlen = maxchars;
2381 } else if (minchars < trie->minlen) {
2382 trie->minlen = minchars;
2383 } else if (maxchars > trie->maxlen) {
2384 trie->maxlen = maxchars;
2386 } /* end first pass */
2387 DEBUG_TRIE_COMPILE_r(
2388 PerlIO_printf( Perl_debug_log,
2389 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2390 (int)depth * 2 + 2,"",
2391 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2392 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2393 (int)trie->minlen, (int)trie->maxlen )
2397 We now know what we are dealing with in terms of unique chars and
2398 string sizes so we can calculate how much memory a naive
2399 representation using a flat table will take. If it's over a reasonable
2400 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2401 conservative but potentially much slower representation using an array
2404 At the end we convert both representations into the same compressed
2405 form that will be used in regexec.c for matching with. The latter
2406 is a form that cannot be used to construct with but has memory
2407 properties similar to the list form and access properties similar
2408 to the table form making it both suitable for fast searches and
2409 small enough that its feasable to store for the duration of a program.
2411 See the comment in the code where the compressed table is produced
2412 inplace from the flat tabe representation for an explanation of how
2413 the compression works.
2418 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2421 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2422 > SvIV(re_trie_maxbuff) )
2425 Second Pass -- Array Of Lists Representation
2427 Each state will be represented by a list of charid:state records
2428 (reg_trie_trans_le) the first such element holds the CUR and LEN
2429 points of the allocated array. (See defines above).
2431 We build the initial structure using the lists, and then convert
2432 it into the compressed table form which allows faster lookups
2433 (but cant be modified once converted).
2436 STRLEN transcount = 1;
2438 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2439 "%*sCompiling trie using list compiler\n",
2440 (int)depth * 2 + 2, ""));
2442 trie->states = (reg_trie_state *)
2443 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2444 sizeof(reg_trie_state) );
2448 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2450 regnode *noper = NEXTOPER( cur );
2451 U8 *uc = (U8*)STRING( noper );
2452 const U8 *e = uc + STR_LEN( noper );
2453 U32 state = 1; /* required init */
2454 U16 charid = 0; /* sanity init */
2455 U32 wordlen = 0; /* required init */
2457 if (OP(noper) == NOTHING) {
2458 regnode *noper_next= regnext(noper);
2459 if (noper_next != tail && OP(noper_next) == flags) {
2461 uc= (U8*)STRING(noper);
2462 e= uc + STR_LEN(noper);
2466 if (OP(noper) != NOTHING) {
2467 for ( ; uc < e ; uc += len ) {
2472 charid = trie->charmap[ uvc ];
2474 SV** const svpp = hv_fetch( widecharmap,
2481 charid=(U16)SvIV( *svpp );
2484 /* charid is now 0 if we dont know the char read, or
2485 * nonzero if we do */
2492 if ( !trie->states[ state ].trans.list ) {
2493 TRIE_LIST_NEW( state );
2496 check <= TRIE_LIST_USED( state );
2499 if ( TRIE_LIST_ITEM( state, check ).forid
2502 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2507 newstate = next_alloc++;
2508 prev_states[newstate] = state;
2509 TRIE_LIST_PUSH( state, charid, newstate );
2514 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2518 TRIE_HANDLE_WORD(state);
2520 } /* end second pass */
2522 /* next alloc is the NEXT state to be allocated */
2523 trie->statecount = next_alloc;
2524 trie->states = (reg_trie_state *)
2525 PerlMemShared_realloc( trie->states,
2527 * sizeof(reg_trie_state) );
2529 /* and now dump it out before we compress it */
2530 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2531 revcharmap, next_alloc,
2535 trie->trans = (reg_trie_trans *)
2536 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
2543 for( state=1 ; state < next_alloc ; state ++ ) {
2547 DEBUG_TRIE_COMPILE_MORE_r(
2548 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2552 if (trie->states[state].trans.list) {
2553 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2557 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2558 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2559 if ( forid < minid ) {
2561 } else if ( forid > maxid ) {
2565 if ( transcount < tp + maxid - minid + 1) {
2567 trie->trans = (reg_trie_trans *)
2568 PerlMemShared_realloc( trie->trans,
2570 * sizeof(reg_trie_trans) );
2571 Zero( trie->trans + (transcount / 2),
2575 base = trie->uniquecharcount + tp - minid;
2576 if ( maxid == minid ) {
2578 for ( ; zp < tp ; zp++ ) {
2579 if ( ! trie->trans[ zp ].next ) {
2580 base = trie->uniquecharcount + zp - minid;
2581 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2583 trie->trans[ zp ].check = state;
2589 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2591 trie->trans[ tp ].check = state;
2596 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2597 const U32 tid = base
2598 - trie->uniquecharcount
2599 + TRIE_LIST_ITEM( state, idx ).forid;
2600 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2602 trie->trans[ tid ].check = state;
2604 tp += ( maxid - minid + 1 );
2606 Safefree(trie->states[ state ].trans.list);
2609 DEBUG_TRIE_COMPILE_MORE_r(
2610 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2613 trie->states[ state ].trans.base=base;
2615 trie->lasttrans = tp + 1;
2619 Second Pass -- Flat Table Representation.
2621 we dont use the 0 slot of either trans[] or states[] so we add 1 to
2622 each. We know that we will need Charcount+1 trans at most to store
2623 the data (one row per char at worst case) So we preallocate both
2624 structures assuming worst case.
2626 We then construct the trie using only the .next slots of the entry
2629 We use the .check field of the first entry of the node temporarily
2630 to make compression both faster and easier by keeping track of how
2631 many non zero fields are in the node.
2633 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2636 There are two terms at use here: state as a TRIE_NODEIDX() which is
2637 a number representing the first entry of the node, and state as a
2638 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2639 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2640 if there are 2 entrys per node. eg:
2648 The table is internally in the right hand, idx form. However as we
2649 also have to deal with the states array which is indexed by nodenum
2650 we have to use TRIE_NODENUM() to convert.
2653 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2654 "%*sCompiling trie using table compiler\n",
2655 (int)depth * 2 + 2, ""));
2657 trie->trans = (reg_trie_trans *)
2658 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2659 * trie->uniquecharcount + 1,
2660 sizeof(reg_trie_trans) );
2661 trie->states = (reg_trie_state *)
2662 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2663 sizeof(reg_trie_state) );
2664 next_alloc = trie->uniquecharcount + 1;
2667 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2669 regnode *noper = NEXTOPER( cur );
2670 const U8 *uc = (U8*)STRING( noper );
2671 const U8 *e = uc + STR_LEN( noper );
2673 U32 state = 1; /* required init */
2675 U16 charid = 0; /* sanity init */
2676 U32 accept_state = 0; /* sanity init */
2678 U32 wordlen = 0; /* required init */
2680 if (OP(noper) == NOTHING) {
2681 regnode *noper_next= regnext(noper);
2682 if (noper_next != tail && OP(noper_next) == flags) {
2684 uc= (U8*)STRING(noper);
2685 e= uc + STR_LEN(noper);
2689 if ( OP(noper) != NOTHING ) {
2690 for ( ; uc < e ; uc += len ) {
2695 charid = trie->charmap[ uvc ];
2697 SV* const * const svpp = hv_fetch( widecharmap,
2701 charid = svpp ? (U16)SvIV(*svpp) : 0;
2705 if ( !trie->trans[ state + charid ].next ) {
2706 trie->trans[ state + charid ].next = next_alloc;
2707 trie->trans[ state ].check++;
2708 prev_states[TRIE_NODENUM(next_alloc)]
2709 = TRIE_NODENUM(state);
2710 next_alloc += trie->uniquecharcount;
2712 state = trie->trans[ state + charid ].next;
2714 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2716 /* charid is now 0 if we dont know the char read, or
2717 * nonzero if we do */
2720 accept_state = TRIE_NODENUM( state );
2721 TRIE_HANDLE_WORD(accept_state);
2723 } /* end second pass */
2725 /* and now dump it out before we compress it */
2726 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
2728 next_alloc, depth+1));
2732 * Inplace compress the table.*
2734 For sparse data sets the table constructed by the trie algorithm will
2735 be mostly 0/FAIL transitions or to put it another way mostly empty.
2736 (Note that leaf nodes will not contain any transitions.)
2738 This algorithm compresses the tables by eliminating most such
2739 transitions, at the cost of a modest bit of extra work during lookup:
2741 - Each states[] entry contains a .base field which indicates the
2742 index in the state[] array wheres its transition data is stored.
2744 - If .base is 0 there are no valid transitions from that node.
2746 - If .base is nonzero then charid is added to it to find an entry in
2749 -If trans[states[state].base+charid].check!=state then the
2750 transition is taken to be a 0/Fail transition. Thus if there are fail
2751 transitions at the front of the node then the .base offset will point
2752 somewhere inside the previous nodes data (or maybe even into a node
2753 even earlier), but the .check field determines if the transition is
2757 The following process inplace converts the table to the compressed
2758 table: We first do not compress the root node 1,and mark all its
2759 .check pointers as 1 and set its .base pointer as 1 as well. This
2760 allows us to do a DFA construction from the compressed table later,
2761 and ensures that any .base pointers we calculate later are greater
2764 - We set 'pos' to indicate the first entry of the second node.
2766 - We then iterate over the columns of the node, finding the first and
2767 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2768 and set the .check pointers accordingly, and advance pos
2769 appropriately and repreat for the next node. Note that when we copy
2770 the next pointers we have to convert them from the original
2771 NODEIDX form to NODENUM form as the former is not valid post
2774 - If a node has no transitions used we mark its base as 0 and do not
2775 advance the pos pointer.
2777 - If a node only has one transition we use a second pointer into the
2778 structure to fill in allocated fail transitions from other states.
2779 This pointer is independent of the main pointer and scans forward
2780 looking for null transitions that are allocated to a state. When it
2781 finds one it writes the single transition into the "hole". If the
2782 pointer doesnt find one the single transition is appended as normal.
2784 - Once compressed we can Renew/realloc the structures to release the
2787 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2788 specifically Fig 3.47 and the associated pseudocode.
2792 const U32 laststate = TRIE_NODENUM( next_alloc );
2795 trie->statecount = laststate;
2797 for ( state = 1 ; state < laststate ; state++ ) {
2799 const U32 stateidx = TRIE_NODEIDX( state );
2800 const U32 o_used = trie->trans[ stateidx ].check;
2801 U32 used = trie->trans[ stateidx ].check;
2802 trie->trans[ stateidx ].check = 0;
2805 used && charid < trie->uniquecharcount;
2808 if ( flag || trie->trans[ stateidx + charid ].next ) {
2809 if ( trie->trans[ stateidx + charid ].next ) {
2811 for ( ; zp < pos ; zp++ ) {
2812 if ( ! trie->trans[ zp ].next ) {
2816 trie->states[ state ].trans.base
2818 + trie->uniquecharcount
2820 trie->trans[ zp ].next
2821 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
2823 trie->trans[ zp ].check = state;
2824 if ( ++zp > pos ) pos = zp;
2831 trie->states[ state ].trans.base
2832 = pos + trie->uniquecharcount - charid ;
2834 trie->trans[ pos ].next
2835 = SAFE_TRIE_NODENUM(
2836 trie->trans[ stateidx + charid ].next );
2837 trie->trans[ pos ].check = state;
2842 trie->lasttrans = pos + 1;
2843 trie->states = (reg_trie_state *)
2844 PerlMemShared_realloc( trie->states, laststate
2845 * sizeof(reg_trie_state) );
2846 DEBUG_TRIE_COMPILE_MORE_r(
2847 PerlIO_printf( Perl_debug_log,
2848 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2849 (int)depth * 2 + 2,"",
2850 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
2854 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
2857 } /* end table compress */
2859 DEBUG_TRIE_COMPILE_MORE_r(
2860 PerlIO_printf(Perl_debug_log,
2861 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
2862 (int)depth * 2 + 2, "",
2863 (UV)trie->statecount,
2864 (UV)trie->lasttrans)
2866 /* resize the trans array to remove unused space */
2867 trie->trans = (reg_trie_trans *)
2868 PerlMemShared_realloc( trie->trans, trie->lasttrans
2869 * sizeof(reg_trie_trans) );
2871 { /* Modify the program and insert the new TRIE node */
2872 U8 nodetype =(U8)(flags & 0xFF);
2876 regnode *optimize = NULL;
2877 #ifdef RE_TRACK_PATTERN_OFFSETS
2880 U32 mjd_nodelen = 0;
2881 #endif /* RE_TRACK_PATTERN_OFFSETS */
2882 #endif /* DEBUGGING */
2884 This means we convert either the first branch or the first Exact,
2885 depending on whether the thing following (in 'last') is a branch
2886 or not and whther first is the startbranch (ie is it a sub part of
2887 the alternation or is it the whole thing.)
2888 Assuming its a sub part we convert the EXACT otherwise we convert
2889 the whole branch sequence, including the first.
2891 /* Find the node we are going to overwrite */
2892 if ( first != startbranch || OP( last ) == BRANCH ) {
2893 /* branch sub-chain */
2894 NEXT_OFF( first ) = (U16)(last - first);
2895 #ifdef RE_TRACK_PATTERN_OFFSETS
2897 mjd_offset= Node_Offset((convert));
2898 mjd_nodelen= Node_Length((convert));
2901 /* whole branch chain */
2903 #ifdef RE_TRACK_PATTERN_OFFSETS
2906 const regnode *nop = NEXTOPER( convert );
2907 mjd_offset= Node_Offset((nop));
2908 mjd_nodelen= Node_Length((nop));
2912 PerlIO_printf(Perl_debug_log,
2913 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2914 (int)depth * 2 + 2, "",
2915 (UV)mjd_offset, (UV)mjd_nodelen)
2918 /* But first we check to see if there is a common prefix we can
2919 split out as an EXACT and put in front of the TRIE node. */
2920 trie->startstate= 1;
2921 if ( trie->bitmap && !widecharmap && !trie->jump ) {
2923 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2927 const U32 base = trie->states[ state ].trans.base;
2929 if ( trie->states[state].wordnum )
2932 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2933 if ( ( base + ofs >= trie->uniquecharcount ) &&
2934 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2935 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2937 if ( ++count > 1 ) {
2938 SV **tmp = av_fetch( revcharmap, ofs, 0);
2939 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2940 if ( state == 1 ) break;
2942 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2944 PerlIO_printf(Perl_debug_log,
2945 "%*sNew Start State=%"UVuf" Class: [",
2946 (int)depth * 2 + 2, "",
2949 SV ** const tmp = av_fetch( revcharmap, idx, 0);
2950 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2952 TRIE_BITMAP_SET(trie,*ch);
2954 TRIE_BITMAP_SET(trie, folder[ *ch ]);
2956 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2960 TRIE_BITMAP_SET(trie,*ch);
2962 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2963 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2969 SV **tmp = av_fetch( revcharmap, idx, 0);
2971 char *ch = SvPV( *tmp, len );
2973 SV *sv=sv_newmortal();
2974 PerlIO_printf( Perl_debug_log,
2975 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2976 (int)depth * 2 + 2, "",
2978 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
2979 PL_colors[0], PL_colors[1],
2980 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2981 PERL_PV_ESCAPE_FIRSTCHAR
2986 OP( convert ) = nodetype;
2987 str=STRING(convert);
2990 STR_LEN(convert) += len;
2996 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
3001 trie->prefixlen = (state-1);
3003 regnode *n = convert+NODE_SZ_STR(convert);
3004 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3005 trie->startstate = state;
3006 trie->minlen -= (state - 1);
3007 trie->maxlen -= (state - 1);
3009 /* At least the UNICOS C compiler choked on this
3010 * being argument to DEBUG_r(), so let's just have
3013 #ifdef PERL_EXT_RE_BUILD
3019 regnode *fix = convert;
3020 U32 word = trie->wordcount;
3022 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3023 while( ++fix < n ) {
3024 Set_Node_Offset_Length(fix, 0, 0);
3027 SV ** const tmp = av_fetch( trie_words, word, 0 );
3029 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3030 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3032 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3040 NEXT_OFF(convert) = (U16)(tail - convert);
3041 DEBUG_r(optimize= n);
3047 if ( trie->maxlen ) {
3048 NEXT_OFF( convert ) = (U16)(tail - convert);
3049 ARG_SET( convert, data_slot );
3050 /* Store the offset to the first unabsorbed branch in
3051 jump[0], which is otherwise unused by the jump logic.
3052 We use this when dumping a trie and during optimisation. */
3054 trie->jump[0] = (U16)(nextbranch - convert);
3056 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3057 * and there is a bitmap
3058 * and the first "jump target" node we found leaves enough room
3059 * then convert the TRIE node into a TRIEC node, with the bitmap
3060 * embedded inline in the opcode - this is hypothetically faster.
3062 if ( !trie->states[trie->startstate].wordnum
3064 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3066 OP( convert ) = TRIEC;
3067 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3068 PerlMemShared_free(trie->bitmap);
3071 OP( convert ) = TRIE;
3073 /* store the type in the flags */
3074 convert->flags = nodetype;
3078 + regarglen[ OP( convert ) ];
3080 /* XXX We really should free up the resource in trie now,
3081 as we won't use them - (which resources?) dmq */
3083 /* needed for dumping*/
3084 DEBUG_r(if (optimize) {
3085 regnode *opt = convert;
3087 while ( ++opt < optimize) {
3088 Set_Node_Offset_Length(opt,0,0);
3091 Try to clean up some of the debris left after the
3094 while( optimize < jumper ) {
3095 mjd_nodelen += Node_Length((optimize));
3096 OP( optimize ) = OPTIMIZED;
3097 Set_Node_Offset_Length(optimize,0,0);
3100 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
3102 } /* end node insert */
3104 /* Finish populating the prev field of the wordinfo array. Walk back
3105 * from each accept state until we find another accept state, and if
3106 * so, point the first word's .prev field at the second word. If the
3107 * second already has a .prev field set, stop now. This will be the
3108 * case either if we've already processed that word's accept state,
3109 * or that state had multiple words, and the overspill words were
3110 * already linked up earlier.
3117 for (word=1; word <= trie->wordcount; word++) {
3119 if (trie->wordinfo[word].prev)
3121 state = trie->wordinfo[word].accept;
3123 state = prev_states[state];
3126 prev = trie->states[state].wordnum;
3130 trie->wordinfo[word].prev = prev;
3132 Safefree(prev_states);
3136 /* and now dump out the compressed format */
3137 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3139 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3141 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3142 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3144 SvREFCNT_dec_NN(revcharmap);
3148 : trie->startstate>1
3154 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3156 /* The Trie is constructed and compressed now so we can build a fail array if
3159 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3161 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3165 We find the fail state for each state in the trie, this state is the longest
3166 proper suffix of the current state's 'word' that is also a proper prefix of
3167 another word in our trie. State 1 represents the word '' and is thus the
3168 default fail state. This allows the DFA not to have to restart after its
3169 tried and failed a word at a given point, it simply continues as though it
3170 had been matching the other word in the first place.
3172 'abcdgu'=~/abcdefg|cdgu/
3173 When we get to 'd' we are still matching the first word, we would encounter
3174 'g' which would fail, which would bring us to the state representing 'd' in
3175 the second word where we would try 'g' and succeed, proceeding to match
3178 /* add a fail transition */
3179 const U32 trie_offset = ARG(source);
3180 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3182 const U32 ucharcount = trie->uniquecharcount;
3183 const U32 numstates = trie->statecount;
3184 const U32 ubound = trie->lasttrans + ucharcount;
3188 U32 base = trie->states[ 1 ].trans.base;
3191 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3193 GET_RE_DEBUG_FLAGS_DECL;
3195 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3196 PERL_UNUSED_CONTEXT;
3198 PERL_UNUSED_ARG(depth);
3201 if ( OP(source) == TRIE ) {
3202 struct regnode_1 *op = (struct regnode_1 *)
3203 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3204 StructCopy(source,op,struct regnode_1);
3205 stclass = (regnode *)op;
3207 struct regnode_charclass *op = (struct regnode_charclass *)
3208 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3209 StructCopy(source,op,struct regnode_charclass);
3210 stclass = (regnode *)op;
3212 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3214 ARG_SET( stclass, data_slot );
3215 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3216 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3217 aho->trie=trie_offset;
3218 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3219 Copy( trie->states, aho->states, numstates, reg_trie_state );
3220 Newxz( q, numstates, U32);
3221 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3224 /* initialize fail[0..1] to be 1 so that we always have
3225 a valid final fail state */
3226 fail[ 0 ] = fail[ 1 ] = 1;
3228 for ( charid = 0; charid < ucharcount ; charid++ ) {
3229 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3231 q[ q_write ] = newstate;
3232 /* set to point at the root */
3233 fail[ q[ q_write++ ] ]=1;
3236 while ( q_read < q_write) {
3237 const U32 cur = q[ q_read++ % numstates ];
3238 base = trie->states[ cur ].trans.base;
3240 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3241 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3243 U32 fail_state = cur;
3246 fail_state = fail[ fail_state ];
3247 fail_base = aho->states[ fail_state ].trans.base;
3248 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3250 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3251 fail[ ch_state ] = fail_state;
3252 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3254 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3256 q[ q_write++ % numstates] = ch_state;
3260 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3261 when we fail in state 1, this allows us to use the
3262 charclass scan to find a valid start char. This is based on the principle
3263 that theres a good chance the string being searched contains lots of stuff
3264 that cant be a start char.
3266 fail[ 0 ] = fail[ 1 ] = 0;
3267 DEBUG_TRIE_COMPILE_r({
3268 PerlIO_printf(Perl_debug_log,
3269 "%*sStclass Failtable (%"UVuf" states): 0",
3270 (int)(depth * 2), "", (UV)numstates
3272 for( q_read=1; q_read<numstates; q_read++ ) {
3273 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3275 PerlIO_printf(Perl_debug_log, "\n");
3278 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3283 #define DEBUG_PEEP(str,scan,depth) \
3284 DEBUG_OPTIMISE_r({if (scan){ \
3285 regnode *Next = regnext(scan); \
3286 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); \
3287 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)", \
3288 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),\
3289 Next ? (REG_NODE_NUM(Next)) : 0 ); \
3290 DEBUG_SHOW_STUDY_FLAGS(flags," [ ","]");\
3291 PerlIO_printf(Perl_debug_log, "\n"); \
3294 /* The below joins as many adjacent EXACTish nodes as possible into a single
3295 * one. The regop may be changed if the node(s) contain certain sequences that
3296 * require special handling. The joining is only done if:
3297 * 1) there is room in the current conglomerated node to entirely contain the
3299 * 2) they are the exact same node type
3301 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3302 * these get optimized out
3304 * If a node is to match under /i (folded), the number of characters it matches
3305 * can be different than its character length if it contains a multi-character
3306 * fold. *min_subtract is set to the total delta number of characters of the
3309 * And *unfolded_multi_char is set to indicate whether or not the node contains
3310 * an unfolded multi-char fold. This happens when whether the fold is valid or
3311 * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3312 * SMALL LETTER SHARP S, as only if the target string being matched against
3313 * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3314 * folding rules depend on the locale in force at runtime. (Multi-char folds
3315 * whose components are all above the Latin1 range are not run-time locale
3316 * dependent, and have already been folded by the time this function is
3319 * This is as good a place as any to discuss the design of handling these
3320 * multi-character fold sequences. It's been wrong in Perl for a very long
3321 * time. There are three code points in Unicode whose multi-character folds
3322 * were long ago discovered to mess things up. The previous designs for
3323 * dealing with these involved assigning a special node for them. This
3324 * approach doesn't always work, as evidenced by this example:
3325 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3326 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3327 * would match just the \xDF, it won't be able to handle the case where a
3328 * successful match would have to cross the node's boundary. The new approach
3329 * that hopefully generally solves the problem generates an EXACTFU_SS node
3330 * that is "sss" in this case.
3332 * It turns out that there are problems with all multi-character folds, and not
3333 * just these three. Now the code is general, for all such cases. The
3334 * approach taken is:
3335 * 1) This routine examines each EXACTFish node that could contain multi-
3336 * character folded sequences. Since a single character can fold into
3337 * such a sequence, the minimum match length for this node is less than
3338 * the number of characters in the node. This routine returns in
3339 * *min_subtract how many characters to subtract from the the actual
3340 * length of the string to get a real minimum match length; it is 0 if
3341 * there are no multi-char foldeds. This delta is used by the caller to
3342 * adjust the min length of the match, and the delta between min and max,
3343 * so that the optimizer doesn't reject these possibilities based on size
3345 * 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3346 * is used for an EXACTFU node that contains at least one "ss" sequence in
3347 * it. For non-UTF-8 patterns and strings, this is the only case where
3348 * there is a possible fold length change. That means that a regular
3349 * EXACTFU node without UTF-8 involvement doesn't have to concern itself
3350 * with length changes, and so can be processed faster. regexec.c takes
3351 * advantage of this. Generally, an EXACTFish node that is in UTF-8 is
3352 * pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3353 * known until runtime). This saves effort in regex matching. However,
3354 * the pre-folding isn't done for non-UTF8 patterns because the fold of
3355 * the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3356 * forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
3357 * again, EXACTFL) nodes fold to isn't known until runtime. The fold
3358 * possibilities for the non-UTF8 patterns are quite simple, except for
3359 * the sharp s. All the ones that don't involve a UTF-8 target string are
3360 * members of a fold-pair, and arrays are set up for all of them so that
3361 * the other member of the pair can be found quickly. Code elsewhere in
3362 * this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3363 * 'ss', even if the pattern isn't UTF-8. This avoids the issues
3364 * described in the next item.
3365 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3366 * validity of the fold won't be known until runtime, and so must remain
3367 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFA
3368 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3369 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3370 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3371 * The reason this is a problem is that the optimizer part of regexec.c
3372 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3373 * that a character in the pattern corresponds to at most a single
3374 * character in the target string. (And I do mean character, and not byte
3375 * here, unlike other parts of the documentation that have never been
3376 * updated to account for multibyte Unicode.) sharp s in EXACTF and
3377 * EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3378 * it can match "\x{17F}\x{17F}". These, along with other ones in EXACTFL
3379 * nodes, violate the assumption, and they are the only instances where it
3380 * is violated. I'm reluctant to try to change the assumption, as the
3381 * code involved is impenetrable to me (khw), so instead the code here
3382 * punts. This routine examines EXACTFL nodes, and (when the pattern
3383 * isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3384 * boolean indicating whether or not the node contains such a fold. When
3385 * it is true, the caller sets a flag that later causes the optimizer in
3386 * this file to not set values for the floating and fixed string lengths,
3387 * and thus avoids the optimizer code in regexec.c that makes the invalid
3388 * assumption. Thus, there is no optimization based on string lengths for
3389 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3390 * EXACTF and EXACTFA nodes that contain the sharp s. (The reason the
3391 * assumption is wrong only in these cases is that all other non-UTF-8
3392 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3393 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3394 * EXACTF nodes because we don't know at compile time if it actually
3395 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3396 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3397 * always matches; and EXACTFA where it never does. In an EXACTFA node in
3398 * a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3399 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3400 * string would require the pattern to be forced into UTF-8, the overhead
3401 * of which we want to avoid. Similarly the unfolded multi-char folds in
3402 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3405 * Similarly, the code that generates tries doesn't currently handle
3406 * not-already-folded multi-char folds, and it looks like a pain to change
3407 * that. Therefore, trie generation of EXACTFA nodes with the sharp s
3408 * doesn't work. Instead, such an EXACTFA is turned into a new regnode,
3409 * EXACTFA_NO_TRIE, which the trie code knows not to handle. Most people
3410 * using /iaa matching will be doing so almost entirely with ASCII
3411 * strings, so this should rarely be encountered in practice */
3413 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3414 if (PL_regkind[OP(scan)] == EXACT) \
3415 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
3418 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3419 UV *min_subtract, bool *unfolded_multi_char,
3420 U32 flags,regnode *val, U32 depth)
3422 /* Merge several consecutive EXACTish nodes into one. */
3423 regnode *n = regnext(scan);
3425 regnode *next = scan + NODE_SZ_STR(scan);
3429 regnode *stop = scan;
3430 GET_RE_DEBUG_FLAGS_DECL;
3432 PERL_UNUSED_ARG(depth);
3435 PERL_ARGS_ASSERT_JOIN_EXACT;
3436 #ifndef EXPERIMENTAL_INPLACESCAN
3437 PERL_UNUSED_ARG(flags);
3438 PERL_UNUSED_ARG(val);
3440 DEBUG_PEEP("join",scan,depth);
3442 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3443 * EXACT ones that are mergeable to the current one. */
3445 && (PL_regkind[OP(n)] == NOTHING
3446 || (stringok && OP(n) == OP(scan)))
3448 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3451 if (OP(n) == TAIL || n > next)
3453 if (PL_regkind[OP(n)] == NOTHING) {
3454 DEBUG_PEEP("skip:",n,depth);
3455 NEXT_OFF(scan) += NEXT_OFF(n);
3456 next = n + NODE_STEP_REGNODE;
3463 else if (stringok) {
3464 const unsigned int oldl = STR_LEN(scan);
3465 regnode * const nnext = regnext(n);
3467 /* XXX I (khw) kind of doubt that this works on platforms (should
3468 * Perl ever run on one) where U8_MAX is above 255 because of lots
3469 * of other assumptions */
3470 /* Don't join if the sum can't fit into a single node */
3471 if (oldl + STR_LEN(n) > U8_MAX)
3474 DEBUG_PEEP("merg",n,depth);
3477 NEXT_OFF(scan) += NEXT_OFF(n);
3478 STR_LEN(scan) += STR_LEN(n);
3479 next = n + NODE_SZ_STR(n);
3480 /* Now we can overwrite *n : */
3481 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3489 #ifdef EXPERIMENTAL_INPLACESCAN
3490 if (flags && !NEXT_OFF(n)) {
3491 DEBUG_PEEP("atch", val, depth);
3492 if (reg_off_by_arg[OP(n)]) {
3493 ARG_SET(n, val - n);
3496 NEXT_OFF(n) = val - n;
3504 *unfolded_multi_char = FALSE;
3506 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
3507 * can now analyze for sequences of problematic code points. (Prior to
3508 * this final joining, sequences could have been split over boundaries, and
3509 * hence missed). The sequences only happen in folding, hence for any
3510 * non-EXACT EXACTish node */
3511 if (OP(scan) != EXACT && OP(scan) != EXACTL) {
3512 U8* s0 = (U8*) STRING(scan);
3514 U8* s_end = s0 + STR_LEN(scan);
3516 int total_count_delta = 0; /* Total delta number of characters that
3517 multi-char folds expand to */
3519 /* One pass is made over the node's string looking for all the
3520 * possibilities. To avoid some tests in the loop, there are two main
3521 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
3526 if (OP(scan) == EXACTFL) {
3529 /* An EXACTFL node would already have been changed to another
3530 * node type unless there is at least one character in it that
3531 * is problematic; likely a character whose fold definition
3532 * won't be known until runtime, and so has yet to be folded.
3533 * For all but the UTF-8 locale, folds are 1-1 in length, but
3534 * to handle the UTF-8 case, we need to create a temporary
3535 * folded copy using UTF-8 locale rules in order to analyze it.
3536 * This is because our macros that look to see if a sequence is
3537 * a multi-char fold assume everything is folded (otherwise the
3538 * tests in those macros would be too complicated and slow).
3539 * Note that here, the non-problematic folds will have already
3540 * been done, so we can just copy such characters. We actually
3541 * don't completely fold the EXACTFL string. We skip the
3542 * unfolded multi-char folds, as that would just create work
3543 * below to figure out the size they already are */
3545 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
3548 STRLEN s_len = UTF8SKIP(s);
3549 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
3550 Copy(s, d, s_len, U8);
3553 else if (is_FOLDS_TO_MULTI_utf8(s)) {
3554 *unfolded_multi_char = TRUE;
3555 Copy(s, d, s_len, U8);
3558 else if (isASCII(*s)) {
3559 *(d++) = toFOLD(*s);
3563 _to_utf8_fold_flags(s, d, &len, FOLD_FLAGS_FULL);
3569 /* Point the remainder of the routine to look at our temporary
3573 } /* End of creating folded copy of EXACTFL string */
3575 /* Examine the string for a multi-character fold sequence. UTF-8
3576 * patterns have all characters pre-folded by the time this code is
3578 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
3579 length sequence we are looking for is 2 */
3581 int count = 0; /* How many characters in a multi-char fold */
3582 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
3583 if (! len) { /* Not a multi-char fold: get next char */
3588 /* Nodes with 'ss' require special handling, except for
3589 * EXACTFA-ish for which there is no multi-char fold to this */
3590 if (len == 2 && *s == 's' && *(s+1) == 's'
3591 && OP(scan) != EXACTFA
3592 && OP(scan) != EXACTFA_NO_TRIE)
3595 if (OP(scan) != EXACTFL) {
3596 OP(scan) = EXACTFU_SS;
3600 else { /* Here is a generic multi-char fold. */
3601 U8* multi_end = s + len;
3603 /* Count how many characters are in it. In the case of
3604 * /aa, no folds which contain ASCII code points are
3605 * allowed, so check for those, and skip if found. */
3606 if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
3607 count = utf8_length(s, multi_end);
3611 while (s < multi_end) {
3614 goto next_iteration;
3624 /* The delta is how long the sequence is minus 1 (1 is how long
3625 * the character that folds to the sequence is) */
3626 total_count_delta += count - 1;
3630 /* We created a temporary folded copy of the string in EXACTFL
3631 * nodes. Therefore we need to be sure it doesn't go below zero,
3632 * as the real string could be shorter */
3633 if (OP(scan) == EXACTFL) {
3634 int total_chars = utf8_length((U8*) STRING(scan),
3635 (U8*) STRING(scan) + STR_LEN(scan));
3636 if (total_count_delta > total_chars) {
3637 total_count_delta = total_chars;
3641 *min_subtract += total_count_delta;
3644 else if (OP(scan) == EXACTFA) {
3646 /* Non-UTF-8 pattern, EXACTFA node. There can't be a multi-char
3647 * fold to the ASCII range (and there are no existing ones in the
3648 * upper latin1 range). But, as outlined in the comments preceding
3649 * this function, we need to flag any occurrences of the sharp s.
3650 * This character forbids trie formation (because of added
3653 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
3654 OP(scan) = EXACTFA_NO_TRIE;
3655 *unfolded_multi_char = TRUE;
3664 /* Non-UTF-8 pattern, not EXACTFA node. Look for the multi-char
3665 * folds that are all Latin1. As explained in the comments
3666 * preceding this function, we look also for the sharp s in EXACTF
3667 * and EXACTFL nodes; it can be in the final position. Otherwise
3668 * we can stop looking 1 byte earlier because have to find at least
3669 * two characters for a multi-fold */
3670 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
3675 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
3676 if (! len) { /* Not a multi-char fold. */
3677 if (*s == LATIN_SMALL_LETTER_SHARP_S
3678 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
3680 *unfolded_multi_char = TRUE;
3687 && isALPHA_FOLD_EQ(*s, 's')
3688 && isALPHA_FOLD_EQ(*(s+1), 's'))
3691 /* EXACTF nodes need to know that the minimum length
3692 * changed so that a sharp s in the string can match this
3693 * ss in the pattern, but they remain EXACTF nodes, as they
3694 * won't match this unless the target string is is UTF-8,
3695 * which we don't know until runtime. EXACTFL nodes can't
3696 * transform into EXACTFU nodes */
3697 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
3698 OP(scan) = EXACTFU_SS;
3702 *min_subtract += len - 1;
3709 /* Allow dumping but overwriting the collection of skipped
3710 * ops and/or strings with fake optimized ops */
3711 n = scan + NODE_SZ_STR(scan);
3719 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
3723 /* REx optimizer. Converts nodes into quicker variants "in place".
3724 Finds fixed substrings. */
3726 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
3727 to the position after last scanned or to NULL. */
3729 #define INIT_AND_WITHP \
3730 assert(!and_withp); \
3731 Newx(and_withp,1, regnode_ssc); \
3732 SAVEFREEPV(and_withp)
3736 S_unwind_scan_frames(pTHX_ const void *p)
3738 scan_frame *f= (scan_frame *)p;
3740 scan_frame *n= f->next_frame;
3748 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
3749 SSize_t *minlenp, SSize_t *deltap,
3754 regnode_ssc *and_withp,
3755 U32 flags, U32 depth)
3756 /* scanp: Start here (read-write). */
3757 /* deltap: Write maxlen-minlen here. */
3758 /* last: Stop before this one. */
3759 /* data: string data about the pattern */
3760 /* stopparen: treat close N as END */
3761 /* recursed: which subroutines have we recursed into */
3762 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
3764 /* There must be at least this number of characters to match */
3767 regnode *scan = *scanp, *next;
3769 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
3770 int is_inf_internal = 0; /* The studied chunk is infinite */
3771 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
3772 scan_data_t data_fake;
3773 SV *re_trie_maxbuff = NULL;
3774 regnode *first_non_open = scan;
3775 SSize_t stopmin = SSize_t_MAX;
3776 scan_frame *frame = NULL;
3777 GET_RE_DEBUG_FLAGS_DECL;
3779 PERL_ARGS_ASSERT_STUDY_CHUNK;
3783 while (first_non_open && OP(first_non_open) == OPEN)
3784 first_non_open=regnext(first_non_open);
3790 RExC_study_chunk_recursed_count++;
3792 DEBUG_OPTIMISE_MORE_r(
3794 PerlIO_printf(Perl_debug_log,
3795 "%*sstudy_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
3796 (int)(depth*2), "", (long)stopparen,
3797 (unsigned long)RExC_study_chunk_recursed_count,
3798 (unsigned long)depth, (unsigned long)recursed_depth,
3801 if (recursed_depth) {
3804 for ( j = 0 ; j < recursed_depth ; j++ ) {
3805 for ( i = 0 ; i < (U32)RExC_npar ; i++ ) {
3807 PAREN_TEST(RExC_study_chunk_recursed +
3808 ( j * RExC_study_chunk_recursed_bytes), i )
3811 !PAREN_TEST(RExC_study_chunk_recursed +
3812 (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
3815 PerlIO_printf(Perl_debug_log," %d",(int)i);
3819 if ( j + 1 < recursed_depth ) {
3820 PerlIO_printf(Perl_debug_log, ",");
3824 PerlIO_printf(Perl_debug_log,"\n");
3827 while ( scan && OP(scan) != END && scan < last ){
3828 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
3829 node length to get a real minimum (because
3830 the folded version may be shorter) */
3831 bool unfolded_multi_char = FALSE;
3832 /* Peephole optimizer: */
3833 DEBUG_STUDYDATA("Peep:", data, depth);
3834 DEBUG_PEEP("Peep", scan, depth);
3837 /* The reason we do this here we need to deal with things like /(?:f)(?:o)(?:o)/
3838 * which cant be dealt with by the normal EXACT parsing code, as each (?:..) is handled
3839 * by a different invocation of reg() -- Yves
3841 JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
3843 /* Follow the next-chain of the current node and optimize
3844 away all the NOTHINGs from it. */
3845 if (OP(scan) != CURLYX) {
3846 const int max = (reg_off_by_arg[OP(scan)]
3848 /* I32 may be smaller than U16 on CRAYs! */
3849 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
3850 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
3854 /* Skip NOTHING and LONGJMP. */
3855 while ((n = regnext(n))
3856 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
3857 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
3858 && off + noff < max)
3860 if (reg_off_by_arg[OP(scan)])
3863 NEXT_OFF(scan) = off;
3866 /* The principal pseudo-switch. Cannot be a switch, since we
3867 look into several different things. */
3868 if ( OP(scan) == DEFINEP ) {
3870 SSize_t deltanext = 0;
3871 SSize_t fake_last_close = 0;
3872 I32 f = SCF_IN_DEFINE;
3874 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
3875 scan = regnext(scan);
3876 assert( OP(scan) == IFTHEN );
3877 DEBUG_PEEP("expect IFTHEN", scan, depth);
3879 data_fake.last_closep= &fake_last_close;
3881 next = regnext(scan);
3882 scan = NEXTOPER(NEXTOPER(scan));
3883 DEBUG_PEEP("scan", scan, depth);
3884 DEBUG_PEEP("next", next, depth);
3886 /* we suppose the run is continuous, last=next...
3887 * NOTE we dont use the return here! */
3888 (void)study_chunk(pRExC_state, &scan, &minlen,
3889 &deltanext, next, &data_fake, stopparen,
3890 recursed_depth, NULL, f, depth+1);
3895 OP(scan) == BRANCH ||
3896 OP(scan) == BRANCHJ ||
3899 next = regnext(scan);
3902 /* The op(next)==code check below is to see if we
3903 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
3904 * IFTHEN is special as it might not appear in pairs.
3905 * Not sure whether BRANCH-BRANCHJ is possible, regardless
3906 * we dont handle it cleanly. */
3907 if (OP(next) == code || code == IFTHEN) {
3908 /* NOTE - There is similar code to this block below for
3909 * handling TRIE nodes on a re-study. If you change stuff here
3910 * check there too. */
3911 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
3913 regnode * const startbranch=scan;
3915 if (flags & SCF_DO_SUBSTR) {
3916 /* Cannot merge strings after this. */
3917 scan_commit(pRExC_state, data, minlenp, is_inf);
3920 if (flags & SCF_DO_STCLASS)
3921 ssc_init_zero(pRExC_state, &accum);
3923 while (OP(scan) == code) {
3924 SSize_t deltanext, minnext, fake;
3926 regnode_ssc this_class;
3928 DEBUG_PEEP("Branch", scan, depth);
3931 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
3933 data_fake.whilem_c = data->whilem_c;
3934 data_fake.last_closep = data->last_closep;
3937 data_fake.last_closep = &fake;
3939 data_fake.pos_delta = delta;
3940 next = regnext(scan);
3942 scan = NEXTOPER(scan); /* everything */
3943 if (code != BRANCH) /* everything but BRANCH */
3944 scan = NEXTOPER(scan);
3946 if (flags & SCF_DO_STCLASS) {
3947 ssc_init(pRExC_state, &this_class);
3948 data_fake.start_class = &this_class;
3949 f = SCF_DO_STCLASS_AND;
3951 if (flags & SCF_WHILEM_VISITED_POS)
3952 f |= SCF_WHILEM_VISITED_POS;
3954 /* we suppose the run is continuous, last=next...*/
3955 minnext = study_chunk(pRExC_state, &scan, minlenp,
3956 &deltanext, next, &data_fake, stopparen,
3957 recursed_depth, NULL, f,depth+1);