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
88 #include "dquote_static.c"
95 # if defined(BUGGY_MSC6)
96 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
97 # pragma optimize("a",off)
98 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
99 # pragma optimize("w",on )
100 # endif /* BUGGY_MSC6 */
104 #define STATIC static
107 typedef struct RExC_state_t {
108 U32 flags; /* are we folding, multilining? */
109 char *precomp; /* uncompiled string. */
110 REGEXP *rx_sv; /* The SV that is the regexp. */
111 regexp *rx; /* perl core regexp structure */
112 regexp_internal *rxi; /* internal data for regexp object pprivate field */
113 char *start; /* Start of input for compile */
114 char *end; /* End of input for compile */
115 char *parse; /* Input-scan pointer. */
116 I32 whilem_seen; /* number of WHILEM in this expr */
117 regnode *emit_start; /* Start of emitted-code area */
118 regnode *emit_bound; /* First regnode outside of the allocated space */
119 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
120 I32 naughty; /* How bad is this pattern? */
121 I32 sawback; /* Did we see \1, ...? */
123 I32 size; /* Code size. */
124 I32 npar; /* Capture buffer count, (OPEN). */
125 I32 cpar; /* Capture buffer count, (CLOSE). */
126 I32 nestroot; /* root parens we are in - used by accept */
130 regnode **open_parens; /* pointers to open parens */
131 regnode **close_parens; /* pointers to close parens */
132 regnode *opend; /* END node in program */
133 I32 utf8; /* whether the pattern is utf8 or not */
134 I32 orig_utf8; /* whether the pattern was originally in utf8 */
135 /* XXX use this for future optimisation of case
136 * where pattern must be upgraded to utf8. */
137 HV *paren_names; /* Paren names */
139 regnode **recurse; /* Recurse regops */
140 I32 recurse_count; /* Number of recurse regops */
143 char *starttry; /* -Dr: where regtry was called. */
144 #define RExC_starttry (pRExC_state->starttry)
147 const char *lastparse;
149 AV *paren_name_list; /* idx -> name */
150 #define RExC_lastparse (pRExC_state->lastparse)
151 #define RExC_lastnum (pRExC_state->lastnum)
152 #define RExC_paren_name_list (pRExC_state->paren_name_list)
156 #define RExC_flags (pRExC_state->flags)
157 #define RExC_precomp (pRExC_state->precomp)
158 #define RExC_rx_sv (pRExC_state->rx_sv)
159 #define RExC_rx (pRExC_state->rx)
160 #define RExC_rxi (pRExC_state->rxi)
161 #define RExC_start (pRExC_state->start)
162 #define RExC_end (pRExC_state->end)
163 #define RExC_parse (pRExC_state->parse)
164 #define RExC_whilem_seen (pRExC_state->whilem_seen)
165 #ifdef RE_TRACK_PATTERN_OFFSETS
166 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
168 #define RExC_emit (pRExC_state->emit)
169 #define RExC_emit_start (pRExC_state->emit_start)
170 #define RExC_emit_bound (pRExC_state->emit_bound)
171 #define RExC_naughty (pRExC_state->naughty)
172 #define RExC_sawback (pRExC_state->sawback)
173 #define RExC_seen (pRExC_state->seen)
174 #define RExC_size (pRExC_state->size)
175 #define RExC_npar (pRExC_state->npar)
176 #define RExC_nestroot (pRExC_state->nestroot)
177 #define RExC_extralen (pRExC_state->extralen)
178 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
179 #define RExC_seen_evals (pRExC_state->seen_evals)
180 #define RExC_utf8 (pRExC_state->utf8)
181 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
182 #define RExC_open_parens (pRExC_state->open_parens)
183 #define RExC_close_parens (pRExC_state->close_parens)
184 #define RExC_opend (pRExC_state->opend)
185 #define RExC_paren_names (pRExC_state->paren_names)
186 #define RExC_recurse (pRExC_state->recurse)
187 #define RExC_recurse_count (pRExC_state->recurse_count)
188 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
191 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
192 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
193 ((*s) == '{' && regcurly(s)))
196 #undef SPSTART /* dratted cpp namespace... */
199 * Flags to be passed up and down.
201 #define WORST 0 /* Worst case. */
202 #define HASWIDTH 0x01 /* Known to match non-null strings. */
204 /* Simple enough to be STAR/PLUS operand, in an EXACT node must be a single
205 * character, and if utf8, must be invariant. Note that this is not the same thing as REGNODE_SIMPLE */
207 #define SPSTART 0x04 /* Starts with * or +. */
208 #define TRYAGAIN 0x08 /* Weeded out a declaration. */
209 #define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
211 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
213 /* whether trie related optimizations are enabled */
214 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
215 #define TRIE_STUDY_OPT
216 #define FULL_TRIE_STUDY
222 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
223 #define PBITVAL(paren) (1 << ((paren) & 7))
224 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
225 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
226 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
228 /* If not already in utf8, do a longjmp back to the beginning */
229 #define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
230 #define REQUIRE_UTF8 STMT_START { \
231 if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
234 /* About scan_data_t.
236 During optimisation we recurse through the regexp program performing
237 various inplace (keyhole style) optimisations. In addition study_chunk
238 and scan_commit populate this data structure with information about
239 what strings MUST appear in the pattern. We look for the longest
240 string that must appear at a fixed location, and we look for the
241 longest string that may appear at a floating location. So for instance
246 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
247 strings (because they follow a .* construct). study_chunk will identify
248 both FOO and BAR as being the longest fixed and floating strings respectively.
250 The strings can be composites, for instance
254 will result in a composite fixed substring 'foo'.
256 For each string some basic information is maintained:
258 - offset or min_offset
259 This is the position the string must appear at, or not before.
260 It also implicitly (when combined with minlenp) tells us how many
261 characters must match before the string we are searching for.
262 Likewise when combined with minlenp and the length of the string it
263 tells us how many characters must appear after the string we have
267 Only used for floating strings. This is the rightmost point that
268 the string can appear at. If set to I32 max it indicates that the
269 string can occur infinitely far to the right.
272 A pointer to the minimum length of the pattern that the string
273 was found inside. This is important as in the case of positive
274 lookahead or positive lookbehind we can have multiple patterns
279 The minimum length of the pattern overall is 3, the minimum length
280 of the lookahead part is 3, but the minimum length of the part that
281 will actually match is 1. So 'FOO's minimum length is 3, but the
282 minimum length for the F is 1. This is important as the minimum length
283 is used to determine offsets in front of and behind the string being
284 looked for. Since strings can be composites this is the length of the
285 pattern at the time it was committed with a scan_commit. Note that
286 the length is calculated by study_chunk, so that the minimum lengths
287 are not known until the full pattern has been compiled, thus the
288 pointer to the value.
292 In the case of lookbehind the string being searched for can be
293 offset past the start point of the final matching string.
294 If this value was just blithely removed from the min_offset it would
295 invalidate some of the calculations for how many chars must match
296 before or after (as they are derived from min_offset and minlen and
297 the length of the string being searched for).
298 When the final pattern is compiled and the data is moved from the
299 scan_data_t structure into the regexp structure the information
300 about lookbehind is factored in, with the information that would
301 have been lost precalculated in the end_shift field for the
304 The fields pos_min and pos_delta are used to store the minimum offset
305 and the delta to the maximum offset at the current point in the pattern.
309 typedef struct scan_data_t {
310 /*I32 len_min; unused */
311 /*I32 len_delta; unused */
315 I32 last_end; /* min value, <0 unless valid. */
318 SV **longest; /* Either &l_fixed, or &l_float. */
319 SV *longest_fixed; /* longest fixed string found in pattern */
320 I32 offset_fixed; /* offset where it starts */
321 I32 *minlen_fixed; /* pointer to the minlen relevant to the string */
322 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
323 SV *longest_float; /* longest floating string found in pattern */
324 I32 offset_float_min; /* earliest point in string it can appear */
325 I32 offset_float_max; /* latest point in string it can appear */
326 I32 *minlen_float; /* pointer to the minlen relevant to the string */
327 I32 lookbehind_float; /* is the position of the string modified by LB */
331 struct regnode_charclass_class *start_class;
335 * Forward declarations for pregcomp()'s friends.
338 static const scan_data_t zero_scan_data =
339 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
341 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
342 #define SF_BEFORE_SEOL 0x0001
343 #define SF_BEFORE_MEOL 0x0002
344 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
345 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
348 # define SF_FIX_SHIFT_EOL (0+2)
349 # define SF_FL_SHIFT_EOL (0+4)
351 # define SF_FIX_SHIFT_EOL (+2)
352 # define SF_FL_SHIFT_EOL (+4)
355 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
356 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
358 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
359 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
360 #define SF_IS_INF 0x0040
361 #define SF_HAS_PAR 0x0080
362 #define SF_IN_PAR 0x0100
363 #define SF_HAS_EVAL 0x0200
364 #define SCF_DO_SUBSTR 0x0400
365 #define SCF_DO_STCLASS_AND 0x0800
366 #define SCF_DO_STCLASS_OR 0x1000
367 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
368 #define SCF_WHILEM_VISITED_POS 0x2000
370 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
371 #define SCF_SEEN_ACCEPT 0x8000
373 #define UTF cBOOL(RExC_utf8)
374 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
375 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
376 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
377 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
378 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
380 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
382 #define OOB_UNICODE 12345678
383 #define OOB_NAMEDCLASS -1
385 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
386 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
389 /* length of regex to show in messages that don't mark a position within */
390 #define RegexLengthToShowInErrorMessages 127
393 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
394 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
395 * op/pragma/warn/regcomp.
397 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
398 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
400 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
403 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
404 * arg. Show regex, up to a maximum length. If it's too long, chop and add
407 #define _FAIL(code) STMT_START { \
408 const char *ellipses = ""; \
409 IV len = RExC_end - RExC_precomp; \
412 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
413 if (len > RegexLengthToShowInErrorMessages) { \
414 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
415 len = RegexLengthToShowInErrorMessages - 10; \
421 #define FAIL(msg) _FAIL( \
422 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
423 msg, (int)len, RExC_precomp, ellipses))
425 #define FAIL2(msg,arg) _FAIL( \
426 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
427 arg, (int)len, RExC_precomp, ellipses))
430 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
432 #define Simple_vFAIL(m) STMT_START { \
433 const IV offset = RExC_parse - RExC_precomp; \
434 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
435 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
439 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
441 #define vFAIL(m) STMT_START { \
443 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
448 * Like Simple_vFAIL(), but accepts two arguments.
450 #define Simple_vFAIL2(m,a1) STMT_START { \
451 const IV offset = RExC_parse - RExC_precomp; \
452 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
453 (int)offset, RExC_precomp, RExC_precomp + offset); \
457 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
459 #define vFAIL2(m,a1) STMT_START { \
461 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
462 Simple_vFAIL2(m, a1); \
467 * Like Simple_vFAIL(), but accepts three arguments.
469 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
470 const IV offset = RExC_parse - RExC_precomp; \
471 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
472 (int)offset, RExC_precomp, RExC_precomp + offset); \
476 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
478 #define vFAIL3(m,a1,a2) STMT_START { \
480 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
481 Simple_vFAIL3(m, a1, a2); \
485 * Like Simple_vFAIL(), but accepts four arguments.
487 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
488 const IV offset = RExC_parse - RExC_precomp; \
489 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
490 (int)offset, RExC_precomp, RExC_precomp + offset); \
493 #define ckWARNreg(loc,m) STMT_START { \
494 const IV offset = loc - RExC_precomp; \
495 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
496 (int)offset, RExC_precomp, RExC_precomp + offset); \
499 #define ckWARNregdep(loc,m) STMT_START { \
500 const IV offset = loc - RExC_precomp; \
501 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
503 (int)offset, RExC_precomp, RExC_precomp + offset); \
506 #define ckWARN2reg(loc, m, a1) STMT_START { \
507 const IV offset = loc - RExC_precomp; \
508 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
509 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
512 #define vWARN3(loc, m, a1, a2) STMT_START { \
513 const IV offset = loc - RExC_precomp; \
514 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
515 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
518 #define ckWARN3reg(loc, m, a1, a2) STMT_START { \
519 const IV offset = loc - RExC_precomp; \
520 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
521 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
524 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
525 const IV offset = loc - RExC_precomp; \
526 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
527 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
530 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
531 const IV offset = loc - RExC_precomp; \
532 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
533 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
536 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
537 const IV offset = loc - RExC_precomp; \
538 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
539 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
543 /* Allow for side effects in s */
544 #define REGC(c,s) STMT_START { \
545 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
548 /* Macros for recording node offsets. 20001227 mjd@plover.com
549 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
550 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
551 * Element 0 holds the number n.
552 * Position is 1 indexed.
554 #ifndef RE_TRACK_PATTERN_OFFSETS
555 #define Set_Node_Offset_To_R(node,byte)
556 #define Set_Node_Offset(node,byte)
557 #define Set_Cur_Node_Offset
558 #define Set_Node_Length_To_R(node,len)
559 #define Set_Node_Length(node,len)
560 #define Set_Node_Cur_Length(node)
561 #define Node_Offset(n)
562 #define Node_Length(n)
563 #define Set_Node_Offset_Length(node,offset,len)
564 #define ProgLen(ri) ri->u.proglen
565 #define SetProgLen(ri,x) ri->u.proglen = x
567 #define ProgLen(ri) ri->u.offsets[0]
568 #define SetProgLen(ri,x) ri->u.offsets[0] = x
569 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
571 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
572 __LINE__, (int)(node), (int)(byte))); \
574 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
576 RExC_offsets[2*(node)-1] = (byte); \
581 #define Set_Node_Offset(node,byte) \
582 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
583 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
585 #define Set_Node_Length_To_R(node,len) STMT_START { \
587 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
588 __LINE__, (int)(node), (int)(len))); \
590 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
592 RExC_offsets[2*(node)] = (len); \
597 #define Set_Node_Length(node,len) \
598 Set_Node_Length_To_R((node)-RExC_emit_start, len)
599 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
600 #define Set_Node_Cur_Length(node) \
601 Set_Node_Length(node, RExC_parse - parse_start)
603 /* Get offsets and lengths */
604 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
605 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
607 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
608 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
609 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
613 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
614 #define EXPERIMENTAL_INPLACESCAN
615 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
617 #define DEBUG_STUDYDATA(str,data,depth) \
618 DEBUG_OPTIMISE_MORE_r(if(data){ \
619 PerlIO_printf(Perl_debug_log, \
620 "%*s" str "Pos:%"IVdf"/%"IVdf \
621 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
622 (int)(depth)*2, "", \
623 (IV)((data)->pos_min), \
624 (IV)((data)->pos_delta), \
625 (UV)((data)->flags), \
626 (IV)((data)->whilem_c), \
627 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
628 is_inf ? "INF " : "" \
630 if ((data)->last_found) \
631 PerlIO_printf(Perl_debug_log, \
632 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
633 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
634 SvPVX_const((data)->last_found), \
635 (IV)((data)->last_end), \
636 (IV)((data)->last_start_min), \
637 (IV)((data)->last_start_max), \
638 ((data)->longest && \
639 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
640 SvPVX_const((data)->longest_fixed), \
641 (IV)((data)->offset_fixed), \
642 ((data)->longest && \
643 (data)->longest==&((data)->longest_float)) ? "*" : "", \
644 SvPVX_const((data)->longest_float), \
645 (IV)((data)->offset_float_min), \
646 (IV)((data)->offset_float_max) \
648 PerlIO_printf(Perl_debug_log,"\n"); \
651 static void clear_re(pTHX_ void *r);
653 /* Mark that we cannot extend a found fixed substring at this point.
654 Update the longest found anchored substring and the longest found
655 floating substrings if needed. */
658 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
660 const STRLEN l = CHR_SVLEN(data->last_found);
661 const STRLEN old_l = CHR_SVLEN(*data->longest);
662 GET_RE_DEBUG_FLAGS_DECL;
664 PERL_ARGS_ASSERT_SCAN_COMMIT;
666 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
667 SvSetMagicSV(*data->longest, data->last_found);
668 if (*data->longest == data->longest_fixed) {
669 data->offset_fixed = l ? data->last_start_min : data->pos_min;
670 if (data->flags & SF_BEFORE_EOL)
672 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
674 data->flags &= ~SF_FIX_BEFORE_EOL;
675 data->minlen_fixed=minlenp;
676 data->lookbehind_fixed=0;
678 else { /* *data->longest == data->longest_float */
679 data->offset_float_min = l ? data->last_start_min : data->pos_min;
680 data->offset_float_max = (l
681 ? data->last_start_max
682 : data->pos_min + data->pos_delta);
683 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
684 data->offset_float_max = I32_MAX;
685 if (data->flags & SF_BEFORE_EOL)
687 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
689 data->flags &= ~SF_FL_BEFORE_EOL;
690 data->minlen_float=minlenp;
691 data->lookbehind_float=0;
694 SvCUR_set(data->last_found, 0);
696 SV * const sv = data->last_found;
697 if (SvUTF8(sv) && SvMAGICAL(sv)) {
698 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
704 data->flags &= ~SF_BEFORE_EOL;
705 DEBUG_STUDYDATA("commit: ",data,0);
708 /* Can match anything (initialization) */
710 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
712 PERL_ARGS_ASSERT_CL_ANYTHING;
714 ANYOF_CLASS_ZERO(cl);
715 ANYOF_BITMAP_SETALL(cl);
716 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL|ANYOF_LOC_NONBITMAP_FOLD|ANYOF_NON_UTF8_LATIN1_ALL;
718 cl->flags |= ANYOF_LOCALE;
721 /* Can match anything (initialization) */
723 S_cl_is_anything(const struct regnode_charclass_class *cl)
727 PERL_ARGS_ASSERT_CL_IS_ANYTHING;
729 for (value = 0; value <= ANYOF_MAX; value += 2)
730 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
732 if (!(cl->flags & ANYOF_UNICODE_ALL))
734 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
739 /* Can match anything (initialization) */
741 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
743 PERL_ARGS_ASSERT_CL_INIT;
745 Zero(cl, 1, struct regnode_charclass_class);
747 cl_anything(pRExC_state, cl);
751 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
753 PERL_ARGS_ASSERT_CL_INIT_ZERO;
755 Zero(cl, 1, struct regnode_charclass_class);
757 cl_anything(pRExC_state, cl);
759 cl->flags |= ANYOF_LOCALE;
762 /* 'And' a given class with another one. Can create false positives */
763 /* We assume that cl is not inverted */
765 S_cl_and(struct regnode_charclass_class *cl,
766 const struct regnode_charclass_class *and_with)
768 PERL_ARGS_ASSERT_CL_AND;
770 assert(and_with->type == ANYOF);
772 if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
773 && !(ANYOF_CLASS_TEST_ANY_SET(cl))
774 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
775 && !(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
776 && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) {
779 if (and_with->flags & ANYOF_INVERT)
780 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
781 cl->bitmap[i] &= ~and_with->bitmap[i];
783 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
784 cl->bitmap[i] &= and_with->bitmap[i];
785 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
786 if (!(and_with->flags & ANYOF_EOS))
787 cl->flags &= ~ANYOF_EOS;
789 if (!(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD))
790 cl->flags &= ~ANYOF_LOC_NONBITMAP_FOLD;
791 if (!(and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL))
792 cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
794 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_NONBITMAP &&
795 !(and_with->flags & ANYOF_INVERT)) {
796 cl->flags &= ~ANYOF_UNICODE_ALL;
797 cl->flags |= and_with->flags & ANYOF_NONBITMAP; /* field is 2 bits; use
800 ARG_SET(cl, ARG(and_with));
802 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
803 !(and_with->flags & ANYOF_INVERT))
804 cl->flags &= ~ANYOF_UNICODE_ALL;
805 if (!(and_with->flags & (ANYOF_NONBITMAP|ANYOF_UNICODE_ALL)) &&
806 !(and_with->flags & ANYOF_INVERT))
807 cl->flags &= ~ANYOF_NONBITMAP;
810 /* 'OR' a given class with another one. Can create false positives */
811 /* We assume that cl is not inverted */
813 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
815 PERL_ARGS_ASSERT_CL_OR;
817 if (or_with->flags & ANYOF_INVERT) {
819 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
820 * <= (B1 | !B2) | (CL1 | !CL2)
821 * which is wasteful if CL2 is small, but we ignore CL2:
822 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
823 * XXXX Can we handle case-fold? Unclear:
824 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
825 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
827 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
828 && !(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
829 && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD) ) {
832 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
833 cl->bitmap[i] |= ~or_with->bitmap[i];
834 } /* XXXX: logic is complicated otherwise */
836 cl_anything(pRExC_state, cl);
839 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
840 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
841 && (!(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
842 || (cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) ) {
845 /* OR char bitmap and class bitmap separately */
846 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
847 cl->bitmap[i] |= or_with->bitmap[i];
848 if (ANYOF_CLASS_TEST_ANY_SET(or_with)) {
849 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
850 cl->classflags[i] |= or_with->classflags[i];
851 cl->flags |= ANYOF_CLASS;
854 else { /* XXXX: logic is complicated, leave it along for a moment. */
855 cl_anything(pRExC_state, cl);
858 if (or_with->flags & ANYOF_EOS)
859 cl->flags |= ANYOF_EOS;
860 if (!(or_with->flags & ANYOF_NON_UTF8_LATIN1_ALL))
861 cl->flags |= ANYOF_NON_UTF8_LATIN1_ALL;
863 if (or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
864 cl->flags |= ANYOF_LOC_NONBITMAP_FOLD;
866 /* If both nodes match something outside the bitmap, but what they match
867 * outside is not the same pointer, and hence not easily compared, give up
868 * and allow the start class to match everything outside the bitmap */
869 if (cl->flags & ANYOF_NONBITMAP && or_with->flags & ANYOF_NONBITMAP &&
870 ARG(cl) != ARG(or_with)) {
871 cl->flags |= ANYOF_UNICODE_ALL;
874 if (or_with->flags & ANYOF_UNICODE_ALL) {
875 cl->flags |= ANYOF_UNICODE_ALL;
879 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
880 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
881 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
882 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
887 dump_trie(trie,widecharmap,revcharmap)
888 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
889 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
891 These routines dump out a trie in a somewhat readable format.
892 The _interim_ variants are used for debugging the interim
893 tables that are used to generate the final compressed
894 representation which is what dump_trie expects.
896 Part of the reason for their existence is to provide a form
897 of documentation as to how the different representations function.
902 Dumps the final compressed table form of the trie to Perl_debug_log.
903 Used for debugging make_trie().
907 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
908 AV *revcharmap, U32 depth)
911 SV *sv=sv_newmortal();
912 int colwidth= widecharmap ? 6 : 4;
914 GET_RE_DEBUG_FLAGS_DECL;
916 PERL_ARGS_ASSERT_DUMP_TRIE;
918 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
919 (int)depth * 2 + 2,"",
920 "Match","Base","Ofs" );
922 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
923 SV ** const tmp = av_fetch( revcharmap, state, 0);
925 PerlIO_printf( Perl_debug_log, "%*s",
927 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
928 PL_colors[0], PL_colors[1],
929 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
930 PERL_PV_ESCAPE_FIRSTCHAR
935 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
936 (int)depth * 2 + 2,"");
938 for( state = 0 ; state < trie->uniquecharcount ; state++ )
939 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
940 PerlIO_printf( Perl_debug_log, "\n");
942 for( state = 1 ; state < trie->statecount ; state++ ) {
943 const U32 base = trie->states[ state ].trans.base;
945 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
947 if ( trie->states[ state ].wordnum ) {
948 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
950 PerlIO_printf( Perl_debug_log, "%6s", "" );
953 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
958 while( ( base + ofs < trie->uniquecharcount ) ||
959 ( base + ofs - trie->uniquecharcount < trie->lasttrans
960 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
963 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
965 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
966 if ( ( base + ofs >= trie->uniquecharcount ) &&
967 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
968 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
970 PerlIO_printf( Perl_debug_log, "%*"UVXf,
972 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
974 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
978 PerlIO_printf( Perl_debug_log, "]");
981 PerlIO_printf( Perl_debug_log, "\n" );
983 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
984 for (word=1; word <= trie->wordcount; word++) {
985 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
986 (int)word, (int)(trie->wordinfo[word].prev),
987 (int)(trie->wordinfo[word].len));
989 PerlIO_printf(Perl_debug_log, "\n" );
992 Dumps a fully constructed but uncompressed trie in list form.
993 List tries normally only are used for construction when the number of
994 possible chars (trie->uniquecharcount) is very high.
995 Used for debugging make_trie().
998 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
999 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1003 SV *sv=sv_newmortal();
1004 int colwidth= widecharmap ? 6 : 4;
1005 GET_RE_DEBUG_FLAGS_DECL;
1007 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1009 /* print out the table precompression. */
1010 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1011 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1012 "------:-----+-----------------\n" );
1014 for( state=1 ; state < next_alloc ; state ++ ) {
1017 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
1018 (int)depth * 2 + 2,"", (UV)state );
1019 if ( ! trie->states[ state ].wordnum ) {
1020 PerlIO_printf( Perl_debug_log, "%5s| ","");
1022 PerlIO_printf( Perl_debug_log, "W%4x| ",
1023 trie->states[ state ].wordnum
1026 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1027 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
1029 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1031 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1032 PL_colors[0], PL_colors[1],
1033 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1034 PERL_PV_ESCAPE_FIRSTCHAR
1036 TRIE_LIST_ITEM(state,charid).forid,
1037 (UV)TRIE_LIST_ITEM(state,charid).newstate
1040 PerlIO_printf(Perl_debug_log, "\n%*s| ",
1041 (int)((depth * 2) + 14), "");
1044 PerlIO_printf( Perl_debug_log, "\n");
1049 Dumps a fully constructed but uncompressed trie in table form.
1050 This is the normal DFA style state transition table, with a few
1051 twists to facilitate compression later.
1052 Used for debugging make_trie().
1055 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1056 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1061 SV *sv=sv_newmortal();
1062 int colwidth= widecharmap ? 6 : 4;
1063 GET_RE_DEBUG_FLAGS_DECL;
1065 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1068 print out the table precompression so that we can do a visual check
1069 that they are identical.
1072 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1074 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1075 SV ** const tmp = av_fetch( revcharmap, charid, 0);
1077 PerlIO_printf( Perl_debug_log, "%*s",
1079 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1080 PL_colors[0], PL_colors[1],
1081 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1082 PERL_PV_ESCAPE_FIRSTCHAR
1088 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1090 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1091 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1094 PerlIO_printf( Perl_debug_log, "\n" );
1096 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1098 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1099 (int)depth * 2 + 2,"",
1100 (UV)TRIE_NODENUM( state ) );
1102 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1103 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1105 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1107 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1109 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1110 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1112 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1113 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1121 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1122 startbranch: the first branch in the whole branch sequence
1123 first : start branch of sequence of branch-exact nodes.
1124 May be the same as startbranch
1125 last : Thing following the last branch.
1126 May be the same as tail.
1127 tail : item following the branch sequence
1128 count : words in the sequence
1129 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1130 depth : indent depth
1132 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1134 A trie is an N'ary tree where the branches are determined by digital
1135 decomposition of the key. IE, at the root node you look up the 1st character and
1136 follow that branch repeat until you find the end of the branches. Nodes can be
1137 marked as "accepting" meaning they represent a complete word. Eg:
1141 would convert into the following structure. Numbers represent states, letters
1142 following numbers represent valid transitions on the letter from that state, if
1143 the number is in square brackets it represents an accepting state, otherwise it
1144 will be in parenthesis.
1146 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1150 (1) +-i->(6)-+-s->[7]
1152 +-s->(3)-+-h->(4)-+-e->[5]
1154 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1156 This shows that when matching against the string 'hers' we will begin at state 1
1157 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1158 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1159 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1160 single traverse. We store a mapping from accepting to state to which word was
1161 matched, and then when we have multiple possibilities we try to complete the
1162 rest of the regex in the order in which they occured in the alternation.
1164 The only prior NFA like behaviour that would be changed by the TRIE support is
1165 the silent ignoring of duplicate alternations which are of the form:
1167 / (DUPE|DUPE) X? (?{ ... }) Y /x
1169 Thus EVAL blocks following a trie may be called a different number of times with
1170 and without the optimisation. With the optimisations dupes will be silently
1171 ignored. This inconsistent behaviour of EVAL type nodes is well established as
1172 the following demonstrates:
1174 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1176 which prints out 'word' three times, but
1178 'words'=~/(word|word|word)(?{ print $1 })S/
1180 which doesnt print it out at all. This is due to other optimisations kicking in.
1182 Example of what happens on a structural level:
1184 The regexp /(ac|ad|ab)+/ will produce the following debug output:
1186 1: CURLYM[1] {1,32767}(18)
1197 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1198 and should turn into:
1200 1: CURLYM[1] {1,32767}(18)
1202 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1210 Cases where tail != last would be like /(?foo|bar)baz/:
1220 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1221 and would end up looking like:
1224 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1231 d = uvuni_to_utf8_flags(d, uv, 0);
1233 is the recommended Unicode-aware way of saying
1238 #define TRIE_STORE_REVCHAR \
1241 SV *zlopp = newSV(2); \
1242 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
1243 unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
1244 SvCUR_set(zlopp, kapow - flrbbbbb); \
1247 av_push(revcharmap, zlopp); \
1249 char ooooff = (char)uvc; \
1250 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
1254 #define TRIE_READ_CHAR STMT_START { \
1258 if ( foldlen > 0 ) { \
1259 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1264 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1265 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1266 foldlen -= UNISKIP( uvc ); \
1267 scan = foldbuf + UNISKIP( uvc ); \
1270 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1280 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1281 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1282 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1283 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1285 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1286 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1287 TRIE_LIST_CUR( state )++; \
1290 #define TRIE_LIST_NEW(state) STMT_START { \
1291 Newxz( trie->states[ state ].trans.list, \
1292 4, reg_trie_trans_le ); \
1293 TRIE_LIST_CUR( state ) = 1; \
1294 TRIE_LIST_LEN( state ) = 4; \
1297 #define TRIE_HANDLE_WORD(state) STMT_START { \
1298 U16 dupe= trie->states[ state ].wordnum; \
1299 regnode * const noper_next = regnext( noper ); \
1302 /* store the word for dumping */ \
1304 if (OP(noper) != NOTHING) \
1305 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
1307 tmp = newSVpvn_utf8( "", 0, UTF ); \
1308 av_push( trie_words, tmp ); \
1312 trie->wordinfo[curword].prev = 0; \
1313 trie->wordinfo[curword].len = wordlen; \
1314 trie->wordinfo[curword].accept = state; \
1316 if ( noper_next < tail ) { \
1318 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1319 trie->jump[curword] = (U16)(noper_next - convert); \
1321 jumper = noper_next; \
1323 nextbranch= regnext(cur); \
1327 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
1328 /* chain, so that when the bits of chain are later */\
1329 /* linked together, the dups appear in the chain */\
1330 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1331 trie->wordinfo[dupe].prev = curword; \
1333 /* we haven't inserted this word yet. */ \
1334 trie->states[ state ].wordnum = curword; \
1339 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1340 ( ( base + charid >= ucharcount \
1341 && base + charid < ubound \
1342 && state == trie->trans[ base - ucharcount + charid ].check \
1343 && trie->trans[ base - ucharcount + charid ].next ) \
1344 ? trie->trans[ base - ucharcount + charid ].next \
1345 : ( state==1 ? special : 0 ) \
1349 #define MADE_JUMP_TRIE 2
1350 #define MADE_EXACT_TRIE 4
1353 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1356 /* first pass, loop through and scan words */
1357 reg_trie_data *trie;
1358 HV *widecharmap = NULL;
1359 AV *revcharmap = newAV();
1361 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1366 regnode *jumper = NULL;
1367 regnode *nextbranch = NULL;
1368 regnode *convert = NULL;
1369 U32 *prev_states; /* temp array mapping each state to previous one */
1370 /* we just use folder as a flag in utf8 */
1371 const U8 * folder = NULL;
1374 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1375 AV *trie_words = NULL;
1376 /* along with revcharmap, this only used during construction but both are
1377 * useful during debugging so we store them in the struct when debugging.
1380 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1381 STRLEN trie_charcount=0;
1383 SV *re_trie_maxbuff;
1384 GET_RE_DEBUG_FLAGS_DECL;
1386 PERL_ARGS_ASSERT_MAKE_TRIE;
1388 PERL_UNUSED_ARG(depth);
1392 case EXACTFU: folder = PL_fold_latin1; break;
1393 case EXACTF: folder = PL_fold; break;
1394 case EXACTFL: folder = PL_fold_locale; break;
1397 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1399 trie->startstate = 1;
1400 trie->wordcount = word_count;
1401 RExC_rxi->data->data[ data_slot ] = (void*)trie;
1402 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1403 if (!(UTF && folder))
1404 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1405 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1406 trie->wordcount+1, sizeof(reg_trie_wordinfo));
1409 trie_words = newAV();
1412 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1413 if (!SvIOK(re_trie_maxbuff)) {
1414 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1417 PerlIO_printf( Perl_debug_log,
1418 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1419 (int)depth * 2 + 2, "",
1420 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1421 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1425 /* Find the node we are going to overwrite */
1426 if ( first == startbranch && OP( last ) != BRANCH ) {
1427 /* whole branch chain */
1430 /* branch sub-chain */
1431 convert = NEXTOPER( first );
1434 /* -- First loop and Setup --
1436 We first traverse the branches and scan each word to determine if it
1437 contains widechars, and how many unique chars there are, this is
1438 important as we have to build a table with at least as many columns as we
1441 We use an array of integers to represent the character codes 0..255
1442 (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1443 native representation of the character value as the key and IV's for the
1446 *TODO* If we keep track of how many times each character is used we can
1447 remap the columns so that the table compression later on is more
1448 efficient in terms of memory by ensuring the most common value is in the
1449 middle and the least common are on the outside. IMO this would be better
1450 than a most to least common mapping as theres a decent chance the most
1451 common letter will share a node with the least common, meaning the node
1452 will not be compressible. With a middle is most common approach the worst
1453 case is when we have the least common nodes twice.
1457 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1458 regnode * const noper = NEXTOPER( cur );
1459 const U8 *uc = (U8*)STRING( noper );
1460 const U8 * const e = uc + STR_LEN( noper );
1462 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1463 const U8 *scan = (U8*)NULL;
1464 U32 wordlen = 0; /* required init */
1466 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1468 if (OP(noper) == NOTHING) {
1472 if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
1473 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1474 regardless of encoding */
1476 for ( ; uc < e ; uc += len ) {
1477 TRIE_CHARCOUNT(trie)++;
1481 if ( !trie->charmap[ uvc ] ) {
1482 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1484 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1488 /* store the codepoint in the bitmap, and its folded
1490 TRIE_BITMAP_SET(trie,uvc);
1492 /* store the folded codepoint */
1493 if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
1496 /* store first byte of utf8 representation of
1497 variant codepoints */
1498 if (! UNI_IS_INVARIANT(uvc)) {
1499 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
1502 set_bit = 0; /* We've done our bit :-) */
1507 widecharmap = newHV();
1509 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1512 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1514 if ( !SvTRUE( *svpp ) ) {
1515 sv_setiv( *svpp, ++trie->uniquecharcount );
1520 if( cur == first ) {
1523 } else if (chars < trie->minlen) {
1525 } else if (chars > trie->maxlen) {
1529 } /* end first pass */
1530 DEBUG_TRIE_COMPILE_r(
1531 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1532 (int)depth * 2 + 2,"",
1533 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1534 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1535 (int)trie->minlen, (int)trie->maxlen )
1539 We now know what we are dealing with in terms of unique chars and
1540 string sizes so we can calculate how much memory a naive
1541 representation using a flat table will take. If it's over a reasonable
1542 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1543 conservative but potentially much slower representation using an array
1546 At the end we convert both representations into the same compressed
1547 form that will be used in regexec.c for matching with. The latter
1548 is a form that cannot be used to construct with but has memory
1549 properties similar to the list form and access properties similar
1550 to the table form making it both suitable for fast searches and
1551 small enough that its feasable to store for the duration of a program.
1553 See the comment in the code where the compressed table is produced
1554 inplace from the flat tabe representation for an explanation of how
1555 the compression works.
1560 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1563 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1565 Second Pass -- Array Of Lists Representation
1567 Each state will be represented by a list of charid:state records
1568 (reg_trie_trans_le) the first such element holds the CUR and LEN
1569 points of the allocated array. (See defines above).
1571 We build the initial structure using the lists, and then convert
1572 it into the compressed table form which allows faster lookups
1573 (but cant be modified once converted).
1576 STRLEN transcount = 1;
1578 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1579 "%*sCompiling trie using list compiler\n",
1580 (int)depth * 2 + 2, ""));
1582 trie->states = (reg_trie_state *)
1583 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1584 sizeof(reg_trie_state) );
1588 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1590 regnode * const noper = NEXTOPER( cur );
1591 U8 *uc = (U8*)STRING( noper );
1592 const U8 * const e = uc + STR_LEN( noper );
1593 U32 state = 1; /* required init */
1594 U16 charid = 0; /* sanity init */
1595 U8 *scan = (U8*)NULL; /* sanity init */
1596 STRLEN foldlen = 0; /* required init */
1597 U32 wordlen = 0; /* required init */
1598 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1600 if (OP(noper) != NOTHING) {
1601 for ( ; uc < e ; uc += len ) {
1606 charid = trie->charmap[ uvc ];
1608 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1612 charid=(U16)SvIV( *svpp );
1615 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1622 if ( !trie->states[ state ].trans.list ) {
1623 TRIE_LIST_NEW( state );
1625 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1626 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1627 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1632 newstate = next_alloc++;
1633 prev_states[newstate] = state;
1634 TRIE_LIST_PUSH( state, charid, newstate );
1639 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1643 TRIE_HANDLE_WORD(state);
1645 } /* end second pass */
1647 /* next alloc is the NEXT state to be allocated */
1648 trie->statecount = next_alloc;
1649 trie->states = (reg_trie_state *)
1650 PerlMemShared_realloc( trie->states,
1652 * sizeof(reg_trie_state) );
1654 /* and now dump it out before we compress it */
1655 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1656 revcharmap, next_alloc,
1660 trie->trans = (reg_trie_trans *)
1661 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1668 for( state=1 ; state < next_alloc ; state ++ ) {
1672 DEBUG_TRIE_COMPILE_MORE_r(
1673 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1677 if (trie->states[state].trans.list) {
1678 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1682 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1683 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1684 if ( forid < minid ) {
1686 } else if ( forid > maxid ) {
1690 if ( transcount < tp + maxid - minid + 1) {
1692 trie->trans = (reg_trie_trans *)
1693 PerlMemShared_realloc( trie->trans,
1695 * sizeof(reg_trie_trans) );
1696 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1698 base = trie->uniquecharcount + tp - minid;
1699 if ( maxid == minid ) {
1701 for ( ; zp < tp ; zp++ ) {
1702 if ( ! trie->trans[ zp ].next ) {
1703 base = trie->uniquecharcount + zp - minid;
1704 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1705 trie->trans[ zp ].check = state;
1711 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1712 trie->trans[ tp ].check = state;
1717 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1718 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1719 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1720 trie->trans[ tid ].check = state;
1722 tp += ( maxid - minid + 1 );
1724 Safefree(trie->states[ state ].trans.list);
1727 DEBUG_TRIE_COMPILE_MORE_r(
1728 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1731 trie->states[ state ].trans.base=base;
1733 trie->lasttrans = tp + 1;
1737 Second Pass -- Flat Table Representation.
1739 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1740 We know that we will need Charcount+1 trans at most to store the data
1741 (one row per char at worst case) So we preallocate both structures
1742 assuming worst case.
1744 We then construct the trie using only the .next slots of the entry
1747 We use the .check field of the first entry of the node temporarily to
1748 make compression both faster and easier by keeping track of how many non
1749 zero fields are in the node.
1751 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1754 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1755 number representing the first entry of the node, and state as a
1756 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1757 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1758 are 2 entrys per node. eg:
1766 The table is internally in the right hand, idx form. However as we also
1767 have to deal with the states array which is indexed by nodenum we have to
1768 use TRIE_NODENUM() to convert.
1771 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1772 "%*sCompiling trie using table compiler\n",
1773 (int)depth * 2 + 2, ""));
1775 trie->trans = (reg_trie_trans *)
1776 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1777 * trie->uniquecharcount + 1,
1778 sizeof(reg_trie_trans) );
1779 trie->states = (reg_trie_state *)
1780 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1781 sizeof(reg_trie_state) );
1782 next_alloc = trie->uniquecharcount + 1;
1785 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1787 regnode * const noper = NEXTOPER( cur );
1788 const U8 *uc = (U8*)STRING( noper );
1789 const U8 * const e = uc + STR_LEN( noper );
1791 U32 state = 1; /* required init */
1793 U16 charid = 0; /* sanity init */
1794 U32 accept_state = 0; /* sanity init */
1795 U8 *scan = (U8*)NULL; /* sanity init */
1797 STRLEN foldlen = 0; /* required init */
1798 U32 wordlen = 0; /* required init */
1799 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1801 if ( OP(noper) != NOTHING ) {
1802 for ( ; uc < e ; uc += len ) {
1807 charid = trie->charmap[ uvc ];
1809 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1810 charid = svpp ? (U16)SvIV(*svpp) : 0;
1814 if ( !trie->trans[ state + charid ].next ) {
1815 trie->trans[ state + charid ].next = next_alloc;
1816 trie->trans[ state ].check++;
1817 prev_states[TRIE_NODENUM(next_alloc)]
1818 = TRIE_NODENUM(state);
1819 next_alloc += trie->uniquecharcount;
1821 state = trie->trans[ state + charid ].next;
1823 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1825 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1828 accept_state = TRIE_NODENUM( state );
1829 TRIE_HANDLE_WORD(accept_state);
1831 } /* end second pass */
1833 /* and now dump it out before we compress it */
1834 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1836 next_alloc, depth+1));
1840 * Inplace compress the table.*
1842 For sparse data sets the table constructed by the trie algorithm will
1843 be mostly 0/FAIL transitions or to put it another way mostly empty.
1844 (Note that leaf nodes will not contain any transitions.)
1846 This algorithm compresses the tables by eliminating most such
1847 transitions, at the cost of a modest bit of extra work during lookup:
1849 - Each states[] entry contains a .base field which indicates the
1850 index in the state[] array wheres its transition data is stored.
1852 - If .base is 0 there are no valid transitions from that node.
1854 - If .base is nonzero then charid is added to it to find an entry in
1857 -If trans[states[state].base+charid].check!=state then the
1858 transition is taken to be a 0/Fail transition. Thus if there are fail
1859 transitions at the front of the node then the .base offset will point
1860 somewhere inside the previous nodes data (or maybe even into a node
1861 even earlier), but the .check field determines if the transition is
1865 The following process inplace converts the table to the compressed
1866 table: We first do not compress the root node 1,and mark all its
1867 .check pointers as 1 and set its .base pointer as 1 as well. This
1868 allows us to do a DFA construction from the compressed table later,
1869 and ensures that any .base pointers we calculate later are greater
1872 - We set 'pos' to indicate the first entry of the second node.
1874 - We then iterate over the columns of the node, finding the first and
1875 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1876 and set the .check pointers accordingly, and advance pos
1877 appropriately and repreat for the next node. Note that when we copy
1878 the next pointers we have to convert them from the original
1879 NODEIDX form to NODENUM form as the former is not valid post
1882 - If a node has no transitions used we mark its base as 0 and do not
1883 advance the pos pointer.
1885 - If a node only has one transition we use a second pointer into the
1886 structure to fill in allocated fail transitions from other states.
1887 This pointer is independent of the main pointer and scans forward
1888 looking for null transitions that are allocated to a state. When it
1889 finds one it writes the single transition into the "hole". If the
1890 pointer doesnt find one the single transition is appended as normal.
1892 - Once compressed we can Renew/realloc the structures to release the
1895 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1896 specifically Fig 3.47 and the associated pseudocode.
1900 const U32 laststate = TRIE_NODENUM( next_alloc );
1903 trie->statecount = laststate;
1905 for ( state = 1 ; state < laststate ; state++ ) {
1907 const U32 stateidx = TRIE_NODEIDX( state );
1908 const U32 o_used = trie->trans[ stateidx ].check;
1909 U32 used = trie->trans[ stateidx ].check;
1910 trie->trans[ stateidx ].check = 0;
1912 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1913 if ( flag || trie->trans[ stateidx + charid ].next ) {
1914 if ( trie->trans[ stateidx + charid ].next ) {
1916 for ( ; zp < pos ; zp++ ) {
1917 if ( ! trie->trans[ zp ].next ) {
1921 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1922 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1923 trie->trans[ zp ].check = state;
1924 if ( ++zp > pos ) pos = zp;
1931 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1933 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1934 trie->trans[ pos ].check = state;
1939 trie->lasttrans = pos + 1;
1940 trie->states = (reg_trie_state *)
1941 PerlMemShared_realloc( trie->states, laststate
1942 * sizeof(reg_trie_state) );
1943 DEBUG_TRIE_COMPILE_MORE_r(
1944 PerlIO_printf( Perl_debug_log,
1945 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1946 (int)depth * 2 + 2,"",
1947 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1950 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1953 } /* end table compress */
1955 DEBUG_TRIE_COMPILE_MORE_r(
1956 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1957 (int)depth * 2 + 2, "",
1958 (UV)trie->statecount,
1959 (UV)trie->lasttrans)
1961 /* resize the trans array to remove unused space */
1962 trie->trans = (reg_trie_trans *)
1963 PerlMemShared_realloc( trie->trans, trie->lasttrans
1964 * sizeof(reg_trie_trans) );
1966 { /* Modify the program and insert the new TRIE node */
1967 U8 nodetype =(U8)(flags & 0xFF);
1971 regnode *optimize = NULL;
1972 #ifdef RE_TRACK_PATTERN_OFFSETS
1975 U32 mjd_nodelen = 0;
1976 #endif /* RE_TRACK_PATTERN_OFFSETS */
1977 #endif /* DEBUGGING */
1979 This means we convert either the first branch or the first Exact,
1980 depending on whether the thing following (in 'last') is a branch
1981 or not and whther first is the startbranch (ie is it a sub part of
1982 the alternation or is it the whole thing.)
1983 Assuming its a sub part we convert the EXACT otherwise we convert
1984 the whole branch sequence, including the first.
1986 /* Find the node we are going to overwrite */
1987 if ( first != startbranch || OP( last ) == BRANCH ) {
1988 /* branch sub-chain */
1989 NEXT_OFF( first ) = (U16)(last - first);
1990 #ifdef RE_TRACK_PATTERN_OFFSETS
1992 mjd_offset= Node_Offset((convert));
1993 mjd_nodelen= Node_Length((convert));
1996 /* whole branch chain */
1998 #ifdef RE_TRACK_PATTERN_OFFSETS
2001 const regnode *nop = NEXTOPER( convert );
2002 mjd_offset= Node_Offset((nop));
2003 mjd_nodelen= Node_Length((nop));
2007 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2008 (int)depth * 2 + 2, "",
2009 (UV)mjd_offset, (UV)mjd_nodelen)
2012 /* But first we check to see if there is a common prefix we can
2013 split out as an EXACT and put in front of the TRIE node. */
2014 trie->startstate= 1;
2015 if ( trie->bitmap && !widecharmap && !trie->jump ) {
2017 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2021 const U32 base = trie->states[ state ].trans.base;
2023 if ( trie->states[state].wordnum )
2026 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2027 if ( ( base + ofs >= trie->uniquecharcount ) &&
2028 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2029 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2031 if ( ++count > 1 ) {
2032 SV **tmp = av_fetch( revcharmap, ofs, 0);
2033 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2034 if ( state == 1 ) break;
2036 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2038 PerlIO_printf(Perl_debug_log,
2039 "%*sNew Start State=%"UVuf" Class: [",
2040 (int)depth * 2 + 2, "",
2043 SV ** const tmp = av_fetch( revcharmap, idx, 0);
2044 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2046 TRIE_BITMAP_SET(trie,*ch);
2048 TRIE_BITMAP_SET(trie, folder[ *ch ]);
2050 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2054 TRIE_BITMAP_SET(trie,*ch);
2056 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2057 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2063 SV **tmp = av_fetch( revcharmap, idx, 0);
2065 char *ch = SvPV( *tmp, len );
2067 SV *sv=sv_newmortal();
2068 PerlIO_printf( Perl_debug_log,
2069 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2070 (int)depth * 2 + 2, "",
2072 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
2073 PL_colors[0], PL_colors[1],
2074 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2075 PERL_PV_ESCAPE_FIRSTCHAR
2080 OP( convert ) = nodetype;
2081 str=STRING(convert);
2084 STR_LEN(convert) += len;
2090 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2095 trie->prefixlen = (state-1);
2097 regnode *n = convert+NODE_SZ_STR(convert);
2098 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2099 trie->startstate = state;
2100 trie->minlen -= (state - 1);
2101 trie->maxlen -= (state - 1);
2103 /* At least the UNICOS C compiler choked on this
2104 * being argument to DEBUG_r(), so let's just have
2107 #ifdef PERL_EXT_RE_BUILD
2113 regnode *fix = convert;
2114 U32 word = trie->wordcount;
2116 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2117 while( ++fix < n ) {
2118 Set_Node_Offset_Length(fix, 0, 0);
2121 SV ** const tmp = av_fetch( trie_words, word, 0 );
2123 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2124 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2126 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2134 NEXT_OFF(convert) = (U16)(tail - convert);
2135 DEBUG_r(optimize= n);
2141 if ( trie->maxlen ) {
2142 NEXT_OFF( convert ) = (U16)(tail - convert);
2143 ARG_SET( convert, data_slot );
2144 /* Store the offset to the first unabsorbed branch in
2145 jump[0], which is otherwise unused by the jump logic.
2146 We use this when dumping a trie and during optimisation. */
2148 trie->jump[0] = (U16)(nextbranch - convert);
2150 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2151 * and there is a bitmap
2152 * and the first "jump target" node we found leaves enough room
2153 * then convert the TRIE node into a TRIEC node, with the bitmap
2154 * embedded inline in the opcode - this is hypothetically faster.
2156 if ( !trie->states[trie->startstate].wordnum
2158 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2160 OP( convert ) = TRIEC;
2161 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2162 PerlMemShared_free(trie->bitmap);
2165 OP( convert ) = TRIE;
2167 /* store the type in the flags */
2168 convert->flags = nodetype;
2172 + regarglen[ OP( convert ) ];
2174 /* XXX We really should free up the resource in trie now,
2175 as we won't use them - (which resources?) dmq */
2177 /* needed for dumping*/
2178 DEBUG_r(if (optimize) {
2179 regnode *opt = convert;
2181 while ( ++opt < optimize) {
2182 Set_Node_Offset_Length(opt,0,0);
2185 Try to clean up some of the debris left after the
2188 while( optimize < jumper ) {
2189 mjd_nodelen += Node_Length((optimize));
2190 OP( optimize ) = OPTIMIZED;
2191 Set_Node_Offset_Length(optimize,0,0);
2194 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2196 } /* end node insert */
2198 /* Finish populating the prev field of the wordinfo array. Walk back
2199 * from each accept state until we find another accept state, and if
2200 * so, point the first word's .prev field at the second word. If the
2201 * second already has a .prev field set, stop now. This will be the
2202 * case either if we've already processed that word's accept state,
2203 * or that state had multiple words, and the overspill words were
2204 * already linked up earlier.
2211 for (word=1; word <= trie->wordcount; word++) {
2213 if (trie->wordinfo[word].prev)
2215 state = trie->wordinfo[word].accept;
2217 state = prev_states[state];
2220 prev = trie->states[state].wordnum;
2224 trie->wordinfo[word].prev = prev;
2226 Safefree(prev_states);
2230 /* and now dump out the compressed format */
2231 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2233 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2235 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2236 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2238 SvREFCNT_dec(revcharmap);
2242 : trie->startstate>1
2248 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2250 /* The Trie is constructed and compressed now so we can build a fail array if it's needed
2252 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2253 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2256 We find the fail state for each state in the trie, this state is the longest proper
2257 suffix of the current state's 'word' that is also a proper prefix of another word in our
2258 trie. State 1 represents the word '' and is thus the default fail state. This allows
2259 the DFA not to have to restart after its tried and failed a word at a given point, it
2260 simply continues as though it had been matching the other word in the first place.
2262 'abcdgu'=~/abcdefg|cdgu/
2263 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2264 fail, which would bring us to the state representing 'd' in the second word where we would
2265 try 'g' and succeed, proceeding to match 'cdgu'.
2267 /* add a fail transition */
2268 const U32 trie_offset = ARG(source);
2269 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2271 const U32 ucharcount = trie->uniquecharcount;
2272 const U32 numstates = trie->statecount;
2273 const U32 ubound = trie->lasttrans + ucharcount;
2277 U32 base = trie->states[ 1 ].trans.base;
2280 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2281 GET_RE_DEBUG_FLAGS_DECL;
2283 PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2285 PERL_UNUSED_ARG(depth);
2289 ARG_SET( stclass, data_slot );
2290 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2291 RExC_rxi->data->data[ data_slot ] = (void*)aho;
2292 aho->trie=trie_offset;
2293 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2294 Copy( trie->states, aho->states, numstates, reg_trie_state );
2295 Newxz( q, numstates, U32);
2296 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2299 /* initialize fail[0..1] to be 1 so that we always have
2300 a valid final fail state */
2301 fail[ 0 ] = fail[ 1 ] = 1;
2303 for ( charid = 0; charid < ucharcount ; charid++ ) {
2304 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2306 q[ q_write ] = newstate;
2307 /* set to point at the root */
2308 fail[ q[ q_write++ ] ]=1;
2311 while ( q_read < q_write) {
2312 const U32 cur = q[ q_read++ % numstates ];
2313 base = trie->states[ cur ].trans.base;
2315 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2316 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2318 U32 fail_state = cur;
2321 fail_state = fail[ fail_state ];
2322 fail_base = aho->states[ fail_state ].trans.base;
2323 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2325 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2326 fail[ ch_state ] = fail_state;
2327 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2329 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2331 q[ q_write++ % numstates] = ch_state;
2335 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2336 when we fail in state 1, this allows us to use the
2337 charclass scan to find a valid start char. This is based on the principle
2338 that theres a good chance the string being searched contains lots of stuff
2339 that cant be a start char.
2341 fail[ 0 ] = fail[ 1 ] = 0;
2342 DEBUG_TRIE_COMPILE_r({
2343 PerlIO_printf(Perl_debug_log,
2344 "%*sStclass Failtable (%"UVuf" states): 0",
2345 (int)(depth * 2), "", (UV)numstates
2347 for( q_read=1; q_read<numstates; q_read++ ) {
2348 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2350 PerlIO_printf(Perl_debug_log, "\n");
2353 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2358 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2359 * These need to be revisited when a newer toolchain becomes available.
2361 #if defined(__sparc64__) && defined(__GNUC__)
2362 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2363 # undef SPARC64_GCC_WORKAROUND
2364 # define SPARC64_GCC_WORKAROUND 1
2368 #define DEBUG_PEEP(str,scan,depth) \
2369 DEBUG_OPTIMISE_r({if (scan){ \
2370 SV * const mysv=sv_newmortal(); \
2371 regnode *Next = regnext(scan); \
2372 regprop(RExC_rx, mysv, scan); \
2373 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2374 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2375 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2382 #define JOIN_EXACT(scan,min,flags) \
2383 if (PL_regkind[OP(scan)] == EXACT) \
2384 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2387 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2388 /* Merge several consecutive EXACTish nodes into one. */
2389 regnode *n = regnext(scan);
2391 regnode *next = scan + NODE_SZ_STR(scan);
2395 regnode *stop = scan;
2396 GET_RE_DEBUG_FLAGS_DECL;
2398 PERL_UNUSED_ARG(depth);
2401 PERL_ARGS_ASSERT_JOIN_EXACT;
2402 #ifndef EXPERIMENTAL_INPLACESCAN
2403 PERL_UNUSED_ARG(flags);
2404 PERL_UNUSED_ARG(val);
2406 DEBUG_PEEP("join",scan,depth);
2408 /* Skip NOTHING, merge EXACT*. */
2410 ( PL_regkind[OP(n)] == NOTHING ||
2411 (stringok && (OP(n) == OP(scan))))
2413 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2415 if (OP(n) == TAIL || n > next)
2417 if (PL_regkind[OP(n)] == NOTHING) {
2418 DEBUG_PEEP("skip:",n,depth);
2419 NEXT_OFF(scan) += NEXT_OFF(n);
2420 next = n + NODE_STEP_REGNODE;
2427 else if (stringok) {
2428 const unsigned int oldl = STR_LEN(scan);
2429 regnode * const nnext = regnext(n);
2431 DEBUG_PEEP("merg",n,depth);
2434 if (oldl + STR_LEN(n) > U8_MAX)
2436 NEXT_OFF(scan) += NEXT_OFF(n);
2437 STR_LEN(scan) += STR_LEN(n);
2438 next = n + NODE_SZ_STR(n);
2439 /* Now we can overwrite *n : */
2440 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2448 #ifdef EXPERIMENTAL_INPLACESCAN
2449 if (flags && !NEXT_OFF(n)) {
2450 DEBUG_PEEP("atch", val, depth);
2451 if (reg_off_by_arg[OP(n)]) {
2452 ARG_SET(n, val - n);
2455 NEXT_OFF(n) = val - n;
2461 #define GREEK_SMALL_LETTER_IOTA_WITH_DIALYTIKA_AND_TONOS 0x0390
2462 #define IOTA_D_T GREEK_SMALL_LETTER_IOTA_WITH_DIALYTIKA_AND_TONOS
2463 #define GREEK_SMALL_LETTER_UPSILON_WITH_DIALYTIKA_AND_TONOS 0x03B0
2464 #define UPSILON_D_T GREEK_SMALL_LETTER_UPSILON_WITH_DIALYTIKA_AND_TONOS
2467 && ( OP(scan) == EXACTF || OP(scan) == EXACTFU)
2468 && ( STR_LEN(scan) >= 6 ) )
2471 Two problematic code points in Unicode casefolding of EXACT nodes:
2473 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2474 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2480 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2481 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2483 This means that in case-insensitive matching (or "loose matching",
2484 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2485 length of the above casefolded versions) can match a target string
2486 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2487 This would rather mess up the minimum length computation.
2489 What we'll do is to look for the tail four bytes, and then peek
2490 at the preceding two bytes to see whether we need to decrease
2491 the minimum length by four (six minus two).
2493 Thanks to the design of UTF-8, there cannot be false matches:
2494 A sequence of valid UTF-8 bytes cannot be a subsequence of
2495 another valid sequence of UTF-8 bytes.
2498 char * const s0 = STRING(scan), *s, *t;
2499 char * const s1 = s0 + STR_LEN(scan) - 1;
2500 char * const s2 = s1 - 4;
2501 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2502 const char t0[] = "\xaf\x49\xaf\x42";
2504 const char t0[] = "\xcc\x88\xcc\x81";
2506 const char * const t1 = t0 + 3;
2509 s < s2 && (t = ninstr(s, s1, t0, t1));
2512 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2513 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2515 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2516 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2524 n = scan + NODE_SZ_STR(scan);
2526 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2533 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2537 /* REx optimizer. Converts nodes into quicker variants "in place".
2538 Finds fixed substrings. */
2540 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2541 to the position after last scanned or to NULL. */
2543 #define INIT_AND_WITHP \
2544 assert(!and_withp); \
2545 Newx(and_withp,1,struct regnode_charclass_class); \
2546 SAVEFREEPV(and_withp)
2548 /* this is a chain of data about sub patterns we are processing that
2549 need to be handled separately/specially in study_chunk. Its so
2550 we can simulate recursion without losing state. */
2552 typedef struct scan_frame {
2553 regnode *last; /* last node to process in this frame */
2554 regnode *next; /* next node to process when last is reached */
2555 struct scan_frame *prev; /*previous frame*/
2556 I32 stop; /* what stopparen do we use */
2560 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2562 #define CASE_SYNST_FNC(nAmE) \
2564 if (flags & SCF_DO_STCLASS_AND) { \
2565 for (value = 0; value < 256; value++) \
2566 if (!is_ ## nAmE ## _cp(value)) \
2567 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2570 for (value = 0; value < 256; value++) \
2571 if (is_ ## nAmE ## _cp(value)) \
2572 ANYOF_BITMAP_SET(data->start_class, value); \
2576 if (flags & SCF_DO_STCLASS_AND) { \
2577 for (value = 0; value < 256; value++) \
2578 if (is_ ## nAmE ## _cp(value)) \
2579 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2582 for (value = 0; value < 256; value++) \
2583 if (!is_ ## nAmE ## _cp(value)) \
2584 ANYOF_BITMAP_SET(data->start_class, value); \
2591 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2592 I32 *minlenp, I32 *deltap,
2597 struct regnode_charclass_class *and_withp,
2598 U32 flags, U32 depth)
2599 /* scanp: Start here (read-write). */
2600 /* deltap: Write maxlen-minlen here. */
2601 /* last: Stop before this one. */
2602 /* data: string data about the pattern */
2603 /* stopparen: treat close N as END */
2604 /* recursed: which subroutines have we recursed into */
2605 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2608 I32 min = 0, pars = 0, code;
2609 regnode *scan = *scanp, *next;
2611 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2612 int is_inf_internal = 0; /* The studied chunk is infinite */
2613 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2614 scan_data_t data_fake;
2615 SV *re_trie_maxbuff = NULL;
2616 regnode *first_non_open = scan;
2617 I32 stopmin = I32_MAX;
2618 scan_frame *frame = NULL;
2619 GET_RE_DEBUG_FLAGS_DECL;
2621 PERL_ARGS_ASSERT_STUDY_CHUNK;
2624 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2628 while (first_non_open && OP(first_non_open) == OPEN)
2629 first_non_open=regnext(first_non_open);
2634 while ( scan && OP(scan) != END && scan < last ){
2635 /* Peephole optimizer: */
2636 DEBUG_STUDYDATA("Peep:", data,depth);
2637 DEBUG_PEEP("Peep",scan,depth);
2638 JOIN_EXACT(scan,&min,0);
2640 /* Follow the next-chain of the current node and optimize
2641 away all the NOTHINGs from it. */
2642 if (OP(scan) != CURLYX) {
2643 const int max = (reg_off_by_arg[OP(scan)]
2645 /* I32 may be smaller than U16 on CRAYs! */
2646 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2647 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2651 /* Skip NOTHING and LONGJMP. */
2652 while ((n = regnext(n))
2653 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2654 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2655 && off + noff < max)
2657 if (reg_off_by_arg[OP(scan)])
2660 NEXT_OFF(scan) = off;
2665 /* The principal pseudo-switch. Cannot be a switch, since we
2666 look into several different things. */
2667 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2668 || OP(scan) == IFTHEN) {
2669 next = regnext(scan);
2671 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2673 if (OP(next) == code || code == IFTHEN) {
2674 /* NOTE - There is similar code to this block below for handling
2675 TRIE nodes on a re-study. If you change stuff here check there
2677 I32 max1 = 0, min1 = I32_MAX, num = 0;
2678 struct regnode_charclass_class accum;
2679 regnode * const startbranch=scan;
2681 if (flags & SCF_DO_SUBSTR)
2682 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2683 if (flags & SCF_DO_STCLASS)
2684 cl_init_zero(pRExC_state, &accum);
2686 while (OP(scan) == code) {
2687 I32 deltanext, minnext, f = 0, fake;
2688 struct regnode_charclass_class this_class;
2691 data_fake.flags = 0;
2693 data_fake.whilem_c = data->whilem_c;
2694 data_fake.last_closep = data->last_closep;
2697 data_fake.last_closep = &fake;
2699 data_fake.pos_delta = delta;
2700 next = regnext(scan);
2701 scan = NEXTOPER(scan);
2703 scan = NEXTOPER(scan);
2704 if (flags & SCF_DO_STCLASS) {
2705 cl_init(pRExC_state, &this_class);
2706 data_fake.start_class = &this_class;
2707 f = SCF_DO_STCLASS_AND;
2709 if (flags & SCF_WHILEM_VISITED_POS)
2710 f |= SCF_WHILEM_VISITED_POS;
2712 /* we suppose the run is continuous, last=next...*/
2713 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2715 stopparen, recursed, NULL, f,depth+1);
2718 if (max1 < minnext + deltanext)
2719 max1 = minnext + deltanext;
2720 if (deltanext == I32_MAX)
2721 is_inf = is_inf_internal = 1;
2723 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2725 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2726 if ( stopmin > minnext)
2727 stopmin = min + min1;
2728 flags &= ~SCF_DO_SUBSTR;
2730 data->flags |= SCF_SEEN_ACCEPT;
2733 if (data_fake.flags & SF_HAS_EVAL)
2734 data->flags |= SF_HAS_EVAL;
2735 data->whilem_c = data_fake.whilem_c;
2737 if (flags & SCF_DO_STCLASS)
2738 cl_or(pRExC_state, &accum, &this_class);
2740 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2742 if (flags & SCF_DO_SUBSTR) {
2743 data->pos_min += min1;
2744 data->pos_delta += max1 - min1;
2745 if (max1 != min1 || is_inf)
2746 data->longest = &(data->longest_float);
2749 delta += max1 - min1;
2750 if (flags & SCF_DO_STCLASS_OR) {
2751 cl_or(pRExC_state, data->start_class, &accum);
2753 cl_and(data->start_class, and_withp);
2754 flags &= ~SCF_DO_STCLASS;
2757 else if (flags & SCF_DO_STCLASS_AND) {
2759 cl_and(data->start_class, &accum);
2760 flags &= ~SCF_DO_STCLASS;
2763 /* Switch to OR mode: cache the old value of
2764 * data->start_class */
2766 StructCopy(data->start_class, and_withp,
2767 struct regnode_charclass_class);
2768 flags &= ~SCF_DO_STCLASS_AND;
2769 StructCopy(&accum, data->start_class,
2770 struct regnode_charclass_class);
2771 flags |= SCF_DO_STCLASS_OR;
2772 data->start_class->flags |= ANYOF_EOS;
2776 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2779 Assuming this was/is a branch we are dealing with: 'scan' now
2780 points at the item that follows the branch sequence, whatever
2781 it is. We now start at the beginning of the sequence and look
2788 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2790 If we can find such a subsequence we need to turn the first
2791 element into a trie and then add the subsequent branch exact
2792 strings to the trie.
2796 1. patterns where the whole set of branches can be converted.
2798 2. patterns where only a subset can be converted.
2800 In case 1 we can replace the whole set with a single regop
2801 for the trie. In case 2 we need to keep the start and end
2804 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2805 becomes BRANCH TRIE; BRANCH X;
2807 There is an additional case, that being where there is a
2808 common prefix, which gets split out into an EXACT like node
2809 preceding the TRIE node.
2811 If x(1..n)==tail then we can do a simple trie, if not we make
2812 a "jump" trie, such that when we match the appropriate word
2813 we "jump" to the appropriate tail node. Essentially we turn
2814 a nested if into a case structure of sorts.
2819 if (!re_trie_maxbuff) {
2820 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2821 if (!SvIOK(re_trie_maxbuff))
2822 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2824 if ( SvIV(re_trie_maxbuff)>=0 ) {
2826 regnode *first = (regnode *)NULL;
2827 regnode *last = (regnode *)NULL;
2828 regnode *tail = scan;
2833 SV * const mysv = sv_newmortal(); /* for dumping */
2835 /* var tail is used because there may be a TAIL
2836 regop in the way. Ie, the exacts will point to the
2837 thing following the TAIL, but the last branch will
2838 point at the TAIL. So we advance tail. If we
2839 have nested (?:) we may have to move through several
2843 while ( OP( tail ) == TAIL ) {
2844 /* this is the TAIL generated by (?:) */
2845 tail = regnext( tail );
2850 regprop(RExC_rx, mysv, tail );
2851 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2852 (int)depth * 2 + 2, "",
2853 "Looking for TRIE'able sequences. Tail node is: ",
2854 SvPV_nolen_const( mysv )
2860 step through the branches, cur represents each
2861 branch, noper is the first thing to be matched
2862 as part of that branch and noper_next is the
2863 regnext() of that node. if noper is an EXACT
2864 and noper_next is the same as scan (our current
2865 position in the regex) then the EXACT branch is
2866 a possible optimization target. Once we have
2867 two or more consecutive such branches we can
2868 create a trie of the EXACT's contents and stich
2869 it in place. If the sequence represents all of
2870 the branches we eliminate the whole thing and
2871 replace it with a single TRIE. If it is a
2872 subsequence then we need to stitch it in. This
2873 means the first branch has to remain, and needs
2874 to be repointed at the item on the branch chain
2875 following the last branch optimized. This could
2876 be either a BRANCH, in which case the
2877 subsequence is internal, or it could be the
2878 item following the branch sequence in which
2879 case the subsequence is at the end.
2883 /* dont use tail as the end marker for this traverse */
2884 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2885 regnode * const noper = NEXTOPER( cur );
2886 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2887 regnode * const noper_next = regnext( noper );
2891 regprop(RExC_rx, mysv, cur);
2892 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2893 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2895 regprop(RExC_rx, mysv, noper);
2896 PerlIO_printf( Perl_debug_log, " -> %s",
2897 SvPV_nolen_const(mysv));
2900 regprop(RExC_rx, mysv, noper_next );
2901 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2902 SvPV_nolen_const(mysv));
2904 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2905 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2907 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2908 : PL_regkind[ OP( noper ) ] == EXACT )
2909 || OP(noper) == NOTHING )
2911 && noper_next == tail
2916 if ( !first || optype == NOTHING ) {
2917 if (!first) first = cur;
2918 optype = OP( noper );
2924 Currently we do not believe that the trie logic can
2925 handle case insensitive matching properly when the
2926 pattern is not unicode (thus forcing unicode semantics).
2928 If/when this is fixed the following define can be swapped
2929 in below to fully enable trie logic.
2931 #define TRIE_TYPE_IS_SAFE 1
2934 #define TRIE_TYPE_IS_SAFE (UTF || optype==EXACT)
2936 if ( last && TRIE_TYPE_IS_SAFE ) {
2937 make_trie( pRExC_state,
2938 startbranch, first, cur, tail, count,
2941 if ( PL_regkind[ OP( noper ) ] == EXACT
2943 && noper_next == tail
2948 optype = OP( noper );
2958 regprop(RExC_rx, mysv, cur);
2959 PerlIO_printf( Perl_debug_log,
2960 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2961 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2965 if ( last && TRIE_TYPE_IS_SAFE ) {
2966 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2967 #ifdef TRIE_STUDY_OPT
2968 if ( ((made == MADE_EXACT_TRIE &&
2969 startbranch == first)
2970 || ( first_non_open == first )) &&
2972 flags |= SCF_TRIE_RESTUDY;
2973 if ( startbranch == first
2976 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2986 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2987 scan = NEXTOPER(NEXTOPER(scan));
2988 } else /* single branch is optimized. */
2989 scan = NEXTOPER(scan);
2991 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2992 scan_frame *newframe = NULL;
2997 if (OP(scan) != SUSPEND) {
2998 /* set the pointer */
2999 if (OP(scan) == GOSUB) {
3001 RExC_recurse[ARG2L(scan)] = scan;
3002 start = RExC_open_parens[paren-1];
3003 end = RExC_close_parens[paren-1];
3006 start = RExC_rxi->program + 1;
3010 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3011 SAVEFREEPV(recursed);
3013 if (!PAREN_TEST(recursed,paren+1)) {
3014 PAREN_SET(recursed,paren+1);
3015 Newx(newframe,1,scan_frame);
3017 if (flags & SCF_DO_SUBSTR) {
3018 SCAN_COMMIT(pRExC_state,data,minlenp);
3019 data->longest = &(data->longest_float);
3021 is_inf = is_inf_internal = 1;
3022 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3023 cl_anything(pRExC_state, data->start_class);
3024 flags &= ~SCF_DO_STCLASS;
3027 Newx(newframe,1,scan_frame);
3030 end = regnext(scan);
3035 SAVEFREEPV(newframe);
3036 newframe->next = regnext(scan);
3037 newframe->last = last;
3038 newframe->stop = stopparen;
3039 newframe->prev = frame;
3049 else if (OP(scan) == EXACT) {
3050 I32 l = STR_LEN(scan);
3053 const U8 * const s = (U8*)STRING(scan);
3054 l = utf8_length(s, s + l);
3055 uc = utf8_to_uvchr(s, NULL);
3057 uc = *((U8*)STRING(scan));
3060 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3061 /* The code below prefers earlier match for fixed
3062 offset, later match for variable offset. */
3063 if (data->last_end == -1) { /* Update the start info. */
3064 data->last_start_min = data->pos_min;
3065 data->last_start_max = is_inf
3066 ? I32_MAX : data->pos_min + data->pos_delta;
3068 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3070 SvUTF8_on(data->last_found);
3072 SV * const sv = data->last_found;
3073 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3074 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3075 if (mg && mg->mg_len >= 0)
3076 mg->mg_len += utf8_length((U8*)STRING(scan),
3077 (U8*)STRING(scan)+STR_LEN(scan));
3079 data->last_end = data->pos_min + l;
3080 data->pos_min += l; /* As in the first entry. */
3081 data->flags &= ~SF_BEFORE_EOL;
3083 if (flags & SCF_DO_STCLASS_AND) {
3084 /* Check whether it is compatible with what we know already! */
3088 /* If compatible, we or it in below. It is compatible if is
3089 * in the bitmp and either 1) its bit or its fold is set, or 2)
3090 * it's for a locale. Even if there isn't unicode semantics
3091 * here, at runtime there may be because of matching against a
3092 * utf8 string, so accept a possible false positive for
3093 * latin1-range folds */
3095 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3096 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3097 && (!(data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD)
3098 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3101 ANYOF_CLASS_ZERO(data->start_class);
3102 ANYOF_BITMAP_ZERO(data->start_class);
3104 ANYOF_BITMAP_SET(data->start_class, uc);
3105 data->start_class->flags &= ~ANYOF_EOS;
3107 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3109 else if (flags & SCF_DO_STCLASS_OR) {
3110 /* false positive possible if the class is case-folded */
3112 ANYOF_BITMAP_SET(data->start_class, uc);
3114 data->start_class->flags |= ANYOF_UNICODE_ALL;
3115 data->start_class->flags &= ~ANYOF_EOS;
3116 cl_and(data->start_class, and_withp);
3118 flags &= ~SCF_DO_STCLASS;
3120 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3121 I32 l = STR_LEN(scan);
3122 UV uc = *((U8*)STRING(scan));
3124 /* Search for fixed substrings supports EXACT only. */
3125 if (flags & SCF_DO_SUBSTR) {
3127 SCAN_COMMIT(pRExC_state, data, minlenp);
3130 const U8 * const s = (U8 *)STRING(scan);
3131 l = utf8_length(s, s + l);
3132 uc = utf8_to_uvchr(s, NULL);
3135 if (flags & SCF_DO_SUBSTR)
3137 if (flags & SCF_DO_STCLASS_AND) {
3138 /* Check whether it is compatible with what we know already! */
3141 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3142 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3143 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3147 ANYOF_CLASS_ZERO(data->start_class);
3148 ANYOF_BITMAP_ZERO(data->start_class);
3150 ANYOF_BITMAP_SET(data->start_class, uc);
3151 data->start_class->flags &= ~ANYOF_EOS;
3152 data->start_class->flags |= ANYOF_LOC_NONBITMAP_FOLD;
3153 if (OP(scan) == EXACTFL) {
3154 data->start_class->flags |= ANYOF_LOCALE;
3158 /* Also set the other member of the fold pair. In case
3159 * that unicode semantics is called for at runtime, use
3160 * the full latin1 fold. (Can't do this for locale,
3161 * because not known until runtime */
3162 ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
3166 else if (flags & SCF_DO_STCLASS_OR) {
3167 if (data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD) {
3168 /* false positive possible if the class is case-folded.
3169 Assume that the locale settings are the same... */
3171 ANYOF_BITMAP_SET(data->start_class, uc);
3172 if (OP(scan) != EXACTFL) {
3174 /* And set the other member of the fold pair, but
3175 * can't do that in locale because not known until
3177 ANYOF_BITMAP_SET(data->start_class,
3178 PL_fold_latin1[uc]);
3181 data->start_class->flags &= ~ANYOF_EOS;
3183 cl_and(data->start_class, and_withp);
3185 flags &= ~SCF_DO_STCLASS;
3187 else if (REGNODE_VARIES(OP(scan))) {
3188 I32 mincount, maxcount, minnext, deltanext, fl = 0;
3189 I32 f = flags, pos_before = 0;
3190 regnode * const oscan = scan;
3191 struct regnode_charclass_class this_class;
3192 struct regnode_charclass_class *oclass = NULL;
3193 I32 next_is_eval = 0;
3195 switch (PL_regkind[OP(scan)]) {
3196 case WHILEM: /* End of (?:...)* . */
3197 scan = NEXTOPER(scan);
3200 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3201 next = NEXTOPER(scan);
3202 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3204 maxcount = REG_INFTY;
3205 next = regnext(scan);
3206 scan = NEXTOPER(scan);
3210 if (flags & SCF_DO_SUBSTR)
3215 if (flags & SCF_DO_STCLASS) {
3217 maxcount = REG_INFTY;
3218 next = regnext(scan);
3219 scan = NEXTOPER(scan);
3222 is_inf = is_inf_internal = 1;
3223 scan = regnext(scan);
3224 if (flags & SCF_DO_SUBSTR) {
3225 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3226 data->longest = &(data->longest_float);
3228 goto optimize_curly_tail;
3230 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3231 && (scan->flags == stopparen))
3236 mincount = ARG1(scan);
3237 maxcount = ARG2(scan);
3239 next = regnext(scan);
3240 if (OP(scan) == CURLYX) {
3241 I32 lp = (data ? *(data->last_closep) : 0);
3242 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3244 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3245 next_is_eval = (OP(scan) == EVAL);
3247 if (flags & SCF_DO_SUBSTR) {
3248 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3249 pos_before = data->pos_min;
3253 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3255 data->flags |= SF_IS_INF;
3257 if (flags & SCF_DO_STCLASS) {
3258 cl_init(pRExC_state, &this_class);
3259 oclass = data->start_class;
3260 data->start_class = &this_class;
3261 f |= SCF_DO_STCLASS_AND;
3262 f &= ~SCF_DO_STCLASS_OR;
3264 /* Exclude from super-linear cache processing any {n,m}
3265 regops for which the combination of input pos and regex
3266 pos is not enough information to determine if a match
3269 For example, in the regex /foo(bar\s*){4,8}baz/ with the
3270 regex pos at the \s*, the prospects for a match depend not
3271 only on the input position but also on how many (bar\s*)
3272 repeats into the {4,8} we are. */
3273 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
3274 f &= ~SCF_WHILEM_VISITED_POS;
3276 /* This will finish on WHILEM, setting scan, or on NULL: */
3277 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3278 last, data, stopparen, recursed, NULL,
3280 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3282 if (flags & SCF_DO_STCLASS)
3283 data->start_class = oclass;
3284 if (mincount == 0 || minnext == 0) {
3285 if (flags & SCF_DO_STCLASS_OR) {
3286 cl_or(pRExC_state, data->start_class, &this_class);
3288 else if (flags & SCF_DO_STCLASS_AND) {
3289 /* Switch to OR mode: cache the old value of
3290 * data->start_class */
3292 StructCopy(data->start_class, and_withp,
3293 struct regnode_charclass_class);
3294 flags &= ~SCF_DO_STCLASS_AND;
3295 StructCopy(&this_class, data->start_class,
3296 struct regnode_charclass_class);
3297 flags |= SCF_DO_STCLASS_OR;
3298 data->start_class->flags |= ANYOF_EOS;
3300 } else { /* Non-zero len */
3301 if (flags & SCF_DO_STCLASS_OR) {
3302 cl_or(pRExC_state, data->start_class, &this_class);
3303 cl_and(data->start_class, and_withp);
3305 else if (flags & SCF_DO_STCLASS_AND)
3306 cl_and(data->start_class, &this_class);
3307 flags &= ~SCF_DO_STCLASS;
3309 if (!scan) /* It was not CURLYX, but CURLY. */
3311 if ( /* ? quantifier ok, except for (?{ ... }) */
3312 (next_is_eval || !(mincount == 0 && maxcount == 1))
3313 && (minnext == 0) && (deltanext == 0)
3314 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3315 && maxcount <= REG_INFTY/3) /* Complement check for big count */
3317 ckWARNreg(RExC_parse,
3318 "Quantifier unexpected on zero-length expression");
3321 min += minnext * mincount;
3322 is_inf_internal |= ((maxcount == REG_INFTY
3323 && (minnext + deltanext) > 0)
3324 || deltanext == I32_MAX);
3325 is_inf |= is_inf_internal;
3326 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3328 /* Try powerful optimization CURLYX => CURLYN. */
3329 if ( OP(oscan) == CURLYX && data
3330 && data->flags & SF_IN_PAR
3331 && !(data->flags & SF_HAS_EVAL)
3332 && !deltanext && minnext == 1 ) {
3333 /* Try to optimize to CURLYN. */
3334 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3335 regnode * const nxt1 = nxt;
3342 if (!REGNODE_SIMPLE(OP(nxt))
3343 && !(PL_regkind[OP(nxt)] == EXACT
3344 && STR_LEN(nxt) == 1))
3350 if (OP(nxt) != CLOSE)
3352 if (RExC_open_parens) {
3353 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3354 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3356 /* Now we know that nxt2 is the only contents: */
3357 oscan->flags = (U8)ARG(nxt);
3359 OP(nxt1) = NOTHING; /* was OPEN. */
3362 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3363 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3364 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
3365 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3366 OP(nxt + 1) = OPTIMIZED; /* was count. */
3367 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
3372 /* Try optimization CURLYX => CURLYM. */
3373 if ( OP(oscan) == CURLYX && data
3374 && !(data->flags & SF_HAS_PAR)
3375 && !(data->flags & SF_HAS_EVAL)
3376 && !deltanext /* atom is fixed width */
3377 && minnext != 0 /* CURLYM can't handle zero width */
3379 /* XXXX How to optimize if data == 0? */
3380 /* Optimize to a simpler form. */
3381 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3385 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3386 && (OP(nxt2) != WHILEM))
3388 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3389 /* Need to optimize away parenths. */
3390 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
3391 /* Set the parenth number. */
3392 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3394 oscan->flags = (U8)ARG(nxt);
3395 if (RExC_open_parens) {
3396 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3397 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3399 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3400 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3403 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3404 OP(nxt + 1) = OPTIMIZED; /* was count. */
3405 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
3406 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
3409 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3410 regnode *nnxt = regnext(nxt1);
3412 if (reg_off_by_arg[OP(nxt1)])
3413 ARG_SET(nxt1, nxt2 - nxt1);
3414 else if (nxt2 - nxt1 < U16_MAX)
3415 NEXT_OFF(nxt1) = nxt2 - nxt1;
3417 OP(nxt) = NOTHING; /* Cannot beautify */
3422 /* Optimize again: */
3423 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3424 NULL, stopparen, recursed, NULL, 0,depth+1);
3429 else if ((OP(oscan) == CURLYX)
3430 && (flags & SCF_WHILEM_VISITED_POS)
3431 /* See the comment on a similar expression above.
3432 However, this time it's not a subexpression
3433 we care about, but the expression itself. */
3434 && (maxcount == REG_INFTY)
3435 && data && ++data->whilem_c < 16) {
3436 /* This stays as CURLYX, we can put the count/of pair. */
3437 /* Find WHILEM (as in regexec.c) */
3438 regnode *nxt = oscan + NEXT_OFF(oscan);
3440 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3442 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3443 | (RExC_whilem_seen << 4)); /* On WHILEM */
3445 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3447 if (flags & SCF_DO_SUBSTR) {
3448 SV *last_str = NULL;
3449 int counted = mincount != 0;
3451 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3452 #if defined(SPARC64_GCC_WORKAROUND)
3455 const char *s = NULL;
3458 if (pos_before >= data->last_start_min)
3461 b = data->last_start_min;
3464 s = SvPV_const(data->last_found, l);
3465 old = b - data->last_start_min;
3468 I32 b = pos_before >= data->last_start_min
3469 ? pos_before : data->last_start_min;
3471 const char * const s = SvPV_const(data->last_found, l);
3472 I32 old = b - data->last_start_min;
3476 old = utf8_hop((U8*)s, old) - (U8*)s;
3478 /* Get the added string: */
3479 last_str = newSVpvn_utf8(s + old, l, UTF);
3480 if (deltanext == 0 && pos_before == b) {
3481 /* What was added is a constant string */
3483 SvGROW(last_str, (mincount * l) + 1);
3484 repeatcpy(SvPVX(last_str) + l,
3485 SvPVX_const(last_str), l, mincount - 1);
3486 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3487 /* Add additional parts. */
3488 SvCUR_set(data->last_found,
3489 SvCUR(data->last_found) - l);
3490 sv_catsv(data->last_found, last_str);
3492 SV * sv = data->last_found;
3494 SvUTF8(sv) && SvMAGICAL(sv) ?
3495 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3496 if (mg && mg->mg_len >= 0)
3497 mg->mg_len += CHR_SVLEN(last_str) - l;
3499 data->last_end += l * (mincount - 1);
3502 /* start offset must point into the last copy */
3503 data->last_start_min += minnext * (mincount - 1);
3504 data->last_start_max += is_inf ? I32_MAX
3505 : (maxcount - 1) * (minnext + data->pos_delta);
3508 /* It is counted once already... */
3509 data->pos_min += minnext * (mincount - counted);
3510 data->pos_delta += - counted * deltanext +
3511 (minnext + deltanext) * maxcount - minnext * mincount;
3512 if (mincount != maxcount) {
3513 /* Cannot extend fixed substrings found inside
3515 SCAN_COMMIT(pRExC_state,data,minlenp);
3516 if (mincount && last_str) {
3517 SV * const sv = data->last_found;
3518 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3519 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3523 sv_setsv(sv, last_str);
3524 data->last_end = data->pos_min;
3525 data->last_start_min =
3526 data->pos_min - CHR_SVLEN(last_str);
3527 data->last_start_max = is_inf
3529 : data->pos_min + data->pos_delta
3530 - CHR_SVLEN(last_str);
3532 data->longest = &(data->longest_float);
3534 SvREFCNT_dec(last_str);
3536 if (data && (fl & SF_HAS_EVAL))
3537 data->flags |= SF_HAS_EVAL;
3538 optimize_curly_tail:
3539 if (OP(oscan) != CURLYX) {
3540 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3542 NEXT_OFF(oscan) += NEXT_OFF(next);
3545 default: /* REF, ANYOFV, and CLUMP only? */
3546 if (flags & SCF_DO_SUBSTR) {
3547 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3548 data->longest = &(data->longest_float);
3550 is_inf = is_inf_internal = 1;
3551 if (flags & SCF_DO_STCLASS_OR)
3552 cl_anything(pRExC_state, data->start_class);
3553 flags &= ~SCF_DO_STCLASS;
3557 else if (OP(scan) == LNBREAK) {
3558 if (flags & SCF_DO_STCLASS) {
3560 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3561 if (flags & SCF_DO_STCLASS_AND) {
3562 for (value = 0; value < 256; value++)
3563 if (!is_VERTWS_cp(value))
3564 ANYOF_BITMAP_CLEAR(data->start_class, value);
3567 for (value = 0; value < 256; value++)
3568 if (is_VERTWS_cp(value))
3569 ANYOF_BITMAP_SET(data->start_class, value);
3571 if (flags & SCF_DO_STCLASS_OR)
3572 cl_and(data->start_class, and_withp);
3573 flags &= ~SCF_DO_STCLASS;
3577 if (flags & SCF_DO_SUBSTR) {
3578 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3580 data->pos_delta += 1;
3581 data->longest = &(data->longest_float);
3584 else if (OP(scan) == FOLDCHAR) {
3585 int d = ARG(scan) == LATIN_SMALL_LETTER_SHARP_S ? 1 : 2;
3586 flags &= ~SCF_DO_STCLASS;
3589 if (flags & SCF_DO_SUBSTR) {
3590 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3592 data->pos_delta += d;
3593 data->longest = &(data->longest_float);
3596 else if (REGNODE_SIMPLE(OP(scan))) {
3599 if (flags & SCF_DO_SUBSTR) {
3600 SCAN_COMMIT(pRExC_state,data,minlenp);
3604 if (flags & SCF_DO_STCLASS) {
3605 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3607 /* Some of the logic below assumes that switching
3608 locale on will only add false positives. */
3609 switch (PL_regkind[OP(scan)]) {
3613 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3614 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3615 cl_anything(pRExC_state, data->start_class);
3618 if (OP(scan) == SANY)
3620 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3621 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3622 || ANYOF_CLASS_TEST_ANY_SET(data->start_class));
3623 cl_anything(pRExC_state, data->start_class);
3625 if (flags & SCF_DO_STCLASS_AND || !value)
3626 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3629 if (flags & SCF_DO_STCLASS_AND)
3630 cl_and(data->start_class,
3631 (struct regnode_charclass_class*)scan);
3633 cl_or(pRExC_state, data->start_class,
3634 (struct regnode_charclass_class*)scan);
3637 if (flags & SCF_DO_STCLASS_AND) {
3638 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3639 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3640 if (OP(scan) == ALNUMU) {
3641 for (value = 0; value < 256; value++) {
3642 if (!isWORDCHAR_L1(value)) {
3643 ANYOF_BITMAP_CLEAR(data->start_class, value);
3647 for (value = 0; value < 256; value++) {
3648 if (!isALNUM(value)) {
3649 ANYOF_BITMAP_CLEAR(data->start_class, value);
3656 if (data->start_class->flags & ANYOF_LOCALE)
3657 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3658 else if (OP(scan) == ALNUMU) {
3659 for (value = 0; value < 256; value++) {
3660 if (isWORDCHAR_L1(value)) {
3661 ANYOF_BITMAP_SET(data->start_class, value);
3665 for (value = 0; value < 256; value++) {
3666 if (isALNUM(value)) {
3667 ANYOF_BITMAP_SET(data->start_class, value);
3674 if (flags & SCF_DO_STCLASS_AND) {
3675 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3676 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3677 if (OP(scan) == NALNUMU) {
3678 for (value = 0; value < 256; value++) {
3679 if (isWORDCHAR_L1(value)) {
3680 ANYOF_BITMAP_CLEAR(data->start_class, value);
3684 for (value = 0; value < 256; value++) {
3685 if (isALNUM(value)) {
3686 ANYOF_BITMAP_CLEAR(data->start_class, value);
3693 if (data->start_class->flags & ANYOF_LOCALE)
3694 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3696 if (OP(scan) == NALNUMU) {
3697 for (value = 0; value < 256; value++) {
3698 if (! isWORDCHAR_L1(value)) {
3699 ANYOF_BITMAP_SET(data->start_class, value);
3703 for (value = 0; value < 256; value++) {
3704 if (! isALNUM(value)) {
3705 ANYOF_BITMAP_SET(data->start_class, value);
3713 if (flags & SCF_DO_STCLASS_AND) {
3714 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3715 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3716 if (OP(scan) == SPACEU) {
3717 for (value = 0; value < 256; value++) {
3718 if (!isSPACE_L1(value)) {
3719 ANYOF_BITMAP_CLEAR(data->start_class, value);
3723 for (value = 0; value < 256; value++) {
3724 if (!isSPACE(value)) {
3725 ANYOF_BITMAP_CLEAR(data->start_class, value);
3732 if (data->start_class->flags & ANYOF_LOCALE) {
3733 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3735 else if (OP(scan) == SPACEU) {
3736 for (value = 0; value < 256; value++) {
3737 if (isSPACE_L1(value)) {
3738 ANYOF_BITMAP_SET(data->start_class, value);
3742 for (value = 0; value < 256; value++) {
3743 if (isSPACE(value)) {
3744 ANYOF_BITMAP_SET(data->start_class, value);
3751 if (flags & SCF_DO_STCLASS_AND) {
3752 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3753 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3754 if (OP(scan) == NSPACEU) {
3755 for (value = 0; value < 256; value++) {
3756 if (isSPACE_L1(value)) {
3757 ANYOF_BITMAP_CLEAR(data->start_class, value);
3761 for (value = 0; value < 256; value++) {
3762 if (isSPACE(value)) {
3763 ANYOF_BITMAP_CLEAR(data->start_class, value);
3770 if (data->start_class->flags & ANYOF_LOCALE)
3771 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3772 else if (OP(scan) == NSPACEU) {
3773 for (value = 0; value < 256; value++) {
3774 if (!isSPACE_L1(value)) {
3775 ANYOF_BITMAP_SET(data->start_class, value);
3780 for (value = 0; value < 256; value++) {
3781 if (!isSPACE(value)) {
3782 ANYOF_BITMAP_SET(data->start_class, value);
3789 if (flags & SCF_DO_STCLASS_AND) {
3790 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3791 for (value = 0; value < 256; value++)
3792 if (!isDIGIT(value))
3793 ANYOF_BITMAP_CLEAR(data->start_class, value);
3796 if (data->start_class->flags & ANYOF_LOCALE)
3797 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3799 for (value = 0; value < 256; value++)
3801 ANYOF_BITMAP_SET(data->start_class, value);
3806 if (flags & SCF_DO_STCLASS_AND) {
3807 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3808 for (value = 0; value < 256; value++)
3810 ANYOF_BITMAP_CLEAR(data->start_class, value);
3813 if (data->start_class->flags & ANYOF_LOCALE)
3814 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3816 for (value = 0; value < 256; value++)
3817 if (!isDIGIT(value))
3818 ANYOF_BITMAP_SET(data->start_class, value);
3822 CASE_SYNST_FNC(VERTWS);
3823 CASE_SYNST_FNC(HORIZWS);
3826 if (flags & SCF_DO_STCLASS_OR)
3827 cl_and(data->start_class, and_withp);
3828 flags &= ~SCF_DO_STCLASS;