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
93 # if defined(BUGGY_MSC6)
94 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
95 # pragma optimize("a",off)
96 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
97 # pragma optimize("w",on )
98 # endif /* BUGGY_MSC6 */
102 #define STATIC static
105 typedef struct RExC_state_t {
106 U32 flags; /* are we folding, multilining? */
107 char *precomp; /* uncompiled string. */
108 REGEXP *rx_sv; /* The SV that is the regexp. */
109 regexp *rx; /* perl core regexp structure */
110 regexp_internal *rxi; /* internal data for regexp object pprivate field */
111 char *start; /* Start of input for compile */
112 char *end; /* End of input for compile */
113 char *parse; /* Input-scan pointer. */
114 I32 whilem_seen; /* number of WHILEM in this expr */
115 regnode *emit_start; /* Start of emitted-code area */
116 regnode *emit_bound; /* First regnode outside of the allocated space */
117 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
118 I32 naughty; /* How bad is this pattern? */
119 I32 sawback; /* Did we see \1, ...? */
121 I32 size; /* Code size. */
122 I32 npar; /* Capture buffer count, (OPEN). */
123 I32 cpar; /* Capture buffer count, (CLOSE). */
124 I32 nestroot; /* root parens we are in - used by accept */
128 regnode **open_parens; /* pointers to open parens */
129 regnode **close_parens; /* pointers to close parens */
130 regnode *opend; /* END node in program */
131 I32 utf8; /* whether the pattern is utf8 or not */
132 I32 orig_utf8; /* whether the pattern was originally in utf8 */
133 /* XXX use this for future optimisation of case
134 * where pattern must be upgraded to utf8. */
135 HV *paren_names; /* Paren names */
137 regnode **recurse; /* Recurse regops */
138 I32 recurse_count; /* Number of recurse regops */
140 char *starttry; /* -Dr: where regtry was called. */
141 #define RExC_starttry (pRExC_state->starttry)
144 const char *lastparse;
146 AV *paren_name_list; /* idx -> name */
147 #define RExC_lastparse (pRExC_state->lastparse)
148 #define RExC_lastnum (pRExC_state->lastnum)
149 #define RExC_paren_name_list (pRExC_state->paren_name_list)
153 #define RExC_flags (pRExC_state->flags)
154 #define RExC_precomp (pRExC_state->precomp)
155 #define RExC_rx_sv (pRExC_state->rx_sv)
156 #define RExC_rx (pRExC_state->rx)
157 #define RExC_rxi (pRExC_state->rxi)
158 #define RExC_start (pRExC_state->start)
159 #define RExC_end (pRExC_state->end)
160 #define RExC_parse (pRExC_state->parse)
161 #define RExC_whilem_seen (pRExC_state->whilem_seen)
162 #ifdef RE_TRACK_PATTERN_OFFSETS
163 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
165 #define RExC_emit (pRExC_state->emit)
166 #define RExC_emit_start (pRExC_state->emit_start)
167 #define RExC_emit_bound (pRExC_state->emit_bound)
168 #define RExC_naughty (pRExC_state->naughty)
169 #define RExC_sawback (pRExC_state->sawback)
170 #define RExC_seen (pRExC_state->seen)
171 #define RExC_size (pRExC_state->size)
172 #define RExC_npar (pRExC_state->npar)
173 #define RExC_nestroot (pRExC_state->nestroot)
174 #define RExC_extralen (pRExC_state->extralen)
175 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
176 #define RExC_seen_evals (pRExC_state->seen_evals)
177 #define RExC_utf8 (pRExC_state->utf8)
178 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
179 #define RExC_open_parens (pRExC_state->open_parens)
180 #define RExC_close_parens (pRExC_state->close_parens)
181 #define RExC_opend (pRExC_state->opend)
182 #define RExC_paren_names (pRExC_state->paren_names)
183 #define RExC_recurse (pRExC_state->recurse)
184 #define RExC_recurse_count (pRExC_state->recurse_count)
187 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
188 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
189 ((*s) == '{' && regcurly(s)))
192 #undef SPSTART /* dratted cpp namespace... */
195 * Flags to be passed up and down.
197 #define WORST 0 /* Worst case. */
198 #define HASWIDTH 0x01 /* Known to match non-null strings. */
200 /* Simple enough to be STAR/PLUS operand, in an EXACT node must be a single
201 * character, and if utf8, must be invariant. */
203 #define SPSTART 0x04 /* Starts with * or +. */
204 #define TRYAGAIN 0x08 /* Weeded out a declaration. */
205 #define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
207 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
209 /* whether trie related optimizations are enabled */
210 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
211 #define TRIE_STUDY_OPT
212 #define FULL_TRIE_STUDY
218 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
219 #define PBITVAL(paren) (1 << ((paren) & 7))
220 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
221 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
222 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
224 /* If not already in utf8, do a longjmp back to the beginning */
225 #define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
226 #define REQUIRE_UTF8 STMT_START { \
227 if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
230 /* About scan_data_t.
232 During optimisation we recurse through the regexp program performing
233 various inplace (keyhole style) optimisations. In addition study_chunk
234 and scan_commit populate this data structure with information about
235 what strings MUST appear in the pattern. We look for the longest
236 string that must appear for at a fixed location, and we look for the
237 longest string that may appear at a floating location. So for instance
242 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
243 strings (because they follow a .* construct). study_chunk will identify
244 both FOO and BAR as being the longest fixed and floating strings respectively.
246 The strings can be composites, for instance
250 will result in a composite fixed substring 'foo'.
252 For each string some basic information is maintained:
254 - offset or min_offset
255 This is the position the string must appear at, or not before.
256 It also implicitly (when combined with minlenp) tells us how many
257 character must match before the string we are searching.
258 Likewise when combined with minlenp and the length of the string
259 tells us how many characters must appear after the string we have
263 Only used for floating strings. This is the rightmost point that
264 the string can appear at. Ifset to I32 max it indicates that the
265 string can occur infinitely far to the right.
268 A pointer to the minimum length of the pattern that the string
269 was found inside. This is important as in the case of positive
270 lookahead or positive lookbehind we can have multiple patterns
275 The minimum length of the pattern overall is 3, the minimum length
276 of the lookahead part is 3, but the minimum length of the part that
277 will actually match is 1. So 'FOO's minimum length is 3, but the
278 minimum length for the F is 1. This is important as the minimum length
279 is used to determine offsets in front of and behind the string being
280 looked for. Since strings can be composites this is the length of the
281 pattern at the time it was commited with a scan_commit. Note that
282 the length is calculated by study_chunk, so that the minimum lengths
283 are not known until the full pattern has been compiled, thus the
284 pointer to the value.
288 In the case of lookbehind the string being searched for can be
289 offset past the start point of the final matching string.
290 If this value was just blithely removed from the min_offset it would
291 invalidate some of the calculations for how many chars must match
292 before or after (as they are derived from min_offset and minlen and
293 the length of the string being searched for).
294 When the final pattern is compiled and the data is moved from the
295 scan_data_t structure into the regexp structure the information
296 about lookbehind is factored in, with the information that would
297 have been lost precalculated in the end_shift field for the
300 The fields pos_min and pos_delta are used to store the minimum offset
301 and the delta to the maximum offset at the current point in the pattern.
305 typedef struct scan_data_t {
306 /*I32 len_min; unused */
307 /*I32 len_delta; unused */
311 I32 last_end; /* min value, <0 unless valid. */
314 SV **longest; /* Either &l_fixed, or &l_float. */
315 SV *longest_fixed; /* longest fixed string found in pattern */
316 I32 offset_fixed; /* offset where it starts */
317 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
318 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
319 SV *longest_float; /* longest floating string found in pattern */
320 I32 offset_float_min; /* earliest point in string it can appear */
321 I32 offset_float_max; /* latest point in string it can appear */
322 I32 *minlen_float; /* pointer to the minlen relevent to the string */
323 I32 lookbehind_float; /* is the position of the string modified by LB */
327 struct regnode_charclass_class *start_class;
331 * Forward declarations for pregcomp()'s friends.
334 static const scan_data_t zero_scan_data =
335 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
337 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
338 #define SF_BEFORE_SEOL 0x0001
339 #define SF_BEFORE_MEOL 0x0002
340 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
341 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
344 # define SF_FIX_SHIFT_EOL (0+2)
345 # define SF_FL_SHIFT_EOL (0+4)
347 # define SF_FIX_SHIFT_EOL (+2)
348 # define SF_FL_SHIFT_EOL (+4)
351 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
352 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
354 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
355 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
356 #define SF_IS_INF 0x0040
357 #define SF_HAS_PAR 0x0080
358 #define SF_IN_PAR 0x0100
359 #define SF_HAS_EVAL 0x0200
360 #define SCF_DO_SUBSTR 0x0400
361 #define SCF_DO_STCLASS_AND 0x0800
362 #define SCF_DO_STCLASS_OR 0x1000
363 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
364 #define SCF_WHILEM_VISITED_POS 0x2000
366 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
367 #define SCF_SEEN_ACCEPT 0x8000
369 #define UTF (RExC_utf8 != 0)
370 #define LOC ((RExC_flags & RXf_PMf_LOCALE) != 0)
371 #define FOLD ((RExC_flags & RXf_PMf_FOLD) != 0)
373 #define OOB_UNICODE 12345678
374 #define OOB_NAMEDCLASS -1
376 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
377 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
380 /* length of regex to show in messages that don't mark a position within */
381 #define RegexLengthToShowInErrorMessages 127
384 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
385 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
386 * op/pragma/warn/regcomp.
388 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
389 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
391 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
394 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
395 * arg. Show regex, up to a maximum length. If it's too long, chop and add
398 #define _FAIL(code) STMT_START { \
399 const char *ellipses = ""; \
400 IV len = RExC_end - RExC_precomp; \
403 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
404 if (len > RegexLengthToShowInErrorMessages) { \
405 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
406 len = RegexLengthToShowInErrorMessages - 10; \
412 #define FAIL(msg) _FAIL( \
413 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
414 msg, (int)len, RExC_precomp, ellipses))
416 #define FAIL2(msg,arg) _FAIL( \
417 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
418 arg, (int)len, RExC_precomp, ellipses))
421 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
423 #define Simple_vFAIL(m) STMT_START { \
424 const IV offset = RExC_parse - RExC_precomp; \
425 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
426 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
430 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
432 #define vFAIL(m) STMT_START { \
434 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
439 * Like Simple_vFAIL(), but accepts two arguments.
441 #define Simple_vFAIL2(m,a1) STMT_START { \
442 const IV offset = RExC_parse - RExC_precomp; \
443 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
444 (int)offset, RExC_precomp, RExC_precomp + offset); \
448 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
450 #define vFAIL2(m,a1) STMT_START { \
452 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
453 Simple_vFAIL2(m, a1); \
458 * Like Simple_vFAIL(), but accepts three arguments.
460 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
461 const IV offset = RExC_parse - RExC_precomp; \
462 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
463 (int)offset, RExC_precomp, RExC_precomp + offset); \
467 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
469 #define vFAIL3(m,a1,a2) STMT_START { \
471 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
472 Simple_vFAIL3(m, a1, a2); \
476 * Like Simple_vFAIL(), but accepts four arguments.
478 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
479 const IV offset = RExC_parse - RExC_precomp; \
480 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
481 (int)offset, RExC_precomp, RExC_precomp + offset); \
484 #define ckWARNreg(loc,m) STMT_START { \
485 const IV offset = loc - RExC_precomp; \
486 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
487 (int)offset, RExC_precomp, RExC_precomp + offset); \
490 #define ckWARNregdep(loc,m) STMT_START { \
491 const IV offset = loc - RExC_precomp; \
492 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
494 (int)offset, RExC_precomp, RExC_precomp + offset); \
497 #define ckWARN2reg(loc, m, a1) STMT_START { \
498 const IV offset = loc - RExC_precomp; \
499 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
500 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
503 #define vWARN3(loc, m, a1, a2) STMT_START { \
504 const IV offset = loc - RExC_precomp; \
505 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
506 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
509 #define ckWARN3reg(loc, m, a1, a2) STMT_START { \
510 const IV offset = loc - RExC_precomp; \
511 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
512 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
515 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
516 const IV offset = loc - RExC_precomp; \
517 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
518 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
521 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
522 const IV offset = loc - RExC_precomp; \
523 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
524 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
527 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
528 const IV offset = loc - RExC_precomp; \
529 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
530 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
534 /* Allow for side effects in s */
535 #define REGC(c,s) STMT_START { \
536 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
539 /* Macros for recording node offsets. 20001227 mjd@plover.com
540 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
541 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
542 * Element 0 holds the number n.
543 * Position is 1 indexed.
545 #ifndef RE_TRACK_PATTERN_OFFSETS
546 #define Set_Node_Offset_To_R(node,byte)
547 #define Set_Node_Offset(node,byte)
548 #define Set_Cur_Node_Offset
549 #define Set_Node_Length_To_R(node,len)
550 #define Set_Node_Length(node,len)
551 #define Set_Node_Cur_Length(node)
552 #define Node_Offset(n)
553 #define Node_Length(n)
554 #define Set_Node_Offset_Length(node,offset,len)
555 #define ProgLen(ri) ri->u.proglen
556 #define SetProgLen(ri,x) ri->u.proglen = x
558 #define ProgLen(ri) ri->u.offsets[0]
559 #define SetProgLen(ri,x) ri->u.offsets[0] = x
560 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
562 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
563 __LINE__, (int)(node), (int)(byte))); \
565 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
567 RExC_offsets[2*(node)-1] = (byte); \
572 #define Set_Node_Offset(node,byte) \
573 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
574 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
576 #define Set_Node_Length_To_R(node,len) STMT_START { \
578 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
579 __LINE__, (int)(node), (int)(len))); \
581 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
583 RExC_offsets[2*(node)] = (len); \
588 #define Set_Node_Length(node,len) \
589 Set_Node_Length_To_R((node)-RExC_emit_start, len)
590 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
591 #define Set_Node_Cur_Length(node) \
592 Set_Node_Length(node, RExC_parse - parse_start)
594 /* Get offsets and lengths */
595 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
596 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
598 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
599 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
600 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
604 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
605 #define EXPERIMENTAL_INPLACESCAN
606 #endif /*RE_TRACK_PATTERN_OFFSETS*/
608 #define DEBUG_STUDYDATA(str,data,depth) \
609 DEBUG_OPTIMISE_MORE_r(if(data){ \
610 PerlIO_printf(Perl_debug_log, \
611 "%*s" str "Pos:%"IVdf"/%"IVdf \
612 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
613 (int)(depth)*2, "", \
614 (IV)((data)->pos_min), \
615 (IV)((data)->pos_delta), \
616 (UV)((data)->flags), \
617 (IV)((data)->whilem_c), \
618 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
619 is_inf ? "INF " : "" \
621 if ((data)->last_found) \
622 PerlIO_printf(Perl_debug_log, \
623 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
624 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
625 SvPVX_const((data)->last_found), \
626 (IV)((data)->last_end), \
627 (IV)((data)->last_start_min), \
628 (IV)((data)->last_start_max), \
629 ((data)->longest && \
630 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
631 SvPVX_const((data)->longest_fixed), \
632 (IV)((data)->offset_fixed), \
633 ((data)->longest && \
634 (data)->longest==&((data)->longest_float)) ? "*" : "", \
635 SvPVX_const((data)->longest_float), \
636 (IV)((data)->offset_float_min), \
637 (IV)((data)->offset_float_max) \
639 PerlIO_printf(Perl_debug_log,"\n"); \
642 static void clear_re(pTHX_ void *r);
644 /* Mark that we cannot extend a found fixed substring at this point.
645 Update the longest found anchored substring and the longest found
646 floating substrings if needed. */
649 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
651 const STRLEN l = CHR_SVLEN(data->last_found);
652 const STRLEN old_l = CHR_SVLEN(*data->longest);
653 GET_RE_DEBUG_FLAGS_DECL;
655 PERL_ARGS_ASSERT_SCAN_COMMIT;
657 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
658 SvSetMagicSV(*data->longest, data->last_found);
659 if (*data->longest == data->longest_fixed) {
660 data->offset_fixed = l ? data->last_start_min : data->pos_min;
661 if (data->flags & SF_BEFORE_EOL)
663 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
665 data->flags &= ~SF_FIX_BEFORE_EOL;
666 data->minlen_fixed=minlenp;
667 data->lookbehind_fixed=0;
669 else { /* *data->longest == data->longest_float */
670 data->offset_float_min = l ? data->last_start_min : data->pos_min;
671 data->offset_float_max = (l
672 ? data->last_start_max
673 : data->pos_min + data->pos_delta);
674 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
675 data->offset_float_max = I32_MAX;
676 if (data->flags & SF_BEFORE_EOL)
678 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
680 data->flags &= ~SF_FL_BEFORE_EOL;
681 data->minlen_float=minlenp;
682 data->lookbehind_float=0;
685 SvCUR_set(data->last_found, 0);
687 SV * const sv = data->last_found;
688 if (SvUTF8(sv) && SvMAGICAL(sv)) {
689 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
695 data->flags &= ~SF_BEFORE_EOL;
696 DEBUG_STUDYDATA("commit: ",data,0);
699 /* Can match anything (initialization) */
701 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
703 PERL_ARGS_ASSERT_CL_ANYTHING;
705 ANYOF_CLASS_ZERO(cl);
706 ANYOF_BITMAP_SETALL(cl);
707 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
709 cl->flags |= ANYOF_LOCALE;
712 /* Can match anything (initialization) */
714 S_cl_is_anything(const struct regnode_charclass_class *cl)
718 PERL_ARGS_ASSERT_CL_IS_ANYTHING;
720 for (value = 0; value <= ANYOF_MAX; value += 2)
721 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
723 if (!(cl->flags & ANYOF_UNICODE_ALL))
725 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
730 /* Can match anything (initialization) */
732 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
734 PERL_ARGS_ASSERT_CL_INIT;
736 Zero(cl, 1, struct regnode_charclass_class);
738 cl_anything(pRExC_state, cl);
742 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
744 PERL_ARGS_ASSERT_CL_INIT_ZERO;
746 Zero(cl, 1, struct regnode_charclass_class);
748 cl_anything(pRExC_state, cl);
750 cl->flags |= ANYOF_LOCALE;
753 /* 'And' a given class with another one. Can create false positives */
754 /* We assume that cl is not inverted */
756 S_cl_and(struct regnode_charclass_class *cl,
757 const struct regnode_charclass_class *and_with)
759 PERL_ARGS_ASSERT_CL_AND;
761 assert(and_with->type == ANYOF);
762 if (!(and_with->flags & ANYOF_CLASS)
763 && !(cl->flags & ANYOF_CLASS)
764 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
765 && !(and_with->flags & ANYOF_FOLD)
766 && !(cl->flags & ANYOF_FOLD)) {
769 if (and_with->flags & ANYOF_INVERT)
770 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
771 cl->bitmap[i] &= ~and_with->bitmap[i];
773 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
774 cl->bitmap[i] &= and_with->bitmap[i];
775 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
776 if (!(and_with->flags & ANYOF_EOS))
777 cl->flags &= ~ANYOF_EOS;
779 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
780 !(and_with->flags & ANYOF_INVERT)) {
781 cl->flags &= ~ANYOF_UNICODE_ALL;
782 cl->flags |= ANYOF_UNICODE;
783 ARG_SET(cl, ARG(and_with));
785 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
786 !(and_with->flags & ANYOF_INVERT))
787 cl->flags &= ~ANYOF_UNICODE_ALL;
788 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
789 !(and_with->flags & ANYOF_INVERT))
790 cl->flags &= ~ANYOF_UNICODE;
793 /* 'OR' a given class with another one. Can create false positives */
794 /* We assume that cl is not inverted */
796 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
798 PERL_ARGS_ASSERT_CL_OR;
800 if (or_with->flags & ANYOF_INVERT) {
802 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
803 * <= (B1 | !B2) | (CL1 | !CL2)
804 * which is wasteful if CL2 is small, but we ignore CL2:
805 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
806 * XXXX Can we handle case-fold? Unclear:
807 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
808 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
810 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
811 && !(or_with->flags & ANYOF_FOLD)
812 && !(cl->flags & ANYOF_FOLD) ) {
815 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
816 cl->bitmap[i] |= ~or_with->bitmap[i];
817 } /* XXXX: logic is complicated otherwise */
819 cl_anything(pRExC_state, cl);
822 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
823 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
824 && (!(or_with->flags & ANYOF_FOLD)
825 || (cl->flags & ANYOF_FOLD)) ) {
828 /* OR char bitmap and class bitmap separately */
829 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
830 cl->bitmap[i] |= or_with->bitmap[i];
831 if (or_with->flags & ANYOF_CLASS) {
832 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
833 cl->classflags[i] |= or_with->classflags[i];
834 cl->flags |= ANYOF_CLASS;
837 else { /* XXXX: logic is complicated, leave it along for a moment. */
838 cl_anything(pRExC_state, cl);
841 if (or_with->flags & ANYOF_EOS)
842 cl->flags |= ANYOF_EOS;
844 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
845 ARG(cl) != ARG(or_with)) {
846 cl->flags |= ANYOF_UNICODE_ALL;
847 cl->flags &= ~ANYOF_UNICODE;
849 if (or_with->flags & ANYOF_UNICODE_ALL) {
850 cl->flags |= ANYOF_UNICODE_ALL;
851 cl->flags &= ~ANYOF_UNICODE;
855 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
856 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
857 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
858 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
863 dump_trie(trie,widecharmap,revcharmap)
864 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
865 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
867 These routines dump out a trie in a somewhat readable format.
868 The _interim_ variants are used for debugging the interim
869 tables that are used to generate the final compressed
870 representation which is what dump_trie expects.
872 Part of the reason for their existance is to provide a form
873 of documentation as to how the different representations function.
878 Dumps the final compressed table form of the trie to Perl_debug_log.
879 Used for debugging make_trie().
883 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
884 AV *revcharmap, U32 depth)
887 SV *sv=sv_newmortal();
888 int colwidth= widecharmap ? 6 : 4;
890 GET_RE_DEBUG_FLAGS_DECL;
892 PERL_ARGS_ASSERT_DUMP_TRIE;
894 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
895 (int)depth * 2 + 2,"",
896 "Match","Base","Ofs" );
898 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
899 SV ** const tmp = av_fetch( revcharmap, state, 0);
901 PerlIO_printf( Perl_debug_log, "%*s",
903 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
904 PL_colors[0], PL_colors[1],
905 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
906 PERL_PV_ESCAPE_FIRSTCHAR
911 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
912 (int)depth * 2 + 2,"");
914 for( state = 0 ; state < trie->uniquecharcount ; state++ )
915 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
916 PerlIO_printf( Perl_debug_log, "\n");
918 for( state = 1 ; state < trie->statecount ; state++ ) {
919 const U32 base = trie->states[ state ].trans.base;
921 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
923 if ( trie->states[ state ].wordnum ) {
924 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
926 PerlIO_printf( Perl_debug_log, "%6s", "" );
929 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
934 while( ( base + ofs < trie->uniquecharcount ) ||
935 ( base + ofs - trie->uniquecharcount < trie->lasttrans
936 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
939 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
941 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
942 if ( ( base + ofs >= trie->uniquecharcount ) &&
943 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
944 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
946 PerlIO_printf( Perl_debug_log, "%*"UVXf,
948 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
950 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
954 PerlIO_printf( Perl_debug_log, "]");
957 PerlIO_printf( Perl_debug_log, "\n" );
959 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
960 for (word=1; word <= trie->wordcount; word++) {
961 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
962 (int)word, (int)(trie->wordinfo[word].prev),
963 (int)(trie->wordinfo[word].len));
965 PerlIO_printf(Perl_debug_log, "\n" );
968 Dumps a fully constructed but uncompressed trie in list form.
969 List tries normally only are used for construction when the number of
970 possible chars (trie->uniquecharcount) is very high.
971 Used for debugging make_trie().
974 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
975 HV *widecharmap, AV *revcharmap, U32 next_alloc,
979 SV *sv=sv_newmortal();
980 int colwidth= widecharmap ? 6 : 4;
981 GET_RE_DEBUG_FLAGS_DECL;
983 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
985 /* print out the table precompression. */
986 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
987 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
988 "------:-----+-----------------\n" );
990 for( state=1 ; state < next_alloc ; state ++ ) {
993 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
994 (int)depth * 2 + 2,"", (UV)state );
995 if ( ! trie->states[ state ].wordnum ) {
996 PerlIO_printf( Perl_debug_log, "%5s| ","");
998 PerlIO_printf( Perl_debug_log, "W%4x| ",
999 trie->states[ state ].wordnum
1002 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1003 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
1005 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1007 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1008 PL_colors[0], PL_colors[1],
1009 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1010 PERL_PV_ESCAPE_FIRSTCHAR
1012 TRIE_LIST_ITEM(state,charid).forid,
1013 (UV)TRIE_LIST_ITEM(state,charid).newstate
1016 PerlIO_printf(Perl_debug_log, "\n%*s| ",
1017 (int)((depth * 2) + 14), "");
1020 PerlIO_printf( Perl_debug_log, "\n");
1025 Dumps a fully constructed but uncompressed trie in table form.
1026 This is the normal DFA style state transition table, with a few
1027 twists to facilitate compression later.
1028 Used for debugging make_trie().
1031 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1032 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1037 SV *sv=sv_newmortal();
1038 int colwidth= widecharmap ? 6 : 4;
1039 GET_RE_DEBUG_FLAGS_DECL;
1041 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1044 print out the table precompression so that we can do a visual check
1045 that they are identical.
1048 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1050 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1051 SV ** const tmp = av_fetch( revcharmap, charid, 0);
1053 PerlIO_printf( Perl_debug_log, "%*s",
1055 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1056 PL_colors[0], PL_colors[1],
1057 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1058 PERL_PV_ESCAPE_FIRSTCHAR
1064 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1066 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1067 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1070 PerlIO_printf( Perl_debug_log, "\n" );
1072 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1074 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1075 (int)depth * 2 + 2,"",
1076 (UV)TRIE_NODENUM( state ) );
1078 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1079 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1081 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1083 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1085 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1086 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1088 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1089 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1097 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1098 startbranch: the first branch in the whole branch sequence
1099 first : start branch of sequence of branch-exact nodes.
1100 May be the same as startbranch
1101 last : Thing following the last branch.
1102 May be the same as tail.
1103 tail : item following the branch sequence
1104 count : words in the sequence
1105 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1106 depth : indent depth
1108 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1110 A trie is an N'ary tree where the branches are determined by digital
1111 decomposition of the key. IE, at the root node you look up the 1st character and
1112 follow that branch repeat until you find the end of the branches. Nodes can be
1113 marked as "accepting" meaning they represent a complete word. Eg:
1117 would convert into the following structure. Numbers represent states, letters
1118 following numbers represent valid transitions on the letter from that state, if
1119 the number is in square brackets it represents an accepting state, otherwise it
1120 will be in parenthesis.
1122 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1126 (1) +-i->(6)-+-s->[7]
1128 +-s->(3)-+-h->(4)-+-e->[5]
1130 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1132 This shows that when matching against the string 'hers' we will begin at state 1
1133 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1134 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1135 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1136 single traverse. We store a mapping from accepting to state to which word was
1137 matched, and then when we have multiple possibilities we try to complete the
1138 rest of the regex in the order in which they occured in the alternation.
1140 The only prior NFA like behaviour that would be changed by the TRIE support is
1141 the silent ignoring of duplicate alternations which are of the form:
1143 / (DUPE|DUPE) X? (?{ ... }) Y /x
1145 Thus EVAL blocks follwing a trie may be called a different number of times with
1146 and without the optimisation. With the optimisations dupes will be silently
1147 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1148 the following demonstrates:
1150 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1152 which prints out 'word' three times, but
1154 'words'=~/(word|word|word)(?{ print $1 })S/
1156 which doesnt print it out at all. This is due to other optimisations kicking in.
1158 Example of what happens on a structural level:
1160 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1162 1: CURLYM[1] {1,32767}(18)
1173 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1174 and should turn into:
1176 1: CURLYM[1] {1,32767}(18)
1178 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1186 Cases where tail != last would be like /(?foo|bar)baz/:
1196 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1197 and would end up looking like:
1200 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1207 d = uvuni_to_utf8_flags(d, uv, 0);
1209 is the recommended Unicode-aware way of saying
1214 #define TRIE_STORE_REVCHAR \
1217 SV *zlopp = newSV(2); \
1218 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
1219 unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
1220 SvCUR_set(zlopp, kapow - flrbbbbb); \
1223 av_push(revcharmap, zlopp); \
1225 char ooooff = (char)uvc; \
1226 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
1230 #define TRIE_READ_CHAR STMT_START { \
1234 if ( foldlen > 0 ) { \
1235 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1240 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1241 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1242 foldlen -= UNISKIP( uvc ); \
1243 scan = foldbuf + UNISKIP( uvc ); \
1246 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1256 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1257 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1258 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1259 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1261 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1262 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1263 TRIE_LIST_CUR( state )++; \
1266 #define TRIE_LIST_NEW(state) STMT_START { \
1267 Newxz( trie->states[ state ].trans.list, \
1268 4, reg_trie_trans_le ); \
1269 TRIE_LIST_CUR( state ) = 1; \
1270 TRIE_LIST_LEN( state ) = 4; \
1273 #define TRIE_HANDLE_WORD(state) STMT_START { \
1274 U16 dupe= trie->states[ state ].wordnum; \
1275 regnode * const noper_next = regnext( noper ); \
1278 /* store the word for dumping */ \
1280 if (OP(noper) != NOTHING) \
1281 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
1283 tmp = newSVpvn_utf8( "", 0, UTF ); \
1284 av_push( trie_words, tmp ); \
1288 trie->wordinfo[curword].prev = 0; \
1289 trie->wordinfo[curword].len = wordlen; \
1290 trie->wordinfo[curword].accept = state; \
1292 if ( noper_next < tail ) { \
1294 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1295 trie->jump[curword] = (U16)(noper_next - convert); \
1297 jumper = noper_next; \
1299 nextbranch= regnext(cur); \
1303 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
1304 /* chain, so that when the bits of chain are later */\
1305 /* linked together, the dups appear in the chain */\
1306 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1307 trie->wordinfo[dupe].prev = curword; \
1309 /* we haven't inserted this word yet. */ \
1310 trie->states[ state ].wordnum = curword; \
1315 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1316 ( ( base + charid >= ucharcount \
1317 && base + charid < ubound \
1318 && state == trie->trans[ base - ucharcount + charid ].check \
1319 && trie->trans[ base - ucharcount + charid ].next ) \
1320 ? trie->trans[ base - ucharcount + charid ].next \
1321 : ( state==1 ? special : 0 ) \
1325 #define MADE_JUMP_TRIE 2
1326 #define MADE_EXACT_TRIE 4
1329 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1332 /* first pass, loop through and scan words */
1333 reg_trie_data *trie;
1334 HV *widecharmap = NULL;
1335 AV *revcharmap = newAV();
1337 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1342 regnode *jumper = NULL;
1343 regnode *nextbranch = NULL;
1344 regnode *convert = NULL;
1345 U32 *prev_states; /* temp array mapping each state to previous one */
1346 /* we just use folder as a flag in utf8 */
1347 const U8 * const folder = ( flags == EXACTF
1349 : ( flags == EXACTFL
1356 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1357 AV *trie_words = NULL;
1358 /* along with revcharmap, this only used during construction but both are
1359 * useful during debugging so we store them in the struct when debugging.
1362 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1363 STRLEN trie_charcount=0;
1365 SV *re_trie_maxbuff;
1366 GET_RE_DEBUG_FLAGS_DECL;
1368 PERL_ARGS_ASSERT_MAKE_TRIE;
1370 PERL_UNUSED_ARG(depth);
1373 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1375 trie->startstate = 1;
1376 trie->wordcount = word_count;
1377 RExC_rxi->data->data[ data_slot ] = (void*)trie;
1378 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1379 if (!(UTF && folder))
1380 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1381 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1382 trie->wordcount+1, sizeof(reg_trie_wordinfo));
1385 trie_words = newAV();
1388 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1389 if (!SvIOK(re_trie_maxbuff)) {
1390 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1393 PerlIO_printf( Perl_debug_log,
1394 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1395 (int)depth * 2 + 2, "",
1396 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1397 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1401 /* Find the node we are going to overwrite */
1402 if ( first == startbranch && OP( last ) != BRANCH ) {
1403 /* whole branch chain */
1406 /* branch sub-chain */
1407 convert = NEXTOPER( first );
1410 /* -- First loop and Setup --
1412 We first traverse the branches and scan each word to determine if it
1413 contains widechars, and how many unique chars there are, this is
1414 important as we have to build a table with at least as many columns as we
1417 We use an array of integers to represent the character codes 0..255
1418 (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1419 native representation of the character value as the key and IV's for the
1422 *TODO* If we keep track of how many times each character is used we can
1423 remap the columns so that the table compression later on is more
1424 efficient in terms of memory by ensuring most common value is in the
1425 middle and the least common are on the outside. IMO this would be better
1426 than a most to least common mapping as theres a decent chance the most
1427 common letter will share a node with the least common, meaning the node
1428 will not be compressable. With a middle is most common approach the worst
1429 case is when we have the least common nodes twice.
1433 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1434 regnode * const noper = NEXTOPER( cur );
1435 const U8 *uc = (U8*)STRING( noper );
1436 const U8 * const e = uc + STR_LEN( noper );
1438 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1439 const U8 *scan = (U8*)NULL;
1440 U32 wordlen = 0; /* required init */
1442 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1444 if (OP(noper) == NOTHING) {
1448 if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
1449 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1450 regardless of encoding */
1452 for ( ; uc < e ; uc += len ) {
1453 TRIE_CHARCOUNT(trie)++;
1457 if ( !trie->charmap[ uvc ] ) {
1458 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1460 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1464 /* store the codepoint in the bitmap, and if its ascii
1465 also store its folded equivelent. */
1466 TRIE_BITMAP_SET(trie,uvc);
1468 /* store the folded codepoint */
1469 if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
1472 /* store first byte of utf8 representation of
1473 codepoints in the 127 < uvc < 256 range */
1474 if (127 < uvc && uvc < 192) {
1475 TRIE_BITMAP_SET(trie,194);
1476 } else if (191 < uvc ) {
1477 TRIE_BITMAP_SET(trie,195);
1478 /* && uvc < 256 -- we know uvc is < 256 already */
1481 set_bit = 0; /* We've done our bit :-) */
1486 widecharmap = newHV();
1488 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1491 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1493 if ( !SvTRUE( *svpp ) ) {
1494 sv_setiv( *svpp, ++trie->uniquecharcount );
1499 if( cur == first ) {
1502 } else if (chars < trie->minlen) {
1504 } else if (chars > trie->maxlen) {
1508 } /* end first pass */
1509 DEBUG_TRIE_COMPILE_r(
1510 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1511 (int)depth * 2 + 2,"",
1512 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1513 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1514 (int)trie->minlen, (int)trie->maxlen )
1518 We now know what we are dealing with in terms of unique chars and
1519 string sizes so we can calculate how much memory a naive
1520 representation using a flat table will take. If it's over a reasonable
1521 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1522 conservative but potentially much slower representation using an array
1525 At the end we convert both representations into the same compressed
1526 form that will be used in regexec.c for matching with. The latter
1527 is a form that cannot be used to construct with but has memory
1528 properties similar to the list form and access properties similar
1529 to the table form making it both suitable for fast searches and
1530 small enough that its feasable to store for the duration of a program.
1532 See the comment in the code where the compressed table is produced
1533 inplace from the flat tabe representation for an explanation of how
1534 the compression works.
1539 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1542 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1544 Second Pass -- Array Of Lists Representation
1546 Each state will be represented by a list of charid:state records
1547 (reg_trie_trans_le) the first such element holds the CUR and LEN
1548 points of the allocated array. (See defines above).
1550 We build the initial structure using the lists, and then convert
1551 it into the compressed table form which allows faster lookups
1552 (but cant be modified once converted).
1555 STRLEN transcount = 1;
1557 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1558 "%*sCompiling trie using list compiler\n",
1559 (int)depth * 2 + 2, ""));
1561 trie->states = (reg_trie_state *)
1562 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1563 sizeof(reg_trie_state) );
1567 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1569 regnode * const noper = NEXTOPER( cur );
1570 U8 *uc = (U8*)STRING( noper );
1571 const U8 * const e = uc + STR_LEN( noper );
1572 U32 state = 1; /* required init */
1573 U16 charid = 0; /* sanity init */
1574 U8 *scan = (U8*)NULL; /* sanity init */
1575 STRLEN foldlen = 0; /* required init */
1576 U32 wordlen = 0; /* required init */
1577 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1579 if (OP(noper) != NOTHING) {
1580 for ( ; uc < e ; uc += len ) {
1585 charid = trie->charmap[ uvc ];
1587 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1591 charid=(U16)SvIV( *svpp );
1594 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1601 if ( !trie->states[ state ].trans.list ) {
1602 TRIE_LIST_NEW( state );
1604 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1605 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1606 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1611 newstate = next_alloc++;
1612 prev_states[newstate] = state;
1613 TRIE_LIST_PUSH( state, charid, newstate );
1618 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1622 TRIE_HANDLE_WORD(state);
1624 } /* end second pass */
1626 /* next alloc is the NEXT state to be allocated */
1627 trie->statecount = next_alloc;
1628 trie->states = (reg_trie_state *)
1629 PerlMemShared_realloc( trie->states,
1631 * sizeof(reg_trie_state) );
1633 /* and now dump it out before we compress it */
1634 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1635 revcharmap, next_alloc,
1639 trie->trans = (reg_trie_trans *)
1640 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1647 for( state=1 ; state < next_alloc ; state ++ ) {
1651 DEBUG_TRIE_COMPILE_MORE_r(
1652 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1656 if (trie->states[state].trans.list) {
1657 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1661 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1662 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1663 if ( forid < minid ) {
1665 } else if ( forid > maxid ) {
1669 if ( transcount < tp + maxid - minid + 1) {
1671 trie->trans = (reg_trie_trans *)
1672 PerlMemShared_realloc( trie->trans,
1674 * sizeof(reg_trie_trans) );
1675 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1677 base = trie->uniquecharcount + tp - minid;
1678 if ( maxid == minid ) {
1680 for ( ; zp < tp ; zp++ ) {
1681 if ( ! trie->trans[ zp ].next ) {
1682 base = trie->uniquecharcount + zp - minid;
1683 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1684 trie->trans[ zp ].check = state;
1690 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1691 trie->trans[ tp ].check = state;
1696 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1697 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1698 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1699 trie->trans[ tid ].check = state;
1701 tp += ( maxid - minid + 1 );
1703 Safefree(trie->states[ state ].trans.list);
1706 DEBUG_TRIE_COMPILE_MORE_r(
1707 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1710 trie->states[ state ].trans.base=base;
1712 trie->lasttrans = tp + 1;
1716 Second Pass -- Flat Table Representation.
1718 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1719 We know that we will need Charcount+1 trans at most to store the data
1720 (one row per char at worst case) So we preallocate both structures
1721 assuming worst case.
1723 We then construct the trie using only the .next slots of the entry
1726 We use the .check field of the first entry of the node temporarily to
1727 make compression both faster and easier by keeping track of how many non
1728 zero fields are in the node.
1730 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1733 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1734 number representing the first entry of the node, and state as a
1735 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1736 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1737 are 2 entrys per node. eg:
1745 The table is internally in the right hand, idx form. However as we also
1746 have to deal with the states array which is indexed by nodenum we have to
1747 use TRIE_NODENUM() to convert.
1750 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1751 "%*sCompiling trie using table compiler\n",
1752 (int)depth * 2 + 2, ""));
1754 trie->trans = (reg_trie_trans *)
1755 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1756 * trie->uniquecharcount + 1,
1757 sizeof(reg_trie_trans) );
1758 trie->states = (reg_trie_state *)
1759 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1760 sizeof(reg_trie_state) );
1761 next_alloc = trie->uniquecharcount + 1;
1764 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1766 regnode * const noper = NEXTOPER( cur );
1767 const U8 *uc = (U8*)STRING( noper );
1768 const U8 * const e = uc + STR_LEN( noper );
1770 U32 state = 1; /* required init */
1772 U16 charid = 0; /* sanity init */
1773 U32 accept_state = 0; /* sanity init */
1774 U8 *scan = (U8*)NULL; /* sanity init */
1776 STRLEN foldlen = 0; /* required init */
1777 U32 wordlen = 0; /* required init */
1778 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1780 if ( OP(noper) != NOTHING ) {
1781 for ( ; uc < e ; uc += len ) {
1786 charid = trie->charmap[ uvc ];
1788 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1789 charid = svpp ? (U16)SvIV(*svpp) : 0;
1793 if ( !trie->trans[ state + charid ].next ) {
1794 trie->trans[ state + charid ].next = next_alloc;
1795 trie->trans[ state ].check++;
1796 prev_states[TRIE_NODENUM(next_alloc)]
1797 = TRIE_NODENUM(state);
1798 next_alloc += trie->uniquecharcount;
1800 state = trie->trans[ state + charid ].next;
1802 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1804 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1807 accept_state = TRIE_NODENUM( state );
1808 TRIE_HANDLE_WORD(accept_state);
1810 } /* end second pass */
1812 /* and now dump it out before we compress it */
1813 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1815 next_alloc, depth+1));
1819 * Inplace compress the table.*
1821 For sparse data sets the table constructed by the trie algorithm will
1822 be mostly 0/FAIL transitions or to put it another way mostly empty.
1823 (Note that leaf nodes will not contain any transitions.)
1825 This algorithm compresses the tables by eliminating most such
1826 transitions, at the cost of a modest bit of extra work during lookup:
1828 - Each states[] entry contains a .base field which indicates the
1829 index in the state[] array wheres its transition data is stored.
1831 - If .base is 0 there are no valid transitions from that node.
1833 - If .base is nonzero then charid is added to it to find an entry in
1836 -If trans[states[state].base+charid].check!=state then the
1837 transition is taken to be a 0/Fail transition. Thus if there are fail
1838 transitions at the front of the node then the .base offset will point
1839 somewhere inside the previous nodes data (or maybe even into a node
1840 even earlier), but the .check field determines if the transition is
1844 The following process inplace converts the table to the compressed
1845 table: We first do not compress the root node 1,and mark its all its
1846 .check pointers as 1 and set its .base pointer as 1 as well. This
1847 allows to do a DFA construction from the compressed table later, and
1848 ensures that any .base pointers we calculate later are greater than
1851 - We set 'pos' to indicate the first entry of the second node.
1853 - We then iterate over the columns of the node, finding the first and
1854 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1855 and set the .check pointers accordingly, and advance pos
1856 appropriately and repreat for the next node. Note that when we copy
1857 the next pointers we have to convert them from the original
1858 NODEIDX form to NODENUM form as the former is not valid post
1861 - If a node has no transitions used we mark its base as 0 and do not
1862 advance the pos pointer.
1864 - If a node only has one transition we use a second pointer into the
1865 structure to fill in allocated fail transitions from other states.
1866 This pointer is independent of the main pointer and scans forward
1867 looking for null transitions that are allocated to a state. When it
1868 finds one it writes the single transition into the "hole". If the
1869 pointer doesnt find one the single transition is appended as normal.
1871 - Once compressed we can Renew/realloc the structures to release the
1874 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1875 specifically Fig 3.47 and the associated pseudocode.
1879 const U32 laststate = TRIE_NODENUM( next_alloc );
1882 trie->statecount = laststate;
1884 for ( state = 1 ; state < laststate ; state++ ) {
1886 const U32 stateidx = TRIE_NODEIDX( state );
1887 const U32 o_used = trie->trans[ stateidx ].check;
1888 U32 used = trie->trans[ stateidx ].check;
1889 trie->trans[ stateidx ].check = 0;
1891 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1892 if ( flag || trie->trans[ stateidx + charid ].next ) {
1893 if ( trie->trans[ stateidx + charid ].next ) {
1895 for ( ; zp < pos ; zp++ ) {
1896 if ( ! trie->trans[ zp ].next ) {
1900 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1901 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1902 trie->trans[ zp ].check = state;
1903 if ( ++zp > pos ) pos = zp;
1910 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1912 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1913 trie->trans[ pos ].check = state;
1918 trie->lasttrans = pos + 1;
1919 trie->states = (reg_trie_state *)
1920 PerlMemShared_realloc( trie->states, laststate
1921 * sizeof(reg_trie_state) );
1922 DEBUG_TRIE_COMPILE_MORE_r(
1923 PerlIO_printf( Perl_debug_log,
1924 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1925 (int)depth * 2 + 2,"",
1926 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1929 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1932 } /* end table compress */
1934 DEBUG_TRIE_COMPILE_MORE_r(
1935 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1936 (int)depth * 2 + 2, "",
1937 (UV)trie->statecount,
1938 (UV)trie->lasttrans)
1940 /* resize the trans array to remove unused space */
1941 trie->trans = (reg_trie_trans *)
1942 PerlMemShared_realloc( trie->trans, trie->lasttrans
1943 * sizeof(reg_trie_trans) );
1945 { /* Modify the program and insert the new TRIE node*/
1946 U8 nodetype =(U8)(flags & 0xFF);
1950 regnode *optimize = NULL;
1951 #ifdef RE_TRACK_PATTERN_OFFSETS
1954 U32 mjd_nodelen = 0;
1955 #endif /* RE_TRACK_PATTERN_OFFSETS */
1956 #endif /* DEBUGGING */
1958 This means we convert either the first branch or the first Exact,
1959 depending on whether the thing following (in 'last') is a branch
1960 or not and whther first is the startbranch (ie is it a sub part of
1961 the alternation or is it the whole thing.)
1962 Assuming its a sub part we conver the EXACT otherwise we convert
1963 the whole branch sequence, including the first.
1965 /* Find the node we are going to overwrite */
1966 if ( first != startbranch || OP( last ) == BRANCH ) {
1967 /* branch sub-chain */
1968 NEXT_OFF( first ) = (U16)(last - first);
1969 #ifdef RE_TRACK_PATTERN_OFFSETS
1971 mjd_offset= Node_Offset((convert));
1972 mjd_nodelen= Node_Length((convert));
1975 /* whole branch chain */
1977 #ifdef RE_TRACK_PATTERN_OFFSETS
1980 const regnode *nop = NEXTOPER( convert );
1981 mjd_offset= Node_Offset((nop));
1982 mjd_nodelen= Node_Length((nop));
1986 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1987 (int)depth * 2 + 2, "",
1988 (UV)mjd_offset, (UV)mjd_nodelen)
1991 /* But first we check to see if there is a common prefix we can
1992 split out as an EXACT and put in front of the TRIE node. */
1993 trie->startstate= 1;
1994 if ( trie->bitmap && !widecharmap && !trie->jump ) {
1996 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2000 const U32 base = trie->states[ state ].trans.base;
2002 if ( trie->states[state].wordnum )
2005 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2006 if ( ( base + ofs >= trie->uniquecharcount ) &&
2007 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2008 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2010 if ( ++count > 1 ) {
2011 SV **tmp = av_fetch( revcharmap, ofs, 0);
2012 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2013 if ( state == 1 ) break;
2015 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2017 PerlIO_printf(Perl_debug_log,
2018 "%*sNew Start State=%"UVuf" Class: [",
2019 (int)depth * 2 + 2, "",
2022 SV ** const tmp = av_fetch( revcharmap, idx, 0);
2023 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2025 TRIE_BITMAP_SET(trie,*ch);
2027 TRIE_BITMAP_SET(trie, folder[ *ch ]);
2029 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2033 TRIE_BITMAP_SET(trie,*ch);
2035 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2036 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2042 SV **tmp = av_fetch( revcharmap, idx, 0);
2044 char *ch = SvPV( *tmp, len );
2046 SV *sv=sv_newmortal();
2047 PerlIO_printf( Perl_debug_log,
2048 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2049 (int)depth * 2 + 2, "",
2051 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
2052 PL_colors[0], PL_colors[1],
2053 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2054 PERL_PV_ESCAPE_FIRSTCHAR
2059 OP( convert ) = nodetype;
2060 str=STRING(convert);
2063 STR_LEN(convert) += len;
2069 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2074 trie->prefixlen = (state-1);
2076 regnode *n = convert+NODE_SZ_STR(convert);
2077 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2078 trie->startstate = state;
2079 trie->minlen -= (state - 1);
2080 trie->maxlen -= (state - 1);
2082 /* At least the UNICOS C compiler choked on this
2083 * being argument to DEBUG_r(), so let's just have
2086 #ifdef PERL_EXT_RE_BUILD
2092 regnode *fix = convert;
2093 U32 word = trie->wordcount;
2095 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2096 while( ++fix < n ) {
2097 Set_Node_Offset_Length(fix, 0, 0);
2100 SV ** const tmp = av_fetch( trie_words, word, 0 );
2102 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2103 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2105 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2113 NEXT_OFF(convert) = (U16)(tail - convert);
2114 DEBUG_r(optimize= n);
2120 if ( trie->maxlen ) {
2121 NEXT_OFF( convert ) = (U16)(tail - convert);
2122 ARG_SET( convert, data_slot );
2123 /* Store the offset to the first unabsorbed branch in
2124 jump[0], which is otherwise unused by the jump logic.
2125 We use this when dumping a trie and during optimisation. */
2127 trie->jump[0] = (U16)(nextbranch - convert);
2130 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
2131 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2133 OP( convert ) = TRIEC;
2134 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2135 PerlMemShared_free(trie->bitmap);
2138 OP( convert ) = TRIE;
2140 /* store the type in the flags */
2141 convert->flags = nodetype;
2145 + regarglen[ OP( convert ) ];
2147 /* XXX We really should free up the resource in trie now,
2148 as we won't use them - (which resources?) dmq */
2150 /* needed for dumping*/
2151 DEBUG_r(if (optimize) {
2152 regnode *opt = convert;
2154 while ( ++opt < optimize) {
2155 Set_Node_Offset_Length(opt,0,0);
2158 Try to clean up some of the debris left after the
2161 while( optimize < jumper ) {
2162 mjd_nodelen += Node_Length((optimize));
2163 OP( optimize ) = OPTIMIZED;
2164 Set_Node_Offset_Length(optimize,0,0);
2167 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2169 } /* end node insert */
2171 /* Finish populating the prev field of the wordinfo array. Walk back
2172 * from each accept state until we find another accept state, and if
2173 * so, point the first word's .prev field at the second word. If the
2174 * second already has a .prev field set, stop now. This will be the
2175 * case either if we've already processed that word's accept state,
2176 * or that that state had multiple words, and the overspill words
2177 * were already linked up earlier.
2184 for (word=1; word <= trie->wordcount; word++) {
2186 if (trie->wordinfo[word].prev)
2188 state = trie->wordinfo[word].accept;
2190 state = prev_states[state];
2193 prev = trie->states[state].wordnum;
2197 trie->wordinfo[word].prev = prev;
2199 Safefree(prev_states);
2203 /* and now dump out the compressed format */
2204 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2206 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2208 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2209 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2211 SvREFCNT_dec(revcharmap);
2215 : trie->startstate>1
2221 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2223 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2225 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2226 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2229 We find the fail state for each state in the trie, this state is the longest proper
2230 suffix of the current states 'word' that is also a proper prefix of another word in our
2231 trie. State 1 represents the word '' and is the thus the default fail state. This allows
2232 the DFA not to have to restart after its tried and failed a word at a given point, it
2233 simply continues as though it had been matching the other word in the first place.
2235 'abcdgu'=~/abcdefg|cdgu/
2236 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2237 fail, which would bring use to the state representing 'd' in the second word where we would
2238 try 'g' and succeed, prodceding to match 'cdgu'.
2240 /* add a fail transition */
2241 const U32 trie_offset = ARG(source);
2242 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2244 const U32 ucharcount = trie->uniquecharcount;
2245 const U32 numstates = trie->statecount;
2246 const U32 ubound = trie->lasttrans + ucharcount;
2250 U32 base = trie->states[ 1 ].trans.base;
2253 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2254 GET_RE_DEBUG_FLAGS_DECL;
2256 PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2258 PERL_UNUSED_ARG(depth);
2262 ARG_SET( stclass, data_slot );
2263 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2264 RExC_rxi->data->data[ data_slot ] = (void*)aho;
2265 aho->trie=trie_offset;
2266 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2267 Copy( trie->states, aho->states, numstates, reg_trie_state );
2268 Newxz( q, numstates, U32);
2269 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2272 /* initialize fail[0..1] to be 1 so that we always have
2273 a valid final fail state */
2274 fail[ 0 ] = fail[ 1 ] = 1;
2276 for ( charid = 0; charid < ucharcount ; charid++ ) {
2277 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2279 q[ q_write ] = newstate;
2280 /* set to point at the root */
2281 fail[ q[ q_write++ ] ]=1;
2284 while ( q_read < q_write) {
2285 const U32 cur = q[ q_read++ % numstates ];
2286 base = trie->states[ cur ].trans.base;
2288 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2289 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2291 U32 fail_state = cur;
2294 fail_state = fail[ fail_state ];
2295 fail_base = aho->states[ fail_state ].trans.base;
2296 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2298 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2299 fail[ ch_state ] = fail_state;
2300 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2302 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2304 q[ q_write++ % numstates] = ch_state;
2308 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2309 when we fail in state 1, this allows us to use the
2310 charclass scan to find a valid start char. This is based on the principle
2311 that theres a good chance the string being searched contains lots of stuff
2312 that cant be a start char.
2314 fail[ 0 ] = fail[ 1 ] = 0;
2315 DEBUG_TRIE_COMPILE_r({
2316 PerlIO_printf(Perl_debug_log,
2317 "%*sStclass Failtable (%"UVuf" states): 0",
2318 (int)(depth * 2), "", (UV)numstates
2320 for( q_read=1; q_read<numstates; q_read++ ) {
2321 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2323 PerlIO_printf(Perl_debug_log, "\n");
2326 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2331 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2332 * These need to be revisited when a newer toolchain becomes available.
2334 #if defined(__sparc64__) && defined(__GNUC__)
2335 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2336 # undef SPARC64_GCC_WORKAROUND
2337 # define SPARC64_GCC_WORKAROUND 1
2341 #define DEBUG_PEEP(str,scan,depth) \
2342 DEBUG_OPTIMISE_r({if (scan){ \
2343 SV * const mysv=sv_newmortal(); \
2344 regnode *Next = regnext(scan); \
2345 regprop(RExC_rx, mysv, scan); \
2346 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2347 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2348 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2355 #define JOIN_EXACT(scan,min,flags) \
2356 if (PL_regkind[OP(scan)] == EXACT) \
2357 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2360 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2361 /* Merge several consecutive EXACTish nodes into one. */
2362 regnode *n = regnext(scan);
2364 regnode *next = scan + NODE_SZ_STR(scan);
2368 regnode *stop = scan;
2369 GET_RE_DEBUG_FLAGS_DECL;
2371 PERL_UNUSED_ARG(depth);
2374 PERL_ARGS_ASSERT_JOIN_EXACT;
2375 #ifndef EXPERIMENTAL_INPLACESCAN
2376 PERL_UNUSED_ARG(flags);
2377 PERL_UNUSED_ARG(val);
2379 DEBUG_PEEP("join",scan,depth);
2381 /* Skip NOTHING, merge EXACT*. */
2383 ( PL_regkind[OP(n)] == NOTHING ||
2384 (stringok && (OP(n) == OP(scan))))
2386 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2388 if (OP(n) == TAIL || n > next)
2390 if (PL_regkind[OP(n)] == NOTHING) {
2391 DEBUG_PEEP("skip:",n,depth);
2392 NEXT_OFF(scan) += NEXT_OFF(n);
2393 next = n + NODE_STEP_REGNODE;
2400 else if (stringok) {
2401 const unsigned int oldl = STR_LEN(scan);
2402 regnode * const nnext = regnext(n);
2404 DEBUG_PEEP("merg",n,depth);
2407 if (oldl + STR_LEN(n) > U8_MAX)
2409 NEXT_OFF(scan) += NEXT_OFF(n);
2410 STR_LEN(scan) += STR_LEN(n);
2411 next = n + NODE_SZ_STR(n);
2412 /* Now we can overwrite *n : */
2413 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2421 #ifdef EXPERIMENTAL_INPLACESCAN
2422 if (flags && !NEXT_OFF(n)) {
2423 DEBUG_PEEP("atch", val, depth);
2424 if (reg_off_by_arg[OP(n)]) {
2425 ARG_SET(n, val - n);
2428 NEXT_OFF(n) = val - n;
2435 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2437 Two problematic code points in Unicode casefolding of EXACT nodes:
2439 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2440 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2446 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2447 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2449 This means that in case-insensitive matching (or "loose matching",
2450 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2451 length of the above casefolded versions) can match a target string
2452 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2453 This would rather mess up the minimum length computation.
2455 What we'll do is to look for the tail four bytes, and then peek
2456 at the preceding two bytes to see whether we need to decrease
2457 the minimum length by four (six minus two).
2459 Thanks to the design of UTF-8, there cannot be false matches:
2460 A sequence of valid UTF-8 bytes cannot be a subsequence of
2461 another valid sequence of UTF-8 bytes.
2464 char * const s0 = STRING(scan), *s, *t;
2465 char * const s1 = s0 + STR_LEN(scan) - 1;
2466 char * const s2 = s1 - 4;
2467 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2468 const char t0[] = "\xaf\x49\xaf\x42";
2470 const char t0[] = "\xcc\x88\xcc\x81";
2472 const char * const t1 = t0 + 3;
2475 s < s2 && (t = ninstr(s, s1, t0, t1));
2478 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2479 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2481 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2482 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2490 n = scan + NODE_SZ_STR(scan);
2492 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2499 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2503 /* REx optimizer. Converts nodes into quickier variants "in place".
2504 Finds fixed substrings. */
2506 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2507 to the position after last scanned or to NULL. */
2509 #define INIT_AND_WITHP \
2510 assert(!and_withp); \
2511 Newx(and_withp,1,struct regnode_charclass_class); \
2512 SAVEFREEPV(and_withp)
2514 /* this is a chain of data about sub patterns we are processing that
2515 need to be handled seperately/specially in study_chunk. Its so
2516 we can simulate recursion without losing state. */
2518 typedef struct scan_frame {
2519 regnode *last; /* last node to process in this frame */
2520 regnode *next; /* next node to process when last is reached */
2521 struct scan_frame *prev; /*previous frame*/
2522 I32 stop; /* what stopparen do we use */
2526 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2528 #define CASE_SYNST_FNC(nAmE) \
2530 if (flags & SCF_DO_STCLASS_AND) { \
2531 for (value = 0; value < 256; value++) \
2532 if (!is_ ## nAmE ## _cp(value)) \
2533 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2536 for (value = 0; value < 256; value++) \
2537 if (is_ ## nAmE ## _cp(value)) \
2538 ANYOF_BITMAP_SET(data->start_class, value); \
2542 if (flags & SCF_DO_STCLASS_AND) { \
2543 for (value = 0; value < 256; value++) \
2544 if (is_ ## nAmE ## _cp(value)) \
2545 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2548 for (value = 0; value < 256; value++) \
2549 if (!is_ ## nAmE ## _cp(value)) \
2550 ANYOF_BITMAP_SET(data->start_class, value); \
2557 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2558 I32 *minlenp, I32 *deltap,
2563 struct regnode_charclass_class *and_withp,
2564 U32 flags, U32 depth)
2565 /* scanp: Start here (read-write). */
2566 /* deltap: Write maxlen-minlen here. */
2567 /* last: Stop before this one. */
2568 /* data: string data about the pattern */
2569 /* stopparen: treat close N as END */
2570 /* recursed: which subroutines have we recursed into */
2571 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2574 I32 min = 0, pars = 0, code;
2575 regnode *scan = *scanp, *next;
2577 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2578 int is_inf_internal = 0; /* The studied chunk is infinite */
2579 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2580 scan_data_t data_fake;
2581 SV *re_trie_maxbuff = NULL;
2582 regnode *first_non_open = scan;
2583 I32 stopmin = I32_MAX;
2584 scan_frame *frame = NULL;
2585 GET_RE_DEBUG_FLAGS_DECL;
2587 PERL_ARGS_ASSERT_STUDY_CHUNK;
2590 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2594 while (first_non_open && OP(first_non_open) == OPEN)
2595 first_non_open=regnext(first_non_open);
2600 while ( scan && OP(scan) != END && scan < last ){
2601 /* Peephole optimizer: */
2602 DEBUG_STUDYDATA("Peep:", data,depth);
2603 DEBUG_PEEP("Peep",scan,depth);
2604 JOIN_EXACT(scan,&min,0);
2606 /* Follow the next-chain of the current node and optimize
2607 away all the NOTHINGs from it. */
2608 if (OP(scan) != CURLYX) {
2609 const int max = (reg_off_by_arg[OP(scan)]
2611 /* I32 may be smaller than U16 on CRAYs! */
2612 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2613 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2617 /* Skip NOTHING and LONGJMP. */
2618 while ((n = regnext(n))
2619 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2620 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2621 && off + noff < max)
2623 if (reg_off_by_arg[OP(scan)])
2626 NEXT_OFF(scan) = off;
2631 /* The principal pseudo-switch. Cannot be a switch, since we
2632 look into several different things. */
2633 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2634 || OP(scan) == IFTHEN) {
2635 next = regnext(scan);
2637 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2639 if (OP(next) == code || code == IFTHEN) {
2640 /* NOTE - There is similar code to this block below for handling
2641 TRIE nodes on a re-study. If you change stuff here check there
2643 I32 max1 = 0, min1 = I32_MAX, num = 0;
2644 struct regnode_charclass_class accum;
2645 regnode * const startbranch=scan;
2647 if (flags & SCF_DO_SUBSTR)
2648 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2649 if (flags & SCF_DO_STCLASS)
2650 cl_init_zero(pRExC_state, &accum);
2652 while (OP(scan) == code) {
2653 I32 deltanext, minnext, f = 0, fake;
2654 struct regnode_charclass_class this_class;
2657 data_fake.flags = 0;
2659 data_fake.whilem_c = data->whilem_c;
2660 data_fake.last_closep = data->last_closep;
2663 data_fake.last_closep = &fake;
2665 data_fake.pos_delta = delta;
2666 next = regnext(scan);
2667 scan = NEXTOPER(scan);
2669 scan = NEXTOPER(scan);
2670 if (flags & SCF_DO_STCLASS) {
2671 cl_init(pRExC_state, &this_class);
2672 data_fake.start_class = &this_class;
2673 f = SCF_DO_STCLASS_AND;
2675 if (flags & SCF_WHILEM_VISITED_POS)
2676 f |= SCF_WHILEM_VISITED_POS;
2678 /* we suppose the run is continuous, last=next...*/
2679 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2681 stopparen, recursed, NULL, f,depth+1);
2684 if (max1 < minnext + deltanext)
2685 max1 = minnext + deltanext;
2686 if (deltanext == I32_MAX)
2687 is_inf = is_inf_internal = 1;
2689 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2691 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2692 if ( stopmin > minnext)
2693 stopmin = min + min1;
2694 flags &= ~SCF_DO_SUBSTR;
2696 data->flags |= SCF_SEEN_ACCEPT;
2699 if (data_fake.flags & SF_HAS_EVAL)
2700 data->flags |= SF_HAS_EVAL;
2701 data->whilem_c = data_fake.whilem_c;
2703 if (flags & SCF_DO_STCLASS)
2704 cl_or(pRExC_state, &accum, &this_class);
2706 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2708 if (flags & SCF_DO_SUBSTR) {
2709 data->pos_min += min1;
2710 data->pos_delta += max1 - min1;
2711 if (max1 != min1 || is_inf)
2712 data->longest = &(data->longest_float);
2715 delta += max1 - min1;
2716 if (flags & SCF_DO_STCLASS_OR) {
2717 cl_or(pRExC_state, data->start_class, &accum);
2719 cl_and(data->start_class, and_withp);
2720 flags &= ~SCF_DO_STCLASS;
2723 else if (flags & SCF_DO_STCLASS_AND) {
2725 cl_and(data->start_class, &accum);
2726 flags &= ~SCF_DO_STCLASS;
2729 /* Switch to OR mode: cache the old value of
2730 * data->start_class */
2732 StructCopy(data->start_class, and_withp,
2733 struct regnode_charclass_class);
2734 flags &= ~SCF_DO_STCLASS_AND;
2735 StructCopy(&accum, data->start_class,
2736 struct regnode_charclass_class);
2737 flags |= SCF_DO_STCLASS_OR;
2738 data->start_class->flags |= ANYOF_EOS;
2742 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2745 Assuming this was/is a branch we are dealing with: 'scan' now
2746 points at the item that follows the branch sequence, whatever
2747 it is. We now start at the beginning of the sequence and look
2754 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2756 If we can find such a subseqence we need to turn the first
2757 element into a trie and then add the subsequent branch exact
2758 strings to the trie.
2762 1. patterns where the whole set of branch can be converted.
2764 2. patterns where only a subset can be converted.
2766 In case 1 we can replace the whole set with a single regop
2767 for the trie. In case 2 we need to keep the start and end
2770 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2771 becomes BRANCH TRIE; BRANCH X;
2773 There is an additional case, that being where there is a
2774 common prefix, which gets split out into an EXACT like node
2775 preceding the TRIE node.
2777 If x(1..n)==tail then we can do a simple trie, if not we make
2778 a "jump" trie, such that when we match the appropriate word
2779 we "jump" to the appopriate tail node. Essentailly we turn
2780 a nested if into a case structure of sorts.
2785 if (!re_trie_maxbuff) {
2786 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2787 if (!SvIOK(re_trie_maxbuff))
2788 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2790 if ( SvIV(re_trie_maxbuff)>=0 ) {
2792 regnode *first = (regnode *)NULL;
2793 regnode *last = (regnode *)NULL;
2794 regnode *tail = scan;
2799 SV * const mysv = sv_newmortal(); /* for dumping */
2801 /* var tail is used because there may be a TAIL
2802 regop in the way. Ie, the exacts will point to the
2803 thing following the TAIL, but the last branch will
2804 point at the TAIL. So we advance tail. If we
2805 have nested (?:) we may have to move through several
2809 while ( OP( tail ) == TAIL ) {
2810 /* this is the TAIL generated by (?:) */
2811 tail = regnext( tail );
2816 regprop(RExC_rx, mysv, tail );
2817 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2818 (int)depth * 2 + 2, "",
2819 "Looking for TRIE'able sequences. Tail node is: ",
2820 SvPV_nolen_const( mysv )
2826 step through the branches, cur represents each
2827 branch, noper is the first thing to be matched
2828 as part of that branch and noper_next is the
2829 regnext() of that node. if noper is an EXACT
2830 and noper_next is the same as scan (our current
2831 position in the regex) then the EXACT branch is
2832 a possible optimization target. Once we have
2833 two or more consequetive such branches we can
2834 create a trie of the EXACT's contents and stich
2835 it in place. If the sequence represents all of
2836 the branches we eliminate the whole thing and
2837 replace it with a single TRIE. If it is a
2838 subsequence then we need to stitch it in. This
2839 means the first branch has to remain, and needs
2840 to be repointed at the item on the branch chain
2841 following the last branch optimized. This could
2842 be either a BRANCH, in which case the
2843 subsequence is internal, or it could be the
2844 item following the branch sequence in which
2845 case the subsequence is at the end.
2849 /* dont use tail as the end marker for this traverse */
2850 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2851 regnode * const noper = NEXTOPER( cur );
2852 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2853 regnode * const noper_next = regnext( noper );
2857 regprop(RExC_rx, mysv, cur);
2858 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2859 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2861 regprop(RExC_rx, mysv, noper);
2862 PerlIO_printf( Perl_debug_log, " -> %s",
2863 SvPV_nolen_const(mysv));
2866 regprop(RExC_rx, mysv, noper_next );
2867 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2868 SvPV_nolen_const(mysv));
2870 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2871 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2873 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2874 : PL_regkind[ OP( noper ) ] == EXACT )
2875 || OP(noper) == NOTHING )
2877 && noper_next == tail
2882 if ( !first || optype == NOTHING ) {
2883 if (!first) first = cur;
2884 optype = OP( noper );
2890 Currently we do not believe that the trie logic can
2891 handle case insensitive matching properly when the
2892 pattern is not unicode (thus forcing unicode semantics).
2894 If/when this is fixed the following define can be swapped
2895 in below to fully enable trie logic.
2897 #define TRIE_TYPE_IS_SAFE 1
2900 #define TRIE_TYPE_IS_SAFE (UTF || optype==EXACT)
2902 if ( last && TRIE_TYPE_IS_SAFE ) {
2903 make_trie( pRExC_state,
2904 startbranch, first, cur, tail, count,
2907 if ( PL_regkind[ OP( noper ) ] == EXACT
2909 && noper_next == tail
2914 optype = OP( noper );
2924 regprop(RExC_rx, mysv, cur);
2925 PerlIO_printf( Perl_debug_log,
2926 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2927 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2931 if ( last && TRIE_TYPE_IS_SAFE ) {
2932 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2933 #ifdef TRIE_STUDY_OPT
2934 if ( ((made == MADE_EXACT_TRIE &&
2935 startbranch == first)
2936 || ( first_non_open == first )) &&
2938 flags |= SCF_TRIE_RESTUDY;
2939 if ( startbranch == first
2942 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2952 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2953 scan = NEXTOPER(NEXTOPER(scan));
2954 } else /* single branch is optimized. */
2955 scan = NEXTOPER(scan);
2957 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2958 scan_frame *newframe = NULL;
2963 if (OP(scan) != SUSPEND) {
2964 /* set the pointer */
2965 if (OP(scan) == GOSUB) {
2967 RExC_recurse[ARG2L(scan)] = scan;
2968 start = RExC_open_parens[paren-1];
2969 end = RExC_close_parens[paren-1];
2972 start = RExC_rxi->program + 1;
2976 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2977 SAVEFREEPV(recursed);
2979 if (!PAREN_TEST(recursed,paren+1)) {
2980 PAREN_SET(recursed,paren+1);
2981 Newx(newframe,1,scan_frame);
2983 if (flags & SCF_DO_SUBSTR) {
2984 SCAN_COMMIT(pRExC_state,data,minlenp);
2985 data->longest = &(data->longest_float);
2987 is_inf = is_inf_internal = 1;
2988 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2989 cl_anything(pRExC_state, data->start_class);
2990 flags &= ~SCF_DO_STCLASS;
2993 Newx(newframe,1,scan_frame);
2996 end = regnext(scan);
3001 SAVEFREEPV(newframe);
3002 newframe->next = regnext(scan);
3003 newframe->last = last;
3004 newframe->stop = stopparen;
3005 newframe->prev = frame;
3015 else if (OP(scan) == EXACT) {
3016 I32 l = STR_LEN(scan);
3019 const U8 * const s = (U8*)STRING(scan);
3020 l = utf8_length(s, s + l);
3021 uc = utf8_to_uvchr(s, NULL);
3023 uc = *((U8*)STRING(scan));
3026 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3027 /* The code below prefers earlier match for fixed
3028 offset, later match for variable offset. */
3029 if (data->last_end == -1) { /* Update the start info. */
3030 data->last_start_min = data->pos_min;
3031 data->last_start_max = is_inf
3032 ? I32_MAX : data->pos_min + data->pos_delta;
3034 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3036 SvUTF8_on(data->last_found);
3038 SV * const sv = data->last_found;
3039 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3040 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3041 if (mg && mg->mg_len >= 0)
3042 mg->mg_len += utf8_length((U8*)STRING(scan),
3043 (U8*)STRING(scan)+STR_LEN(scan));
3045 data->last_end = data->pos_min + l;
3046 data->pos_min += l; /* As in the first entry. */
3047 data->flags &= ~SF_BEFORE_EOL;
3049 if (flags & SCF_DO_STCLASS_AND) {
3050 /* Check whether it is compatible with what we know already! */
3054 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3055 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3056 && (!(data->start_class->flags & ANYOF_FOLD)
3057 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
3060 ANYOF_CLASS_ZERO(data->start_class);
3061 ANYOF_BITMAP_ZERO(data->start_class);
3063 ANYOF_BITMAP_SET(data->start_class, uc);
3064 data->start_class->flags &= ~ANYOF_EOS;
3066 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3068 else if (flags & SCF_DO_STCLASS_OR) {
3069 /* false positive possible if the class is case-folded */
3071 ANYOF_BITMAP_SET(data->start_class, uc);
3073 data->start_class->flags |= ANYOF_UNICODE_ALL;
3074 data->start_class->flags &= ~ANYOF_EOS;
3075 cl_and(data->start_class, and_withp);
3077 flags &= ~SCF_DO_STCLASS;
3079 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3080 I32 l = STR_LEN(scan);
3081 UV uc = *((U8*)STRING(scan));
3083 /* Search for fixed substrings supports EXACT only. */
3084 if (flags & SCF_DO_SUBSTR) {
3086 SCAN_COMMIT(pRExC_state, data, minlenp);
3089 const U8 * const s = (U8 *)STRING(scan);
3090 l = utf8_length(s, s + l);
3091 uc = utf8_to_uvchr(s, NULL);
3094 if (flags & SCF_DO_SUBSTR)
3096 if (flags & SCF_DO_STCLASS_AND) {
3097 /* Check whether it is compatible with what we know already! */
3101 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3102 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3103 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
3105 ANYOF_CLASS_ZERO(data->start_class);
3106 ANYOF_BITMAP_ZERO(data->start_class);
3108 ANYOF_BITMAP_SET(data->start_class, uc);
3109 data->start_class->flags &= ~ANYOF_EOS;
3110 data->start_class->flags |= ANYOF_FOLD;
3111 if (OP(scan) == EXACTFL)
3112 data->start_class->flags |= ANYOF_LOCALE;
3115 else if (flags & SCF_DO_STCLASS_OR) {
3116 if (data->start_class->flags & ANYOF_FOLD) {
3117 /* false positive possible if the class is case-folded.
3118 Assume that the locale settings are the same... */
3120 ANYOF_BITMAP_SET(data->start_class, uc);
3121 data->start_class->flags &= ~ANYOF_EOS;
3123 cl_and(data->start_class, and_withp);
3125 flags &= ~SCF_DO_STCLASS;
3127 else if (REGNODE_VARIES(OP(scan))) {
3128 I32 mincount, maxcount, minnext, deltanext, fl = 0;
3129 I32 f = flags, pos_before = 0;
3130 regnode * const oscan = scan;
3131 struct regnode_charclass_class this_class;
3132 struct regnode_charclass_class *oclass = NULL;
3133 I32 next_is_eval = 0;
3135 switch (PL_regkind[OP(scan)]) {
3136 case WHILEM: /* End of (?:...)* . */
3137 scan = NEXTOPER(scan);
3140 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3141 next = NEXTOPER(scan);
3142 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3144 maxcount = REG_INFTY;
3145 next = regnext(scan);
3146 scan = NEXTOPER(scan);
3150 if (flags & SCF_DO_SUBSTR)
3155 if (flags & SCF_DO_STCLASS) {
3157 maxcount = REG_INFTY;
3158 next = regnext(scan);
3159 scan = NEXTOPER(scan);
3162 is_inf = is_inf_internal = 1;
3163 scan = regnext(scan);
3164 if (flags & SCF_DO_SUBSTR) {
3165 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3166 data->longest = &(data->longest_float);
3168 goto optimize_curly_tail;
3170 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3171 && (scan->flags == stopparen))
3176 mincount = ARG1(scan);
3177 maxcount = ARG2(scan);
3179 next = regnext(scan);
3180 if (OP(scan) == CURLYX) {
3181 I32 lp = (data ? *(data->last_closep) : 0);
3182 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3184 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3185 next_is_eval = (OP(scan) == EVAL);
3187 if (flags & SCF_DO_SUBSTR) {
3188 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3189 pos_before = data->pos_min;
3193 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3195 data->flags |= SF_IS_INF;
3197 if (flags & SCF_DO_STCLASS) {
3198 cl_init(pRExC_state, &this_class);
3199 oclass = data->start_class;
3200 data->start_class = &this_class;
3201 f |= SCF_DO_STCLASS_AND;
3202 f &= ~SCF_DO_STCLASS_OR;
3204 /* These are the cases when once a subexpression
3205 fails at a particular position, it cannot succeed
3206 even after backtracking at the enclosing scope.
3208 XXXX what if minimal match and we are at the
3209 initial run of {n,m}? */
3210 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
3211 f &= ~SCF_WHILEM_VISITED_POS;
3213 /* This will finish on WHILEM, setting scan, or on NULL: */
3214 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3215 last, data, stopparen, recursed, NULL,
3217 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3219 if (flags & SCF_DO_STCLASS)
3220 data->start_class = oclass;
3221 if (mincount == 0 || minnext == 0) {
3222 if (flags & SCF_DO_STCLASS_OR) {
3223 cl_or(pRExC_state, data->start_class, &this_class);
3225 else if (flags & SCF_DO_STCLASS_AND) {
3226 /* Switch to OR mode: cache the old value of
3227 * data->start_class */
3229 StructCopy(data->start_class, and_withp,
3230 struct regnode_charclass_class);
3231 flags &= ~SCF_DO_STCLASS_AND;
3232 StructCopy(&this_class, data->start_class,
3233 struct regnode_charclass_class);
3234 flags |= SCF_DO_STCLASS_OR;
3235 data->start_class->flags |= ANYOF_EOS;
3237 } else { /* Non-zero len */
3238 if (flags & SCF_DO_STCLASS_OR) {
3239 cl_or(pRExC_state, data->start_class, &this_class);
3240 cl_and(data->start_class, and_withp);
3242 else if (flags & SCF_DO_STCLASS_AND)
3243 cl_and(data->start_class, &this_class);
3244 flags &= ~SCF_DO_STCLASS;
3246 if (!scan) /* It was not CURLYX, but CURLY. */
3248 if ( /* ? quantifier ok, except for (?{ ... }) */
3249 (next_is_eval || !(mincount == 0 && maxcount == 1))
3250 && (minnext == 0) && (deltanext == 0)
3251 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3252 && maxcount <= REG_INFTY/3) /* Complement check for big count */
3254 ckWARNreg(RExC_parse,
3255 "Quantifier unexpected on zero-length expression");
3258 min += minnext * mincount;
3259 is_inf_internal |= ((maxcount == REG_INFTY
3260 && (minnext + deltanext) > 0)
3261 || deltanext == I32_MAX);
3262 is_inf |= is_inf_internal;
3263 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3265 /* Try powerful optimization CURLYX => CURLYN. */
3266 if ( OP(oscan) == CURLYX && data
3267 && data->flags & SF_IN_PAR
3268 && !(data->flags & SF_HAS_EVAL)
3269 && !deltanext && minnext == 1 ) {
3270 /* Try to optimize to CURLYN. */
3271 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3272 regnode * const nxt1 = nxt;
3279 if (!REGNODE_SIMPLE(OP(nxt))
3280 && !(PL_regkind[OP(nxt)] == EXACT
3281 && STR_LEN(nxt) == 1))
3287 if (OP(nxt) != CLOSE)
3289 if (RExC_open_parens) {
3290 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3291 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3293 /* Now we know that nxt2 is the only contents: */
3294 oscan->flags = (U8)ARG(nxt);
3296 OP(nxt1) = NOTHING; /* was OPEN. */
3299 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3300 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3301 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
3302 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3303 OP(nxt + 1) = OPTIMIZED; /* was count. */
3304 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
3309 /* Try optimization CURLYX => CURLYM. */
3310 if ( OP(oscan) == CURLYX && data
3311 && !(data->flags & SF_HAS_PAR)
3312 && !(data->flags & SF_HAS_EVAL)
3313 && !deltanext /* atom is fixed width */
3314 && minnext != 0 /* CURLYM can't handle zero width */
3316 /* XXXX How to optimize if data == 0? */
3317 /* Optimize to a simpler form. */
3318 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3322 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3323 && (OP(nxt2) != WHILEM))
3325 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3326 /* Need to optimize away parenths. */
3327 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
3328 /* Set the parenth number. */
3329 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3331 oscan->flags = (U8)ARG(nxt);
3332 if (RExC_open_parens) {
3333 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3334 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3336 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3337 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3340 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3341 OP(nxt + 1) = OPTIMIZED; /* was count. */
3342 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3343 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3346 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3347 regnode *nnxt = regnext(nxt1);
3350 if (reg_off_by_arg[OP(nxt1)])
3351 ARG_SET(nxt1, nxt2 - nxt1);
3352 else if (nxt2 - nxt1 < U16_MAX)
3353 NEXT_OFF(nxt1) = nxt2 - nxt1;
3355 OP(nxt) = NOTHING; /* Cannot beautify */
3360 /* Optimize again: */
3361 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3362 NULL, stopparen, recursed, NULL, 0,depth+1);
3367 else if ((OP(oscan) == CURLYX)
3368 && (flags & SCF_WHILEM_VISITED_POS)
3369 /* See the comment on a similar expression above.
3370 However, this time it not a subexpression
3371 we care about, but the expression itself. */
3372 && (maxcount == REG_INFTY)
3373 && data && ++data->whilem_c < 16) {
3374 /* This stays as CURLYX, we can put the count/of pair. */
3375 /* Find WHILEM (as in regexec.c) */
3376 regnode *nxt = oscan + NEXT_OFF(oscan);
3378 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3380 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3381 | (RExC_whilem_seen << 4)); /* On WHILEM */
3383 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3385 if (flags & SCF_DO_SUBSTR) {
3386 SV *last_str = NULL;
3387 int counted = mincount != 0;
3389 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3390 #if defined(SPARC64_GCC_WORKAROUND)
3393 const char *s = NULL;
3396 if (pos_before >= data->last_start_min)
3399 b = data->last_start_min;
3402 s = SvPV_const(data->last_found, l);
3403 old = b - data->last_start_min;
3406 I32 b = pos_before >= data->last_start_min
3407 ? pos_before : data->last_start_min;
3409 const char * const s = SvPV_const(data->last_found, l);
3410 I32 old = b - data->last_start_min;
3414 old = utf8_hop((U8*)s, old) - (U8*)s;
3417 /* Get the added string: */
3418 last_str = newSVpvn_utf8(s + old, l, UTF);
3419 if (deltanext == 0 && pos_before == b) {
3420 /* What was added is a constant string */
3422 SvGROW(last_str, (mincount * l) + 1);
3423 repeatcpy(SvPVX(last_str) + l,
3424 SvPVX_const(last_str), l, mincount - 1);
3425 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3426 /* Add additional parts. */
3427 SvCUR_set(data->last_found,
3428 SvCUR(data->last_found) - l);
3429 sv_catsv(data->last_found, last_str);
3431 SV * sv = data->last_found;
3433 SvUTF8(sv) && SvMAGICAL(sv) ?
3434 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3435 if (mg && mg->mg_len >= 0)
3436 mg->mg_len += CHR_SVLEN(last_str) - l;
3438 data->last_end += l * (mincount - 1);
3441 /* start offset must point into the last copy */
3442 data->last_start_min += minnext * (mincount - 1);
3443 data->last_start_max += is_inf ? I32_MAX
3444 : (maxcount - 1) * (minnext + data->pos_delta);
3447 /* It is counted once already... */
3448 data->pos_min += minnext * (mincount - counted);
3449 data->pos_delta += - counted * deltanext +
3450 (minnext + deltanext) * maxcount - minnext * mincount;
3451 if (mincount != maxcount) {
3452 /* Cannot extend fixed substrings found inside
3454 SCAN_COMMIT(pRExC_state,data,minlenp);
3455 if (mincount && last_str) {
3456 SV * const sv = data->last_found;
3457 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3458 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3462 sv_setsv(sv, last_str);
3463 data->last_end = data->pos_min;
3464 data->last_start_min =
3465 data->pos_min - CHR_SVLEN(last_str);
3466 data->last_start_max = is_inf
3468 : data->pos_min + data->pos_delta
3469 - CHR_SVLEN(last_str);
3471 data->longest = &(data->longest_float);
3473 SvREFCNT_dec(last_str);
3475 if (data && (fl & SF_HAS_EVAL))
3476 data->flags |= SF_HAS_EVAL;
3477 optimize_curly_tail:
3478 if (OP(oscan) != CURLYX) {
3479 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3481 NEXT_OFF(oscan) += NEXT_OFF(next);
3484 default: /* REF and CLUMP only? */
3485 if (flags & SCF_DO_SUBSTR) {
3486 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3487 data->longest = &(data->longest_float);
3489 is_inf = is_inf_internal = 1;
3490 if (flags & SCF_DO_STCLASS_OR)
3491 cl_anything(pRExC_state, data->start_class);
3492 flags &= ~SCF_DO_STCLASS;
3496 else if (OP(scan) == LNBREAK) {
3497 if (flags & SCF_DO_STCLASS) {
3499 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3500 if (flags & SCF_DO_STCLASS_AND) {
3501 for (value = 0; value < 256; value++)
3502 if (!is_VERTWS_cp(value))
3503 ANYOF_BITMAP_CLEAR(data->start_class, value);
3506 for (value = 0; value < 256; value++)
3507 if (is_VERTWS_cp(value))
3508 ANYOF_BITMAP_SET(data->start_class, value);
3510 if (flags & SCF_DO_STCLASS_OR)
3511 cl_and(data->start_class, and_withp);
3512 flags &= ~SCF_DO_STCLASS;
3516 if (flags & SCF_DO_SUBSTR) {
3517 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3519 data->pos_delta += 1;
3520 data->longest = &(data->longest_float);
3524 else if (OP(scan) == FOLDCHAR) {
3525 int d = ARG(scan)==0xDF ? 1 : 2;
3526 flags &= ~SCF_DO_STCLASS;
3529 if (flags & SCF_DO_SUBSTR) {
3530 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3532 data->pos_delta += d;
3533 data->longest = &(data->longest_float);
3536 else if (REGNODE_SIMPLE(OP(scan))) {
3539 if (flags & SCF_DO_SUBSTR) {
3540 SCAN_COMMIT(pRExC_state,data,minlenp);
3544 if (flags & SCF_DO_STCLASS) {
3545 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3547 /* Some of the logic below assumes that switching
3548 locale on will only add false positives. */
3549 switch (PL_regkind[OP(scan)]) {
3553 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3554 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3555 cl_anything(pRExC_state, data->start_class);
3558 if (OP(scan) == SANY)
3560 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3561 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3562 || (data->start_class->flags & ANYOF_CLASS));
3563 cl_anything(pRExC_state, data->start_class);
3565 if (flags & SCF_DO_STCLASS_AND || !value)
3566 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3569 if (flags & SCF_DO_STCLASS_AND)
3570 cl_and(data->start_class,
3571 (struct regnode_charclass_class*)scan);
3573 cl_or(pRExC_state, data->start_class,
3574 (struct regnode_charclass_class*)scan);
3577 if (flags & SCF_DO_STCLASS_AND) {
3578 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3579 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3580 for (value = 0; value < 256; value++)
3581 if (!isALNUM(value))
3582 ANYOF_BITMAP_CLEAR(data->start_class, value);
3586 if (data->start_class->flags & ANYOF_LOCALE)
3587 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3589 for (value = 0; value < 256; value++)
3591 ANYOF_BITMAP_SET(data->start_class, value);
3596 if (flags & SCF_DO_STCLASS_AND) {
3597 if (data->start_class->flags & ANYOF_LOCALE)
3598 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3601 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3602 data->start_class->flags |= ANYOF_LOCALE;
3606 if (flags & SCF_DO_STCLASS_AND) {
3607 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3608 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3609 for (value = 0; value < 256; value++)
3611 ANYOF_BITMAP_CLEAR(data->start_class, value);
3615 if (data->start_class->flags & ANYOF_LOCALE)
3616 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3618 for (value = 0; value < 256; value++)
3619 if (!isALNUM(value))
3620 ANYOF_BITMAP_SET(data->start_class, value);
3625 if (flags & SCF_DO_STCLASS_AND) {
3626 if (data->start_class->flags & ANYOF_LOCALE)
3627 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3630 data->start_class->flags |= ANYOF_LOCALE;
3631 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3635 if (flags & SCF_DO_STCLASS_AND) {
3636 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3637 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3638 for (value = 0; value < 256; value++)
3639 if (!isSPACE(value))
3640 ANYOF_BITMAP_CLEAR(data->start_class, value);
3644 if (data->start_class->flags & ANYOF_LOCALE)
3645 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3647 for (value = 0; value < 256; value++)
3649 ANYOF_BITMAP_SET(data->start_class, value);
3654 if (flags & SCF_DO_STCLASS_AND) {
3655 if (data->start_class->flags & ANYOF_LOCALE)
3656 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3659 data->start_class->flags |= ANYOF_LOCALE;
3660 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3664 if (flags & SCF_DO_STCLASS_AND) {
3665 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3666 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3667 for (value = 0; value < 256; value++)
3669 ANYOF_BITMAP_CLEAR(data->start_class, value);
3673 if (data->start_class->flags & ANYOF_LOCALE)
3674 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3676 for (value = 0; value < 256; value++)
3677 if (!isSPACE(value))
3678 ANYOF_BITMAP_SET(data->start_class, value);
3683 if (flags & SCF_DO_STCLASS_AND) {
3684 if (data->start_class->flags & ANYOF_LOCALE) {
3685 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3686 for (value = 0; value < 256; value++)
3687 if (!isSPACE(value))
3688 ANYOF_BITMAP_CLEAR(data->start_class, value);
3692 data->start_class->flags |= ANYOF_LOCALE;
3693 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3697 if (flags & SCF_DO_STCLASS_AND) {
3698 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3699 for (value = 0; value < 256; value++)
3700 if (!isDIGIT(value))
3701 ANYOF_BITMAP_CLEAR(data->start_class, value);
3704 if (data->start_class->flags & ANYOF_LOCALE)
3705 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3707 for (value = 0; value < 256; value++)
3709 ANYOF_BITMAP_SET(data->start_class, value);
3714 if (flags & SCF_DO_STCLASS_AND) {
3715 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3716 for (value = 0; value < 256; value++)
3718 ANYOF_BITMAP_CLEAR(data->start_class, value);
3721 if (data->start_class->flags & ANYOF_LOCALE)
3722 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3724 for (value = 0; value < 256; value++)
3725 if (!isDIGIT(value))
3726 ANYOF_BITMAP_SET(data->start_class, value);
3730 CASE_SYNST_FNC(VERTWS);
3731 CASE_SYNST_FNC(HORIZWS);
3734 if (flags & SCF_DO_STCLASS_OR)
3735 cl_and(data->start_class, and_withp);
3736 flags &= ~SCF_DO_STCLASS;
3739 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3740 data->flags |= (OP(scan) == MEOL
3744 else if ( PL_regkind[OP(scan)] == BRANCHJ
3745 /* Lookbehind, or need to calculate parens/evals/stclass: */
3746 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3747 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3748 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3749 || OP(scan) == UNLESSM )
3751 /* Negative Lookahead/lookbehind
3752 In this case we can't do fixed string optimisation.
3755 I32 deltanext, minnext, fake = 0;
3757 struct regnode_charclass_class intrnl;
3760 data_fake.flags = 0;
3762 data_fake.whilem_c = data->whilem_c;
3763 data_fake.last_closep = data->last_closep;
3766 data_fake.last_closep = &fake;
3767 data_fake.pos_delta = delta;
3768 if ( flags & SCF_DO_STCLASS && !scan->flags
3769 && OP(scan) == IFMATCH ) { /* Lookahead */
3770 cl_init(pRExC_state, &intrnl);
3771 data_fake.start_class = &intrnl;
3772 f |= SCF_DO_STCLASS_AND;
3774 if (flags & SCF_WHILEM_VISITED_POS)
3775 f |= SCF_WHILEM_VISITED_POS;
3776 next = regnext(scan);
3777 nscan = NEXTOPER(NEXTOPER(scan));
3778 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
3779 last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3782 FAIL("Variable length lookbehind not implemented");
3784 else if (minnext > (I32)U8_MAX) {
3785 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3787 scan->flags = (U8)minnext;
3790 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3792 if (data_fake.flags & SF_HAS_EVAL)
3793 data->flags |= SF_HAS_EVAL;
3794 data->whilem_c = data_fake.whilem_c;
3796 if (f & SCF_DO_STCLASS_AND) {
3797 if (flags & SCF_DO_STCLASS_OR) {
3798 /* OR before, AND after: ideally we would recurse with
3799 * data_fake to get the AND applied by study of the
3800 * remainder of the pattern, and then derecurse;
3801 * *** HACK *** for now just treat as "no information".
3802 * See [perl #56690].
3804 cl_init(pRExC_state, data->start_class);
3806 /* AND before and after: combine and continue */
3807 const int was = (data->start_class->flags & ANYOF_EOS);
3809 cl_and(data->start_class, &intrnl);
3811 data->start_class->flags |= ANYOF_EOS;
3815 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3817 /* Positive Lookahead/lookbehind
3818 In this case we can do fixed string optimisation,
3819 but we must be careful about it. Note in the case of
3820 lookbehind the positions will be offset by the minimum
3821 length of the pattern, something we won't know about
3822 until after the recurse.
3824 I32 deltanext, fake = 0;
3826 struct regnode_charclass_class intrnl;
3828 /* We use SAVEFREEPV so that when the full compile
3829 is finished perl will clean up the allocated
3830 minlens when its all done. This was we don't
3831 have to worry about freeing them when we know
3832 they wont be used, which would be a pain.
3835 Newx( minnextp, 1, I32 );
3836 SAVEFREEPV(minnextp);
3839 StructCopy(data, &data_fake, scan_data_t);
3840 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3843 SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
3844 data_fake.last_found=newSVsv(data->last_found);
3848 data_fake.last_closep = &fake;
3849 data_fake.flags = 0;
3850 data_fake.pos_delta = delta;
3852 data_fake.flags |= SF_IS_INF;
3853 if ( flags & SCF_DO_STCLASS && !scan->flags
3854 && OP(scan) == IFMATCH ) { /* Lookahead */
3855 cl_init(pRExC_state, &intrnl);
3856 data_fake.start_class = &intrnl;
3857 f |= SCF_DO_STCLASS_AND;
3859 if (flags & SCF_WHILEM_VISITED_POS)
3860 f |= SCF_WHILEM_VISITED_POS;
3861 next = regnext(scan);
3862 nscan = NEXTOPER(NEXTOPER(scan));
3864 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
3865 last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3868 FAIL("Variable length lookbehind not implemented");
3870 else if (*minnextp > (I32)U8_MAX) {
3871 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3873 scan->flags = (U8)*minnextp;
3878 if (f & SCF_DO_STCLASS_AND) {
3879 const int was = (data->start_class->flags & ANYOF_EOS);
3881 cl_and(data->start_class, &intrnl);
3883 data->start_class->flags |= ANYOF_EOS;
3886 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3888 if (data_fake.flags & SF_HAS_EVAL)
3889 data->flags |= SF_HAS_EVAL;
3890 data->whilem_c = data_fake.whilem_c;
3891 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3892 if (RExC_rx->minlen<*minnextp)
3893 RExC_rx->minlen=*minnextp;
3894 SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
3895 SvREFCNT_dec(data_fake.last_found);
3897 if ( data_fake.minlen_fixed != minlenp )
3899 data->offset_fixed= data_fake.offset_fixed;
3900 data->minlen_fixed= data_fake.minlen_fixed;
3901 data->lookbehind_fixed+= scan->flags;
3903 if ( data_fake.minlen_float != minlenp )
3905 data->minlen_float= data_fake.minlen_float;
3906 data->offset_float_min=data_fake.offset_float_min;
3907 data->offset_float_max=data_fake.offset_float_max;
3908 data->lookbehind_float+= scan->flags;
3917 else if (OP(scan) == OPEN) {
3918 if (stopparen != (I32)ARG(scan))
3921 else if (OP(scan) == CLOSE) {
3922 if (stopparen == (I32)ARG(scan)) {
3925 if ((I32)ARG(scan) == is_par) {
3926 next = regnext(scan);
3928 if ( next && (OP(next) != WHILEM) && next < last)
3929 is_par = 0; /* Disable optimization */
3932 *(data->last_closep) = ARG(scan);
3934 else if (OP(scan) == EVAL) {
3936 data->flags |= SF_HAS_EVAL;
3938 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3939 if (flags & SCF_DO_SUBSTR) {
3940 SCAN_COMMIT(pRExC_state,data,minlenp);
3941 flags &= ~SCF_DO_SUBSTR;
3943 if (data && OP(scan)==ACCEPT) {
3944 data->flags |= SCF_SEEN_ACCEPT;
3949 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3951 if (flags & SCF_DO_SUBSTR) {
3952 SCAN_COMMIT(pRExC_state,data,minlenp);
3953 data->longest = &(data->longest_float);
3955 is_inf = is_inf_internal = 1;
3956 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3957 cl_anything(pRExC_state, data->start_class);
3958 flags &= ~SCF_DO_STCLASS;
3960 else if (OP(scan) == GPOS) {
3961 if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
3962 !(delta || is_inf || (data && data->pos_delta)))
3964 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
3965 RExC_rx->extflags |= RXf_ANCH_GPOS;
3966 if (RExC_rx->gofs < (U32)min)
3967 RExC_rx->gofs = min;
3969 RExC_rx->extflags |= RXf_GPOS_FLOAT;
3973 #ifdef TRIE_STUDY_OPT
3974 #ifdef FULL_TRIE_STUDY
3975 else if (PL_regkind[OP(scan)] == TRIE) {
3976 /* NOTE - There is similar code to this block above for handling
3977 BRANCH nodes on the initial study. If you change stuff here
3979 regnode *trie_node= scan;
3980 regnode *tail= regnext(scan);
3981 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3982 I32 max1 = 0, min1 = I32_MAX;
3983 struct regnode_charclass_class accum;
3985 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3986 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3987 if (flags & SCF_DO_STCLASS)
3988 cl_init_zero(pRExC_state, &accum);
3994 const regnode *nextbranch= NULL;
3997 for ( word=1 ; word <= trie->wordcount ; word++)
3999 I32 deltanext=0, minnext=0, f = 0, fake;
4000 struct regnode_charclass_class this_class;
4002 data_fake.flags = 0;
4004 data_fake.whilem_c = data->whilem_c;
4005 data_fake.last_closep = data->last_closep;
4008 data_fake.last_closep = &fake;
4009 data_fake.pos_delta = delta;
4010 if (flags & SCF_DO_STCLASS) {
4011 cl_init(pRExC_state, &this_class);
4012 data_fake.start_class = &this_class;
4013 f = SCF_DO_STCLASS_AND;
4015 if (flags & SCF_WHILEM_VISITED_POS)
4016 f |= SCF_WHILEM_VISITED_POS;
4018 if (trie->jump[word]) {
4020 nextbranch = trie_node + trie->jump[0];
4021 scan= trie_node + trie->jump[word];
4022 /* We go from the jump point to the branch that follows
4023 it. Note this means we need the vestigal unused branches
4024 even though they arent otherwise used.
4026 minnext = study_chunk(pRExC_state, &scan, minlenp,
4027 &deltanext, (regnode *)nextbranch, &data_fake,
4028 stopparen, recursed, NULL, f,depth+1);
4030 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
4031 nextbranch= regnext((regnode*)nextbranch);
4033 if (min1 > (I32)(minnext + trie->minlen))
4034 min1 = minnext + trie->minlen;
4035 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
4036 max1 = minnext + deltanext + trie->maxlen;
4037 if (deltanext == I32_MAX)
4038 is_inf = is_inf_internal = 1;
4040 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4042 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4043 if ( stopmin > min + min1)
4044 stopmin = min + min1;
4045 flags &= ~SCF_DO_SUBSTR;
4047 data->flags |= SCF_SEEN_ACCEPT;
4050 if (data_fake.flags & SF_HAS_EVAL)
4051 data->flags |= SF_HAS_EVAL;
4052 data->whilem_c = data_fake.whilem_c;
4054 if (flags & SCF_DO_STCLASS)
4055 cl_or(pRExC_state, &accum, &this_class);
4058 if (flags & SCF_DO_SUBSTR) {
4059 data->pos_min += min1;
4060 data->pos_delta += max1 - min1;
4061 if (max1 != min1 || is_inf)
4062 data->longest = &(data->longest_float);
4065 delta += max1 - min1;
4066 if (flags & SCF_DO_STCLASS_OR) {
4067 cl_or(pRExC_state, data->start_class, &accum);
4069 cl_and(data->start_class, and_withp);
4070 flags &= ~SCF_DO_STCLASS;
4073 else if (flags & SCF_DO_STCLASS_AND) {
4075 cl_and(data->start_class, &accum);
4076 flags &= ~SCF_DO_STCLASS;
4079 /* Switch to OR mode: cache the old value of
4080 * data->start_class */
4082 StructCopy(data->start_class, and_withp,
4083 struct regnode_charclass_class);
4084 flags &= ~SCF_DO_STCLASS_AND;
4085 StructCopy(&accum, data->start_class,
4086 struct regnode_charclass_class);
4087 flags |= SCF_DO_STCLASS_OR;
4088 data->start_class->flags |= ANYOF_EOS;
4095 else if (PL_regkind[OP(scan)] == TRIE) {
4096 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4099 min += trie->minlen;
4100 delta += (trie->maxlen - trie->minlen);
4101 flags &= ~SCF_DO_STCLASS; /* xxx */
4102 if (flags & SCF_DO_SUBSTR) {
4103 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
4104 data->pos_min += trie->minlen;
4105 data->pos_delta += (trie->maxlen - trie->minlen);
4106 if (trie->maxlen != trie->minlen)
4107 data->longest = &(data->longest_float);
4109 if (trie->jump) /* no more substrings -- for now /grr*/
4110 flags &= ~SCF_DO_SUBSTR;
4112 #endif /* old or new */
4113 #endif /* TRIE_STUDY_OPT */
4115 /* Else: zero-length, ignore. */
4116 scan = regnext(scan);
4121 stopparen = frame->stop;
4122 frame = frame->prev;
4123 goto fake_study_recurse;
4128 DEBUG_STUDYDATA("pre-fin:",data,depth);
4131 *deltap = is_inf_internal ? I32_MAX : delta;
4132 if (flags & SCF_DO_SUBSTR && is_inf)
4133 data->pos_delta = I32_MAX - data->pos_min;
4134 if (is_par > (I32)U8_MAX)
4136 if (is_par && pars==1 && data) {
4137 data->flags |= SF_IN_PAR;
4138 data->flags &= ~SF_HAS_PAR;
4140 else if (pars && data) {
4141 data->flags |= SF_HAS_PAR;
4142 data->flags &= ~SF_IN_PAR;
4144 if (flags & SCF_DO_STCLASS_OR)
4145 cl_and(data->start_class, and_withp);
4146 if (flags & SCF_TRIE_RESTUDY)
4147 data->flags |= SCF_TRIE_RESTUDY;
4149 DEBUG_STUDYDATA("post-fin:",data,depth);
4151 return min < stopmin ? min : stopmin;
4155 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4157 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4159 PERL_ARGS_ASSERT_ADD_DATA;
4161 Renewc(RExC_rxi->data,
4162 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4163 char, struct reg_data);
4165 Renew(RExC_rxi->data->what, count + n, U8);
4167 Newx(RExC_rxi->data->what, n, U8);
4168 RExC_rxi->data->count = count + n;
4169 Copy(s, RExC_rxi->data->what + count, n, U8);
4173 /*XXX: todo make this not included in a non debugging perl */
4174 #ifndef PERL_IN_XSUB_RE
4176 Perl_reginitcolors(pTHX)
4179 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4181 char *t = savepv(s);
4185 t = strchr(t, '\t');
4191 PL_colors[i] = t = (char *)"";
4196 PL_colors[i++] = (char *)"";
4203 #ifdef TRIE_STUDY_OPT
4204 #define CHECK_RESTUDY_GOTO \
4206 (data.flags & SCF_TRIE_RESTUDY) \
4210 #define CHECK_RESTUDY_GOTO
4214 - pregcomp - compile a regular expression into internal code
4216 * We can't allocate space until we know how big the compiled form will be,
4217 * but we can't compile it (and thus know how big it is) until we've got a
4218 * place to put the code. So we cheat: we compile it twice, once with code
4219 * generation turned off and size counting turned on, and once "for real".
4220 * This also means that we don't allocate space until we are sure that the
4221 * thing really will compile successfully, and we never have to move the
4222 * code and thus invalidate pointers into it. (Note that it has to be in
4223 * one piece because free() must be able to free it all.) [NB: not true in perl]
4225 * Beware that the optimization-preparation code in here knows about some
4226 * of the structure of the compiled regexp. [I'll say.]
4231 #ifndef PERL_IN_XSUB_RE
4232 #define RE_ENGINE_PTR &PL_core_reg_engine
4234 extern const struct regexp_engine my_reg_engine;
4235 #define RE_ENGINE_PTR &my_reg_engine
4238 #ifndef PERL_IN_XSUB_RE
4240 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
4243 HV * const table = GvHV(PL_hintgv);
4245 PERL_ARGS_ASSERT_PREGCOMP;
4247 /* Dispatch a request to compile a regexp to correct
4250 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
4251 GET_RE_DEBUG_FLAGS_DECL;
4252 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
4253 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
4255 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4258 return CALLREGCOMP_ENG(eng, pattern, flags);
4261 return Perl_re_compile(aTHX_ pattern, flags);
4266 Perl_re_compile(pTHX_ SV * const pattern, U32 pm_flags)
4271 register regexp_internal *ri;
4273 char *exp = SvPV(pattern, plen);
4274 char* xend = exp + plen;
4283 RExC_state_t RExC_state;
4284 RExC_state_t * const pRExC_state = &RExC_state;
4285 #ifdef TRIE_STUDY_OPT
4287 RExC_state_t copyRExC_state;
4289 GET_RE_DEBUG_FLAGS_DECL;
4291 PERL_ARGS_ASSERT_RE_COMPILE;
4293 DEBUG_r(if (!PL_colorset) reginitcolors());
4295 RExC_utf8 = RExC_orig_utf8 = SvUTF8(pattern);
4298 SV *dsv= sv_newmortal();
4299 RE_PV_QUOTED_DECL(s, RExC_utf8,
4300 dsv, exp, plen, 60);
4301 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
4302 PL_colors[4],PL_colors[5],s);
4305 /* Longjmp back to here if have to switch in midstream to utf8 */
4306 if (! RExC_orig_utf8) {
4307 JMPENV_PUSH(jump_ret);
4310 if (jump_ret != 0) {
4313 /* Here, we longjmped back. If the cause was other than changing to
4314 * utf8, pop our own setjmp, and longjmp to the correct handler */
4315 if (jump_ret != UTF8_LONGJMP) {
4317 JMPENV_JUMP(jump_ret);
4322 /* It's possible to write a regexp in ascii that represents Unicode
4323 codepoints outside of the byte range, such as via \x{100}. If we
4324 detect such a sequence we have to convert the entire pattern to utf8
4325 and then recompile, as our sizing calculation will have been based
4326 on 1 byte == 1 character, but we will need to use utf8 to encode
4327 at least some part of the pattern, and therefore must convert the whole
4330 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
4331 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
4332 exp = (char*)Perl_bytes_to_utf8(aTHX_ (U8*)SvPV(pattern, plen), &len);
4334 RExC_orig_utf8 = RExC_utf8 = 1;
4339 RExC_flags = pm_flags;
4343 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
4344 RExC_seen_evals = 0;
4347 /* First pass: determine size, legality. */
4355 RExC_emit = &PL_regdummy;
4356 RExC_whilem_seen = 0;
4357 RExC_open_parens = NULL;
4358 RExC_close_parens = NULL;
4360 RExC_paren_names = NULL;
4362 RExC_paren_name_list = NULL;
4364 RExC_recurse = NULL;
4365 RExC_recurse_count = 0;
4367 #if 0 /* REGC() is (currently) a NOP at the first pass.
4368 * Clever compilers notice this and complain. --jhi */
4369 REGC((U8)REG_MAGIC, (char*)RExC_emit);
4371 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4372 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4373 RExC_precomp = NULL;
4377 /* Here, finished first pass. Get rid of our setjmp, which we added for
4378 * efficiency only if the passed-in string wasn't in utf8, as shown by
4379 * RExC_orig_utf8. But if the first pass was redone, that variable will be
4380 * 1 here even though the original string wasn't utf8, but in this case
4381 * there will have been a long jump */
4382 if (jump_ret == UTF8_LONGJMP || ! RExC_orig_utf8) {
4386 PerlIO_printf(Perl_debug_log,
4387 "Required size %"IVdf" nodes\n"
4388 "Starting second pass (creation)\n",
4391 RExC_lastparse=NULL;
4393 /* Small enough for pointer-storage convention?
4394 If extralen==0, this means that we will not need long jumps. */
4395 if (RExC_size >= 0x10000L && RExC_extralen)
4396 RExC_size += RExC_extralen;
4399 if (RExC_whilem_seen > 15)
4400 RExC_whilem_seen = 15;
4402 /* Allocate space and zero-initialize. Note, the two step process
4403 of zeroing when in debug mode, thus anything assigned has to
4404 happen after that */
4405 rx = (REGEXP*) newSV_type(SVt_REGEXP);
4406 r = (struct regexp*)SvANY(rx);
4407 Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
4408 char, regexp_internal);
4409 if ( r == NULL || ri == NULL )
4410 FAIL("Regexp out of space");
4412 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4413 Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
4415 /* bulk initialize base fields with 0. */
4416 Zero(ri, sizeof(regexp_internal), char);
4419 /* non-zero initialization begins here */
4421 r->engine= RE_ENGINE_PTR;
4422 r->extflags = pm_flags;
4424 bool has_p = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
4425 bool has_minus = ((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD);
4426 bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
4427 U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
4428 >> RXf_PMf_STD_PMMOD_SHIFT);
4429 const char *fptr = STD_PAT_MODS; /*"msix"*/
4431 const STRLEN wraplen = plen + has_minus + has_p + has_runon
4432 + (sizeof(STD_PAT_MODS) - 1)
4433 + (sizeof("(?:)") - 1);
4435 p = sv_grow(MUTABLE_SV(rx), wraplen + 1);
4436 SvCUR_set(rx, wraplen);
4438 SvFLAGS(rx) |= SvUTF8(pattern);
4441 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
4443 char *r = p + (sizeof(STD_PAT_MODS) - 1) + has_minus - 1;
4444 char *colon = r + 1;
4447 while((ch = *fptr++)) {
4461 Copy(RExC_precomp, p, plen, char);
4462 assert ((RX_WRAPPED(rx) - p) < 16);
4463 r->pre_prefix = p - RX_WRAPPED(rx);
4472 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4474 if (RExC_seen & REG_SEEN_RECURSE) {
4475 Newxz(RExC_open_parens, RExC_npar,regnode *);
4476 SAVEFREEPV(RExC_open_parens);
4477 Newxz(RExC_close_parens,RExC_npar,regnode *);
4478 SAVEFREEPV(RExC_close_parens);
4481 /* Useful during FAIL. */
4482 #ifdef RE_TRACK_PATTERN_OFFSETS
4483 Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4484 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4485 "%s %"UVuf" bytes for offset annotations.\n",
4486 ri->u.offsets ? "Got" : "Couldn't get",
4487 (UV)((2*RExC_size+1) * sizeof(U32))));
4489 SetProgLen(ri,RExC_size);
4493 REH_CALL_COMP_BEGIN_HOOK(pRExC_state->rx);
4495 /* Second pass: emit code. */
4496 RExC_flags = pm_flags; /* don't let top level (?i) bleed */
4501 RExC_emit_start = ri->program;
4502 RExC_emit = ri->program;
4503 RExC_emit_bound = ri->program + RExC_size + 1;
4505 /* Store the count of eval-groups for security checks: */
4506 RExC_rx->seen_evals = RExC_seen_evals;
4507 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4508 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4512 /* XXXX To minimize changes to RE engine we always allocate
4513 3-units-long substrs field. */
4514 Newx(r->substrs, 1, struct reg_substr_data);
4515 if (RExC_recurse_count) {
4516 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4517 SAVEFREEPV(RExC_recurse);
4521 r->minlen = minlen = sawplus = sawopen = 0;
4522 Zero(r->substrs, 1, struct reg_substr_data);
4524 #ifdef TRIE_STUDY_OPT
4526 StructCopy(&zero_scan_data, &data, scan_data_t);
4527 copyRExC_state = RExC_state;
4530 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4532 RExC_state = copyRExC_state;
4533 if (seen & REG_TOP_LEVEL_BRANCHES)
4534 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4536 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4537 if (data.last_found) {
4538 SvREFCNT_dec(data.longest_fixed);
4539 SvREFCNT_dec(data.longest_float);
4540 SvREFCNT_dec(data.last_found);
4542 StructCopy(&zero_scan_data, &data, scan_data_t);
4545 StructCopy(&zero_scan_data, &data, scan_data_t);
4548 /* Dig out information for optimizations. */
4549 r->extflags = RExC_flags; /* was pm_op */
4550 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
4553 SvUTF8_on(rx); /* Unicode in it? */
4554 ri->regstclass = NULL;
4555 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
4556 r->intflags |= PREGf_NAUGHTY;
4557 scan = ri->program + 1; /* First BRANCH. */
4559 /* testing for BRANCH here tells us whether there is "must appear"
4560 data in the pattern. If there is then we can use it for optimisations */
4561 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
4563 STRLEN longest_float_length, longest_fixed_length;
4564 struct regnode_charclass_class ch_class; /* pointed to by data */
4566 I32 last_close = 0; /* pointed to by data */
4567 regnode *first= scan;
4568 regnode *first_next= regnext(first);
4571 * Skip introductions and multiplicators >= 1
4572 * so that we can extract the 'meat' of the pattern that must
4573 * match in the large if() sequence following.
4574 * NOTE that EXACT is NOT covered here, as it is normally
4575 * picked up by the optimiser separately.
4577 * This is unfortunate as the optimiser isnt handling lookahead
4578 * properly currently.
4581 while ((OP(first) == OPEN && (sawopen = 1)) ||
4582 /* An OR of *one* alternative - should not happen now. */
4583 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
4584 /* for now we can't handle lookbehind IFMATCH*/
4585 (OP(first) == IFMATCH && !first->flags) ||
4586 (OP(first) == PLUS) ||
4587 (OP(first) == MINMOD) ||
4588 /* An {n,m} with n>0 */
4589 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
4590 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
4593 * the only op that could be a regnode is PLUS, all the rest
4594 * will be regnode_1 or regnode_2.
4597 if (OP(first) == PLUS)
4600 first += regarglen[OP(first)];
4602 first = NEXTOPER(first);
4603 first_next= regnext(first);
4606 /* Starting-point info. */
4608 DEBUG_PEEP("first:",first,0);
4609 /* Ignore EXACT as we deal with it later. */
4610 if (PL_regkind[OP(first)] == EXACT) {
4611 if (OP(first) == EXACT)
4612 NOOP; /* Empty, get anchored substr later. */
4613 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4614 ri->regstclass = first;
4617 else if (PL_regkind[OP(first)] == TRIE &&
4618 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
4621 /* this can happen only on restudy */
4622 if ( OP(first) == TRIE ) {
4623 struct regnode_1 *trieop = (struct regnode_1 *)
4624 PerlMemShared_calloc(1, sizeof(struct regnode_1));
4625 StructCopy(first,trieop,struct regnode_1);
4626 trie_op=(regnode *)trieop;
4628 struct regnode_charclass *trieop = (struct regnode_charclass *)
4629 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
4630 StructCopy(first,trieop,struct regnode_charclass);
4631 trie_op=(regnode *)trieop;
4634 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4635 ri->regstclass = trie_op;
4638 else if (REGNODE_SIMPLE(OP(first)))
4639 ri->regstclass = first;
4640 else if (PL_regkind[OP(first)] == BOUND ||
4641 PL_regkind[OP(first)] == NBOUND)
4642 ri->regstclass = first;
4643 else if (PL_regkind[OP(first)] == BOL) {
4644 r->extflags |= (OP(first) == MBOL
4646 : (OP(first) == SBOL
4649 first = NEXTOPER(first);
4652 else if (OP(first) == GPOS) {
4653 r->extflags |= RXf_ANCH_GPOS;
4654 first = NEXTOPER(first);
4657 else if ((!sawopen || !RExC_sawback) &&
4658 (OP(first) == STAR &&
4659 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4660 !(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
4662 /* turn .* into ^.* with an implied $*=1 */
4664 (OP(NEXTOPER(first)) == REG_ANY)
4667 r->extflags |= type;
4668 r->intflags |= PREGf_IMPLICIT;
4669 first = NEXTOPER(first);
4672 if (sawplus && (!sawopen || !RExC_sawback)
4673 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4674 /* x+ must match at the 1st pos of run of x's */
4675 r->intflags |= PREGf_SKIP;
4677 /* Scan is after the zeroth branch, first is atomic matcher. */
4678 #ifdef TRIE_STUDY_OPT
4681 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4682 (IV)(first - scan + 1))
4686 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4687 (IV)(first - scan + 1))
4693 * If there's something expensive in the r.e., find the
4694 * longest literal string that must appear and make it the
4695 * regmust. Resolve ties in favor of later strings, since
4696 * the regstart check works with the beginning of the r.e.
4697 * and avoiding duplication strengthens checking. Not a
4698 * strong reason, but sufficient in the absence of others.
4699 * [Now we resolve ties in favor of the earlier string if
4700 * it happens that c_offset_min has been invalidated, since the
4701 * earlier string may buy us something the later one won't.]
4704 data.longest_fixed = newSVpvs("");
4705 data.longest_float = newSVpvs("");
4706 data.last_found = newSVpvs("");
4707 data.longest = &(data.longest_fixed);
4709 if (!ri->regstclass) {
4710 cl_init(pRExC_state, &ch_class);
4711 data.start_class = &ch_class;
4712 stclass_flag = SCF_DO_STCLASS_AND;
4713 } else /* XXXX Check for BOUND? */
4715 data.last_closep = &last_close;
4717 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4718 &data, -1, NULL, NULL,
4719 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4725 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4726 && data.last_start_min == 0 && data.last_end > 0
4727 && !RExC_seen_zerolen
4728 && !(RExC_seen & REG_SEEN_VERBARG)
4729 && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
4730 r->extflags |= RXf_CHECK_ALL;
4731 scan_commit(pRExC_state, &data,&minlen,0);
4732 SvREFCNT_dec(data.last_found);
4734 /* Note that code very similar to this but for anchored string
4735 follows immediately below, changes may need to be made to both.
4738 longest_float_length = CHR_SVLEN(data.longest_float);
4739 if (longest_float_length
4740 || (data.flags & SF_FL_BEFORE_EOL
4741 && (!(data.flags & SF_FL_BEFORE_MEOL)
4742 || (RExC_flags & RXf_PMf_MULTILINE))))
4746 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4747 && data.offset_fixed == data.offset_float_min
4748 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4749 goto remove_float; /* As in (a)+. */
4751 /* copy the information about the longest float from the reg_scan_data
4752 over to the program. */
4753 if (SvUTF8(data.longest_float)) {
4754 r->float_utf8 = data.longest_float;
4755 r->float_substr = NULL;
4757 r->float_substr = data.longest_float;
4758 r->float_utf8 = NULL;
4760 /* float_end_shift is how many chars that must be matched that
4761 follow this item. We calculate it ahead of time as once the
4762 lookbehind offset is added in we lose the ability to correctly
4764 ml = data.minlen_float ? *(data.minlen_float)
4765 : (I32)longest_float_length;
4766 r->float_end_shift = ml - data.offset_float_min
4767 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4768 + data.lookbehind_float;
4769 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4770 r->float_max_offset = data.offset_float_max;
4771 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4772 r->float_max_offset -= data.lookbehind_float;
4774 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4775 && (!(data.flags & SF_FL_BEFORE_MEOL)
4776 || (RExC_flags & RXf_PMf_MULTILINE)));
4777 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4781 r->float_substr = r->float_utf8 = NULL;
4782 SvREFCNT_dec(data.longest_float);
4783 longest_float_length = 0;
4786 /* Note that code very similar to this but for floating string
4787 is immediately above, changes may need to be made to both.
4790 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4791 if (longest_fixed_length
4792 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4793 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4794 || (RExC_flags & RXf_PMf_MULTILINE))))
4798 /* copy the information about the longest fixed
4799 from the reg_scan_data over to the program. */
4800 if (SvUTF8(data.longest_fixed)) {
4801 r->anchored_utf8 = data.longest_fixed;
4802 r->anchored_substr = NULL;
4804 r->anchored_substr = data.longest_fixed;
4805 r->anchored_utf8 = NULL;
4807 /* fixed_end_shift is how many chars that must be matched that
4808 follow this item. We calculate it ahead of time as once the
4809 lookbehind offset is added in we lose the ability to correctly
4811 ml = data.minlen_fixed ? *(data.minlen_fixed)
4812 : (I32)longest_fixed_length;
4813 r->anchored_end_shift = ml - data.offset_fixed
4814 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4815 + data.lookbehind_fixed;
4816 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4818 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4819 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4820 || (RExC_flags & RXf_PMf_MULTILINE)));
4821 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4824 r->anchored_substr = r->anchored_utf8 = NULL;
4825 SvREFCNT_dec(data.longest_fixed);
4826 longest_fixed_length = 0;
4829 && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
4830 ri->regstclass = NULL;
4831 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4833 && !(data.start_class->flags & ANYOF_EOS)
4834 && !cl_is_anything(data.start_class))
4836 const U32 n = add_data(pRExC_state, 1, "f");
4838 Newx(RExC_rxi->data->data[n], 1,
4839 struct regnode_charclass_class);
4840 StructCopy(data.start_class,
4841 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4842 struct regnode_charclass_class);
4843 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4844 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4845 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4846 regprop(r, sv, (regnode*)data.start_class);
4847 PerlIO_printf(Perl_debug_log,
4848 "synthetic stclass \"%s\".\n",
4849 SvPVX_const(sv));});
4852 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4853 if (longest_fixed_length > longest_float_length) {
4854 r->check_end_shift = r->anchored_end_shift;
4855 r->check_substr = r->anchored_substr;
4856 r->check_utf8 = r->anchored_utf8;
4857 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4858 if (r->extflags & RXf_ANCH_SINGLE)
4859 r->extflags |= RXf_NOSCAN;
4862 r->check_end_shift = r->float_end_shift;
4863 r->check_substr = r->float_substr;
4864 r->check_utf8 = r->float_utf8;
4865 r->check_offset_min = r->float_min_offset;
4866 r->check_offset_max = r->float_max_offset;
4868 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4869 This should be changed ASAP! */
4870 if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
4871 r->extflags |= RXf_USE_INTUIT;
4872 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4873 r->extflags |= RXf_INTUIT_TAIL;
4875 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4876 if ( (STRLEN)minlen < longest_float_length )
4877 minlen= longest_float_length;
4878 if ( (STRLEN)minlen < longest_fixed_length )
4879 minlen= longest_fixed_length;
4883 /* Several toplevels. Best we can is to set minlen. */
4885 struct regnode_charclass_class ch_class;
4888 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4890 scan = ri->program + 1;
4891 cl_init(pRExC_state, &ch_class);
4892 data.start_class = &ch_class;
4893 data.last_closep = &last_close;
4896 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4897 &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4901 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4902 = r->float_substr = r->float_utf8 = NULL;
4903 if (!(data.start_class->flags & ANYOF_EOS)
4904 && !cl_is_anything(data.start_class))
4906 const U32 n = add_data(pRExC_state, 1, "f");
4908 Newx(RExC_rxi->data->data[n], 1,
4909 struct regnode_charclass_class);
4910 StructCopy(data.start_class,
4911 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4912 struct regnode_charclass_class);
4913 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4914 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4915 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4916 regprop(r, sv, (regnode*)data.start_class);
4917 PerlIO_printf(Perl_debug_log,
4918 "synthetic stclass \"%s\".\n",
4919 SvPVX_const(sv));});
4923 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4924 the "real" pattern. */
4926 PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4927 (IV)minlen, (IV)r->minlen);
4929 r->minlenret = minlen;
4930 if (r->minlen < minlen)
4933 if (RExC_seen & REG_SEEN_GPOS)
4934 r->extflags |= RXf_GPOS_SEEN;
4935 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4936 r->extflags |= RXf_LOOKBEHIND_SEEN;
4937 if (RExC_seen & REG_SEEN_EVAL)
4938 r->extflags |= RXf_EVAL_SEEN;
4939 if (RExC_seen & REG_SEEN_CANY)
4940 r->extflags |= RXf_CANY_SEEN;
4941 if (RExC_seen & REG_SEEN_VERBARG)
4942 r->intflags |= PREGf_VERBARG_SEEN;
4943 if (RExC_seen & REG_SEEN_CUTGROUP)
4944 r->intflags |= PREGf_CUTGROUP_SEEN;
4945 if (RExC_paren_names)
4946 RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
4948 RXp_PAREN_NAMES(r) = NULL;
4950 #ifdef STUPID_PATTERN_CHECKS
4951 if (RX_PRELEN(rx) == 0)
4952 r->extflags |= RXf_NULL;
4953 if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
4954 /* XXX: this should happen BEFORE we compile */
4955 r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
4956 else if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
4957 r->extflags |= RXf_WHITE;
4958 else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
4959 r->extflags |= RXf_START_ONLY;
4961 if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
4962 /* XXX: this should happen BEFORE we compile */
4963 r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
4965 regnode *first = ri->program + 1;
4967 U8 nop = OP(NEXTOPER(first));
4969 if (PL_regkind[fop] == NOTHING && nop == END)
4970 r->extflags |= RXf_NULL;
4971 else if (PL_regkind[fop] == BOL && nop == END)
4972 r->extflags |= RXf_START_ONLY;
4973 else if (fop == PLUS && nop ==SPACE && OP(regnext(first))==END)
4974 r->extflags |= RXf_WHITE;
4978 if (RExC_paren_names) {
4979 ri->name_list_idx = add_data( pRExC_state, 1, "a" );
4980 ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
4983 ri->name_list_idx = 0;
4985 if (RExC_recurse_count) {
4986 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4987 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4988 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4991 Newxz(r->offs, RExC_npar, regexp_paren_pair);
4992 /* assume we don't need to swap parens around before we match */
4995 PerlIO_printf(Perl_debug_log,"Final program:\n");
4998 #ifdef RE_TRACK_PATTERN_OFFSETS
4999 DEBUG_OFFSETS_r(if (ri->u.offsets) {
5000 const U32 len = ri->u.offsets[0];
5002 GET_RE_DEBUG_FLAGS_DECL;
5003 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
5004 for (i = 1; i <= len; i++) {
5005 if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
5006 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
5007 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
5009 PerlIO_printf(Perl_debug_log, "\n");
5015 #undef RE_ENGINE_PTR
5019 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
5022 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
5024 PERL_UNUSED_ARG(value);
5026 if (flags & RXapif_FETCH) {
5027 return reg_named_buff_fetch(rx, key, flags);
5028 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
5029 Perl_croak_no_modify(aTHX);
5031 } else if (flags & RXapif_EXISTS) {
5032 return reg_named_buff_exists(rx, key, flags)
5035 } else if (flags & RXapif_REGNAMES) {
5036 return reg_named_buff_all(rx, flags);
5037 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
5038 return reg_named_buff_scalar(rx, flags);
5040 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
5046 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
5049 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
5050 PERL_UNUSED_ARG(lastkey);
5052 if (flags & RXapif_FIRSTKEY)
5053 return reg_named_buff_firstkey(rx, flags);
5054 else if (flags & RXapif_NEXTKEY)
5055 return reg_named_buff_nextkey(rx, flags);
5057 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
5063 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
5066 AV *retarray = NULL;
5068 struct regexp *const rx = (struct regexp *)SvANY(r);
5070 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
5072 if (flags & RXapif_ALL)
5075 if (rx && RXp_PAREN_NAMES(rx)) {
5076 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
5079 SV* sv_dat=HeVAL(he_str);
5080 I32 *nums=(I32*)SvPVX(sv_dat);
5081 for ( i=0; i<SvIVX(sv_dat); i++ ) {
5082 if ((I32)(rx->nparens) >= nums[i]
5083 && rx->offs[nums[i]].start != -1
5084 && rx->offs[nums[i]].end != -1)
5087 CALLREG_NUMBUF_FETCH(r,nums[i],ret);
5091 ret = newSVsv(&PL_sv_undef);
5094 av_push(retarray, ret);
5097 return newRV_noinc(MUTABLE_SV(retarray));
5104 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
5107 struct regexp *const rx = (struct regexp *)SvANY(r);
5109 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
5111 if (rx && RXp_PAREN_NAMES(rx)) {
5112 if (flags & RXapif_ALL) {
5113 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
5115 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
5129 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
5131 struct regexp *const rx = (struct regexp *)SvANY(r);
5133 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
5135 if ( rx && RXp_PAREN_NAMES(rx) ) {
5136 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
5138 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
5145 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
5147 struct regexp *const rx = (struct regexp *)SvANY(r);
5148 GET_RE_DEBUG_FLAGS_DECL;
5150 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
5152 if (rx && RXp_PAREN_NAMES(rx)) {
5153 HV *hv = RXp_PAREN_NAMES(rx);
5155 while ( (temphe = hv_iternext_flags(hv,0)) ) {
5158 SV* sv_dat = HeVAL(temphe);
5159 I32 *nums = (I32*)SvPVX(sv_dat);
5160 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5161 if ((I32)(rx->lastparen) >= nums[i] &&
5162 rx->offs[nums[i]].start != -1 &&
5163 rx->offs[nums[i]].end != -1)
5169 if (parno || flags & RXapif_ALL) {
5170 return newSVhek(HeKEY_hek(temphe));
5178 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
5183 struct regexp *const rx = (struct regexp *)SvANY(r);
5185 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
5187 if (rx && RXp_PAREN_NAMES(rx)) {
5188 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
5189 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
5190 } else if (flags & RXapif_ONE) {
5191 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
5192 av = MUTABLE_AV(SvRV(ret));
5193 length = av_len(av);
5195 return newSViv(length + 1);
5197 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
5201 return &PL_sv_undef;
5205 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
5207 struct regexp *const rx = (struct regexp *)SvANY(r);
5210 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
5212 if (rx && RXp_PAREN_NAMES(rx)) {
5213 HV *hv= RXp_PAREN_NAMES(rx);
5215 (void)hv_iterinit(hv);
5216 while ( (temphe = hv_iternext_flags(hv,0)) ) {
5219 SV* sv_dat = HeVAL(temphe);
5220 I32 *nums = (I32*)SvPVX(sv_dat);
5221 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5222 if ((I32)(rx->lastparen) >= nums[i] &&
5223 rx->offs[nums[i]].start != -1 &&
5224 rx->offs[nums[i]].end != -1)
5230 if (parno || flags & RXapif_ALL) {
5231 av_push(av, newSVhek(HeKEY_hek(temphe)));
5236 return newRV_noinc(MUTABLE_SV(av));
5240 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
5243 struct regexp *const rx = (struct regexp *)SvANY(r);
5248 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
5251 sv_setsv(sv,&PL_sv_undef);
5255 if (paren == RX_BUFF_IDX_PREMATCH && rx->offs[0].start != -1) {
5257 i = rx->offs[0].start;
5261 if (paren == RX_BUFF_IDX_POSTMATCH && rx->offs[0].end != -1) {
5263 s = rx->subbeg + rx->offs[0].end;
5264 i = rx->sublen - rx->offs[0].end;
5267 if ( 0 <= paren && paren <= (I32)rx->nparens &&
5268 (s1 = rx->offs[paren].start) != -1 &&
5269 (t1 = rx->offs[paren].end) != -1)
5273 s = rx->subbeg + s1;
5275 sv_setsv(sv,&PL_sv_undef);
5278 assert(rx->sublen >= (s - rx->subbeg) + i );
5280 const int oldtainted = PL_tainted;
5282 sv_setpvn(sv, s, i);
5283 PL_tainted = oldtainted;
5284 if ( (rx->extflags & RXf_CANY_SEEN)
5285 ? (RXp_MATCH_UTF8(rx)
5286 && (!i || is_utf8_string((U8*)s, i)))
5287 : (RXp_MATCH_UTF8(rx)) )
5294 if (RXp_MATCH_TAINTED(rx)) {
5295 if (SvTYPE(sv) >= SVt_PVMG) {
5296 MAGIC* const mg = SvMAGIC(sv);
5299 SvMAGIC_set(sv, mg->mg_moremagic);
5301 if ((mgt = SvMAGIC(sv))) {
5302 mg->mg_moremagic = mgt;
5303 SvMAGIC_set(sv, mg);
5313 sv_setsv(sv,&PL_sv_undef);
5319 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
5320 SV const * const value)
5322 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
5324 PERL_UNUSED_ARG(rx);
5325 PERL_UNUSED_ARG(paren);
5326 PERL_UNUSED_ARG(value);
5329 Perl_croak_no_modify(aTHX);
5333 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
5336 struct regexp *const rx = (struct regexp *)SvANY(r);
5340 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
5342 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
5344 /* $` / ${^PREMATCH} */
5345 case RX_BUFF_IDX_PREMATCH:
5346 if (rx->offs[0].start != -1) {
5347 i = rx->offs[0].start;
5355 /* $' / ${^POSTMATCH} */
5356 case RX_BUFF_IDX_POSTMATCH:
5357 if (rx->offs[0].end != -1) {
5358 i = rx->sublen - rx->offs[0].end;
5360 s1 = rx->offs[0].end;
5366 /* $& / ${^MATCH}, $1, $2, ... */
5368 if (paren <= (I32)rx->nparens &&
5369 (s1 = rx->offs[paren].start) != -1 &&
5370 (t1 = rx->offs[paren].end) != -1)
5375 if (ckWARN(WARN_UNINITIALIZED))
5376 report_uninit((const SV *)sv);
5381 if (i > 0 && RXp_MATCH_UTF8(rx)) {
5382 const char * const s = rx->subbeg + s1;
5387 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
5394 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
5396 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
5397 PERL_UNUSED_ARG(rx);
5401 return newSVpvs("Regexp");
5404 /* Scans the name of a named buffer from the pattern.
5405 * If flags is REG_RSN_RETURN_NULL returns null.
5406 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
5407 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
5408 * to the parsed name as looked up in the RExC_paren_names hash.
5409 * If there is an error throws a vFAIL().. type exception.
5412 #define REG_RSN_RETURN_NULL 0
5413 #define REG_RSN_RETURN_NAME 1
5414 #define REG_RSN_RETURN_DATA 2
5417 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
5419 char *name_start = RExC_parse;
5421 PERL_ARGS_ASSERT_REG_SCAN_NAME;
5423 if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
5424 /* skip IDFIRST by using do...while */
5427 RExC_parse += UTF8SKIP(RExC_parse);
5428 } while (isALNUM_utf8((U8*)RExC_parse));
5432 } while (isALNUM(*RExC_parse));
5437 = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
5438 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
5439 if ( flags == REG_RSN_RETURN_NAME)
5441 else if (flags==REG_RSN_RETURN_DATA) {
5444 if ( ! sv_name ) /* should not happen*/
5445 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
5446 if (RExC_paren_names)
5447 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
5449 sv_dat = HeVAL(he_str);
5451 vFAIL("Reference to nonexistent named group");
5455 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
5462 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
5463 int rem=(int)(RExC_end - RExC_parse); \
5472 if (RExC_lastparse!=RExC_parse) \
5473 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
5476 iscut ? "..." : "<" \
5479 PerlIO_printf(Perl_debug_log,"%16s",""); \
5482 num = RExC_size + 1; \
5484 num=REG_NODE_NUM(RExC_emit); \
5485 if (RExC_lastnum!=num) \
5486 PerlIO_printf(Perl_debug_log,"|%4d",num); \
5488 PerlIO_printf(Perl_debug_log,"|%4s",""); \
5489 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
5490 (int)((depth*2)), "", \
5494 RExC_lastparse=RExC_parse; \
5499 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
5500 DEBUG_PARSE_MSG((funcname)); \
5501 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
5503 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
5504 DEBUG_PARSE_MSG((funcname)); \
5505 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
5508 - reg - regular expression, i.e. main body or parenthesized thing
5510 * Caller must absorb opening parenthesis.
5512 * Combining parenthesis handling with the base level of regular expression
5513 * is a trifle forced, but the need to tie the tails of the branches to what
5514 * follows makes it hard to avoid.
5516 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
5518 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
5520 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
5524 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
5525 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
5528 register regnode *ret; /* Will be the head of the group. */
5529 register regnode *br;
5530 register regnode *lastbr;
5531 register regnode *ender = NULL;
5532 register I32 parno = 0;
5534 U32 oregflags = RExC_flags;
5535 bool have_branch = 0;
5537 I32 freeze_paren = 0;
5538 I32 after_freeze = 0;
5540 /* for (?g), (?gc), and (?o) warnings; warning
5541 about (?c) will warn about (?g) -- japhy */
5543 #define WASTED_O 0x01
5544 #define WASTED_G 0x02
5545 #define WASTED_C 0x04
5546 #define WASTED_GC (0x02|0x04)
5547 I32 wastedflags = 0x00;
5549 char * parse_start = RExC_parse; /* MJD */
5550 char * const oregcomp_parse = RExC_parse;
5552 GET_RE_DEBUG_FLAGS_DECL;
5554 PERL_ARGS_ASSERT_REG;
5555 DEBUG_PARSE("reg ");
5557 *flagp = 0; /* Tentatively. */
5560 /* Make an OPEN node, if parenthesized. */
5562 if ( *RExC_parse == '*') { /* (*VERB:ARG) */
5563 char *start_verb = RExC_parse;
5564 STRLEN verb_len = 0;
5565 char *start_arg = NULL;
5566 unsigned char op = 0;
5568 int internal_argval = 0; /* internal_argval is only useful if !argok */
5569 while ( *RExC_parse && *RExC_parse != ')' ) {
5570 if ( *RExC_parse == ':' ) {
5571 start_arg = RExC_parse + 1;
5577 verb_len = RExC_parse - start_verb;
5580 while ( *RExC_parse && *RExC_parse != ')' )
5582 if ( *RExC_parse != ')' )
5583 vFAIL("Unterminated verb pattern argument");
5584 if ( RExC_parse == start_arg )
5587 if ( *RExC_parse != ')' )
5588 vFAIL("Unterminated verb pattern");
5591 switch ( *start_verb ) {
5592 case 'A': /* (*ACCEPT) */
5593 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
5595 internal_argval = RExC_nestroot;
5598 case 'C': /* (*COMMIT) */
5599 if ( memEQs(start_verb,verb_len,"COMMIT") )
5602 case 'F': /* (*FAIL) */
5603 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
5608 case ':': /* (*:NAME) */
5609 case 'M': /* (*MARK:NAME) */
5610 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
5615 case 'P': /* (*PRUNE) */
5616 if ( memEQs(start_verb,verb_len,"PRUNE") )
5619 case 'S': /* (*SKIP) */
5620 if ( memEQs(start_verb,verb_len,"SKIP") )
5623 case 'T': /* (*THEN) */
5624 /* [19:06] <TimToady> :: is then */
5625 if ( memEQs(start_verb,verb_len,"THEN") ) {
5627 RExC_seen |= REG_SEEN_CUTGROUP;
5633 vFAIL3("Unknown verb pattern '%.*s'",
5634 verb_len, start_verb);
5637 if ( start_arg && internal_argval ) {
5638 vFAIL3("Verb pattern '%.*s' may not have an argument",
5639 verb_len, start_verb);
5640 } else if ( argok < 0 && !start_arg ) {
5641 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
5642 verb_len, start_verb);
5644 ret = reganode(pRExC_state, op, internal_argval);
5645 if ( ! internal_argval && ! SIZE_ONLY ) {
5647 SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
5648 ARG(ret) = add_data( pRExC_state, 1, "S" );
5649 RExC_rxi->data->data[ARG(ret)]=(void*)sv;
5656 if (!internal_argval)
5657 RExC_seen |= REG_SEEN_VERBARG;
5658 } else if ( start_arg ) {
5659 vFAIL3("Verb pattern '%.*s' may not have an argument",
5660 verb_len, start_verb);
5662 ret = reg_node(pRExC_state, op);
5664 nextchar(pRExC_state);
5667 if (*RExC_parse == '?') { /* (?...) */
5668 bool is_logical = 0;
5669 const char * const seqstart = RExC_parse;
5672 paren = *RExC_parse++;
5673 ret = NULL; /* For look-ahead/behind. */
5676 case 'P': /* (?P...) variants for those used to PCRE/Python */
5677 paren = *RExC_parse++;
5678 if ( paren == '<') /* (?P<...>) named capture */
5680 else if (paren == '>') { /* (?P>name) named recursion */
5681 goto named_recursion;
5683 else if (paren == '=') { /* (?P=...) named backref */
5684 /* this pretty much dupes the code for \k<NAME> in regatom(), if
5685 you change this make sure you change that */
5686 char* name_start = RExC_parse;
5688 SV *sv_dat = reg_scan_name(pRExC_state,
5689 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5690 if (RExC_parse == name_start || *RExC_parse != ')')
5691 vFAIL2("Sequence %.3s... not terminated",parse_start);
5694 num = add_data( pRExC_state, 1, "S" );
5695 RExC_rxi->data->data[num]=(void*)sv_dat;
5696 SvREFCNT_inc_simple_void(sv_dat);
5699 ret = reganode(pRExC_state,
5700 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5704 Set_Node_Offset(ret, parse_start+1);
5705 Set_Node_Cur_Length(ret); /* MJD */
5707 nextchar(pRExC_state);
5711 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5713 case '<': /* (?<...) */
5714 if (*RExC_parse == '!')
5716 else if (*RExC_parse != '=')
5722 case '\'': /* (?'...') */
5723 name_start= RExC_parse;
5724 svname = reg_scan_name(pRExC_state,
5725 SIZE_ONLY ? /* reverse test from the others */
5726 REG_RSN_RETURN_NAME :
5727 REG_RSN_RETURN_NULL);
5728 if (RExC_parse == name_start) {
5730 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5733 if (*RExC_parse != paren)
5734 vFAIL2("Sequence (?%c... not terminated",
5735 paren=='>' ? '<' : paren);
5739 if (!svname) /* shouldnt happen */
5741 "panic: reg_scan_name returned NULL");
5742 if (!RExC_paren_names) {
5743 RExC_paren_names= newHV();
5744 sv_2mortal(MUTABLE_SV(RExC_paren_names));
5746 RExC_paren_name_list= newAV();
5747 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
5750 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
5752 sv_dat = HeVAL(he_str);
5754 /* croak baby croak */
5756 "panic: paren_name hash element allocation failed");
5757 } else if ( SvPOK(sv_dat) ) {
5758 /* (?|...) can mean we have dupes so scan to check
5759 its already been stored. Maybe a flag indicating
5760 we are inside such a construct would be useful,
5761 but the arrays are likely to be quite small, so
5762 for now we punt -- dmq */
5763 IV count = SvIV(sv_dat);
5764 I32 *pv = (I32*)SvPVX(sv_dat);
5766 for ( i = 0 ; i < count ; i++ ) {
5767 if ( pv[i] == RExC_npar ) {
5773 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
5774 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
5775 pv[count] = RExC_npar;
5776 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
5779 (void)SvUPGRADE(sv_dat,SVt_PVNV);
5780 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
5782 SvIV_set(sv_dat, 1);
5785 if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
5786 SvREFCNT_dec(svname);
5789 /*sv_dump(sv_dat);*/
5791 nextchar(pRExC_state);
5793 goto capturing_parens;
5795 RExC_seen |= REG_SEEN_LOOKBEHIND;
5797 case '=': /* (?=...) */
5798 RExC_seen_zerolen++;
5800 case '!': /* (?!...) */
5801 RExC_seen_zerolen++;
5802 if (*RExC_parse == ')') {
5803 ret=reg_node(pRExC_state, OPFAIL);
5804 nextchar(pRExC_state);
5808 case '|': /* (?|...) */
5809 /* branch reset, behave like a (?:...) except that
5810 buffers in alternations share the same numbers */
5812 after_freeze = freeze_paren = RExC_npar;
5814 case ':': /* (?:...) */
5815 case '>': /* (?>...) */
5817 case '$': /* (?$...) */
5818 case '@': /* (?@...) */
5819 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
5821 case '#': /* (?#...) */
5822 while (*RExC_parse && *RExC_parse != ')')
5824 if (*RExC_parse != ')')
5825 FAIL("Sequence (?#... not terminated");
5826 nextchar(pRExC_state);
5829 case '0' : /* (?0) */
5830 case 'R' : /* (?R) */
5831 if (*RExC_parse != ')')
5832 FAIL("Sequence (?R) not terminated");
5833 ret = reg_node(pRExC_state, GOSTART);
5834 *flagp |= POSTPONED;
5835 nextchar(pRExC_state);
5838 { /* named and numeric backreferences */
5840 case '&': /* (?&NAME) */
5841 parse_start = RExC_parse - 1;
5844 SV *sv_dat = reg_scan_name(pRExC_state,
5845 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5846 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5848 goto gen_recurse_regop;
5851 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5853 vFAIL("Illegal pattern");
5855 goto parse_recursion;
5857 case '-': /* (?-1) */
5858 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5859 RExC_parse--; /* rewind to let it be handled later */
5863 case '1': case '2': case '3': case '4': /* (?1) */
5864 case '5': case '6': case '7': case '8': case '9':
5867 num = atoi(RExC_parse);
5868 parse_start = RExC_parse - 1; /* MJD */
5869 if (*RExC_parse == '-')
5871 while (isDIGIT(*RExC_parse))
5873 if (*RExC_parse!=')')
5874 vFAIL("Expecting close bracket");
5877 if ( paren == '-' ) {
5879 Diagram of capture buffer numbering.
5880 Top line is the normal capture buffer numbers
5881 Botton line is the negative indexing as from
5885 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5889 num = RExC_npar + num;
5892 vFAIL("Reference to nonexistent group");
5894 } else if ( paren == '+' ) {
5895 num = RExC_npar + num - 1;
5898 ret = reganode(pRExC_state, GOSUB, num);
5900 if (num > (I32)RExC_rx->nparens) {
5902 vFAIL("Reference to nonexistent group");
5904 ARG2L_SET( ret, RExC_recurse_count++);
5906 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5907 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5911 RExC_seen |= REG_SEEN_RECURSE;
5912 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5913 Set_Node_Offset(ret, parse_start); /* MJD */
5915 *flagp |= POSTPONED;
5916 nextchar(pRExC_state);
5918 } /* named and numeric backreferences */
5921 case '?': /* (??...) */
5923 if (*RExC_parse != '{') {
5925 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5928 *flagp |= POSTPONED;
5929 paren = *RExC_parse++;
5931 case '{': /* (?{...}) */
5936 char *s = RExC_parse;
5938 RExC_seen_zerolen++;
5939 RExC_seen |= REG_SEEN_EVAL;
5940 while (count && (c = *RExC_parse)) {
5951 if (*RExC_parse != ')') {
5953 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5957 OP_4tree *sop, *rop;
5958 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5961 Perl_save_re_context(aTHX);
5962 rop = sv_compile_2op(sv, &sop, "re", &pad);
5963 sop->op_private |= OPpREFCOUNTED;
5964 /* re_dup will OpREFCNT_inc */
5965 OpREFCNT_set(sop, 1);
5968 n = add_data(pRExC_state, 3, "nop");
5969 RExC_rxi->data->data[n] = (void*)rop;
5970 RExC_rxi->data->data[n+1] = (void*)sop;
5971 RExC_rxi->data->data[n+2] = (void*)pad;
5974 else { /* First pass */
5975 if (PL_reginterp_cnt < ++RExC_seen_evals
5977 /* No compiled RE interpolated, has runtime
5978 components ===> unsafe. */
5979 FAIL("Eval-group not allowed at runtime, use re 'eval'");
5980 if (PL_tainting && PL_tainted)
5981 FAIL("Eval-group in insecure regular expression");
5982 #if PERL_VERSION > 8
5983 if (IN_PERL_COMPILETIME)
5988 nextchar(pRExC_state);
5990 ret = reg_node(pRExC_state, LOGICAL);
5993 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5994 /* deal with the length of this later - MJD */
5997 ret = reganode(pRExC_state, EVAL, n);
5998 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5999 Set_Node_Offset(ret, parse_start);
6002 case '(': /* (?(?{...})...) and (?(?=...)...) */
6005 if (RExC_parse[0] == '?') { /* (?(?...)) */
6006 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
6007 || RExC_parse[1] == '<'
6008 || RExC_parse[1] == '{') { /* Lookahead or eval. */
6011 ret = reg_node(pRExC_state, LOGICAL);
6014 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
6018 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
6019 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
6021 char ch = RExC_parse[0] == '<' ? '>' : '\'';
6022 char *name_start= RExC_parse++;
6024 SV *sv_dat=reg_scan_name(pRExC_state,
6025 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6026 if (RExC_parse == name_start || *RExC_parse != ch)
6027 vFAIL2("Sequence (?(%c... not terminated",
6028 (ch == '>' ? '<' : ch));
6031 num = add_data( pRExC_state, 1, "S" );
6032 RExC_rxi->data->data[num]=(void*)sv_dat;
6033 SvREFCNT_inc_simple_void(sv_dat);
6035 ret = reganode(pRExC_state,NGROUPP,num);
6036 goto insert_if_check_paren;
6038 else if (RExC_parse[0] == 'D' &&
6039 RExC_parse[1] == 'E' &&
6040 RExC_parse[2] == 'F' &&
6041 RExC_parse[3] == 'I' &&
6042 RExC_parse[4] == 'N' &&
6043 RExC_parse[5] == 'E')
6045 ret = reganode(pRExC_state,DEFINEP,0);
6048 goto insert_if_check_paren;
6050 else if (RExC_parse[0] == 'R') {
6053 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
6054 parno = atoi(RExC_parse++);
6055 while (isDIGIT(*RExC_parse))
6057 } else if (RExC_parse[0] == '&') {
6060 sv_dat = reg_scan_name(pRExC_state,
6061 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6062 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
6064 ret = reganode(pRExC_state,INSUBP,parno);
6065 goto insert_if_check_paren;
6067 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
6070 parno = atoi(RExC_parse++);
6072 while (isDIGIT(*RExC_parse))
6074 ret = reganode(pRExC_state, GROUPP, parno);
6076 insert_if_check_paren:
6077 if ((c = *nextchar(pRExC_state)) != ')')
6078 vFAIL("Switch condition not recognized");
6080 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
6081 br = regbranch(pRExC_state, &flags, 1,depth+1);
6083 br = reganode(pRExC_state, LONGJMP, 0);
6085 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
6086 c = *nextchar(pRExC_state);
6091 vFAIL("(?(DEFINE)....) does not allow branches");
6092 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
6093 regbranch(pRExC_state, &flags, 1,depth+1);
6094 REGTAIL(pRExC_state, ret, lastbr);
6097 c = *nextchar(pRExC_state);
6102 vFAIL("Switch (?(condition)... contains too many branches");
6103 ender = reg_node(pRExC_state, TAIL);
6104 REGTAIL(pRExC_state, br, ender);
6106 REGTAIL(pRExC_state, lastbr, ender);
6107 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
6110 REGTAIL(pRExC_state, ret, ender);
6111 RExC_size++; /* XXX WHY do we need this?!!
6112 For large programs it seems to be required
6113 but I can't figure out why. -- dmq*/
6117 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
6121 RExC_parse--; /* for vFAIL to print correctly */
6122 vFAIL("Sequence (? incomplete");
6126 parse_flags: /* (?i) */
6128 U32 posflags = 0, negflags = 0;
6129 U32 *flagsp = &posflags;
6131 while (*RExC_parse) {
6132 /* && strchr("iogcmsx", *RExC_parse) */
6133 /* (?g), (?gc) and (?o) are useless here
6134 and must be globally applied -- japhy */
6135 switch (*RExC_parse) {
6136 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
6137 case ONCE_PAT_MOD: /* 'o' */
6138 case GLOBAL_PAT_MOD: /* 'g' */
6139 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6140 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
6141 if (! (wastedflags & wflagbit) ) {
6142 wastedflags |= wflagbit;
6145 "Useless (%s%c) - %suse /%c modifier",
6146 flagsp == &negflags ? "?-" : "?",
6148 flagsp == &negflags ? "don't " : "",
6155 case CONTINUE_PAT_MOD: /* 'c' */
6156 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6157 if (! (wastedflags & WASTED_C) ) {
6158 wastedflags |= WASTED_GC;
6161 "Useless (%sc) - %suse /gc modifier",
6162 flagsp == &negflags ? "?-" : "?",
6163 flagsp == &negflags ? "don't " : ""
6168 case KEEPCOPY_PAT_MOD: /* 'p' */
6169 if (flagsp == &negflags) {
6171 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
6173 *flagsp |= RXf_PMf_KEEPCOPY;
6177 if (flagsp == &negflags) {
6179 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
6183 wastedflags = 0; /* reset so (?g-c) warns twice */
6189 RExC_flags |= posflags;
6190 RExC_flags &= ~negflags;
6192 oregflags |= posflags;
6193 oregflags &= ~negflags;
6195 nextchar(pRExC_state);
6206 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
6211 }} /* one for the default block, one for the switch */
6218 ret = reganode(pRExC_state, OPEN, parno);
6221 RExC_nestroot = parno;
6222 if (RExC_seen & REG_SEEN_RECURSE
6223 && !RExC_open_parens[parno-1])
6225 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
6226 "Setting open paren #%"IVdf" to %d\n",
6227 (IV)parno, REG_NODE_NUM(ret)));
6228 RExC_open_parens[parno-1]= ret;
6231 Set_Node_Length(ret, 1); /* MJD */
6232 Set_Node_Offset(ret, RExC_parse); /* MJD */
6240 /* Pick up the branches, linking them together. */
6241 parse_start = RExC_parse; /* MJD */
6242 br = regbranch(pRExC_state, &flags, 1,depth+1);
6245 if (RExC_npar > after_freeze)
6246 after_freeze = RExC_npar;
6247 RExC_npar = freeze_paren;
6250 /* branch_len = (paren != 0); */
6254 if (*RExC_parse == '|') {
6255 if (!SIZE_ONLY && RExC_extralen) {
6256 reginsert(pRExC_state, BRANCHJ, br, depth+1);
6259 reginsert(pRExC_state, BRANCH, br, depth+1);
6260 Set_Node_Length(br, paren != 0);
6261 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
6265 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
6267 else if (paren == ':') {
6268 *flagp |= flags&SIMPLE;
6270 if (is_open) { /* Starts with OPEN. */
6271 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
6273 else if (paren != '?') /* Not Conditional */
6275 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
6277 while (*RExC_parse == '|') {
6278 if (!SIZE_ONLY && RExC_extralen) {
6279 ender = reganode(pRExC_state, LONGJMP,0);
6280 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
6283 RExC_extralen += 2; /* Account for LONGJMP. */
6284 nextchar(pRExC_state);
6286 if (RExC_npar > after_freeze)
6287 after_freeze = RExC_npar;
6288 RExC_npar = freeze_paren;
6290 br = regbranch(pRExC_state, &flags, 0, depth+1);
6294 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
6296 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
6299 if (have_branch || paren != ':') {
6300 /* Make a closing node, and hook it on the end. */
6303 ender = reg_node(pRExC_state, TAIL);
6306 ender = reganode(pRExC_state, CLOSE, parno);
6307 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
6308 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
6309 "Setting close paren #%"IVdf" to %d\n",
6310 (IV)parno, REG_NODE_NUM(ender)));
6311 RExC_close_parens[parno-1]= ender;
6312 if (RExC_nestroot == parno)
6315 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
6316 Set_Node_Length(ender,1); /* MJD */
6322 *flagp &= ~HASWIDTH;
6325 ender = reg_node(pRExC_state, SUCCEED);
6328 ender = reg_node(pRExC_state, END);
6330 assert(!RExC_opend); /* there can only be one! */
6335 REGTAIL(pRExC_state, lastbr, ender);
6337 if (have_branch && !SIZE_ONLY) {
6339 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
6341 /* Hook the tails of the branches to the closing node. */
6342 for (br = ret; br; br = regnext(br)) {
6343 const U8 op = PL_regkind[OP(br)];
6345 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
6347 else if (op == BRANCHJ) {
6348 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
6356 static const char parens[] = "=!<,>";
6358 if (paren && (p = strchr(parens, paren))) {
6359 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
6360 int flag = (p - parens) > 1;
6363 node = SUSPEND, flag = 0;
6364 reginsert(pRExC_state, node,ret, depth+1);
6365 Set_Node_Cur_Length(ret);
6366 Set_Node_Offset(ret, parse_start + 1);
6368 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
6372 /* Check for proper termination. */
6374 RExC_flags = oregflags;
6375 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
6376 RExC_parse = oregcomp_parse;
6377 vFAIL("Unmatched (");
6380 else if (!paren && RExC_parse < RExC_end) {
6381 if (*RExC_parse == ')') {
6383 vFAIL("Unmatched )");
6386 FAIL("Junk on end of regexp"); /* "Can't happen". */
6390 RExC_npar = after_freeze;
6395 - regbranch - one alternative of an | operator
6397 * Implements the concatenation operator.
6400 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
6403 register regnode *ret;
6404 register regnode *chain = NULL;
6405 register regnode *latest;
6406 I32 flags = 0, c = 0;
6407 GET_RE_DEBUG_FLAGS_DECL;
6409 PERL_ARGS_ASSERT_REGBRANCH;
6411 DEBUG_PARSE("brnc");
6416 if (!SIZE_ONLY && RExC_extralen)
6417 ret = reganode(pRExC_state, BRANCHJ,0);
6419 ret = reg_node(pRExC_state, BRANCH);
6420 Set_Node_Length(ret, 1);
6424 if (!first && SIZE_ONLY)
6425 RExC_extralen += 1; /* BRANCHJ */
6427 *flagp = WORST; /* Tentatively. */
6430 nextchar(pRExC_state);
6431 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
6433 latest = regpiece(pRExC_state, &flags,depth+1);
6434 if (latest == NULL) {
6435 if (flags & TRYAGAIN)
6439 else if (ret == NULL)
6441 *flagp |= flags&(HASWIDTH|POSTPONED);
6442 if (chain == NULL) /* First piece. */
6443 *flagp |= flags&SPSTART;
6446 REGTAIL(pRExC_state, chain, latest);
6451 if (chain == NULL) { /* Loop ran zero times. */
6452 chain = reg_node(pRExC_state, NOTHING);
6457 *flagp |= flags&SIMPLE;
6464 - regpiece - something followed by possible [*+?]
6466 * Note that the branching code sequences used for ? and the general cases
6467 * of * and + are somewhat optimized: they use the same NOTHING node as
6468 * both the endmarker for their branch list and the body of the last branch.
6469 * It might seem that this node could be dispensed with entirely, but the
6470 * endmarker role is not redundant.
6473 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6476 register regnode *ret;
6478 register char *next;
6480 const char * const origparse = RExC_parse;
6482 I32 max = REG_INFTY;
6484 const char *maxpos = NULL;
6485 GET_RE_DEBUG_FLAGS_DECL;
6487 PERL_ARGS_ASSERT_REGPIECE;
6489 DEBUG_PARSE("piec");
6491 ret = regatom(pRExC_state, &flags,depth+1);
6493 if (flags & TRYAGAIN)
6500 if (op == '{' && regcurly(RExC_parse)) {
6502 parse_start = RExC_parse; /* MJD */
6503 next = RExC_parse + 1;
6504 while (isDIGIT(*next) || *next == ',') {
6513 if (*next == '}') { /* got one */
6517 min = atoi(RExC_parse);
6521 maxpos = RExC_parse;
6523 if (!max && *maxpos != '0')
6524 max = REG_INFTY; /* meaning "infinity" */
6525 else if (max >= REG_INFTY)
6526 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
6528 nextchar(pRExC_state);
6531 if ((flags&SIMPLE)) {
6532 RExC_naughty += 2 + RExC_naughty / 2;
6533 reginsert(pRExC_state, CURLY, ret, depth+1);
6534 Set_Node_Offset(ret, parse_start+1); /* MJD */
6535 Set_Node_Cur_Length(ret);
6538 regnode * const w = reg_node(pRExC_state, WHILEM);
6541 REGTAIL(pRExC_state, ret, w);
6542 if (!SIZE_ONLY && RExC_extralen) {
6543 reginsert(pRExC_state, LONGJMP,ret, depth+1);
6544 reginsert(pRExC_state, NOTHING,ret, depth+1);
6545 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
6547 reginsert(pRExC_state, CURLYX,ret, depth+1);
6549 Set_Node_Offset(ret, parse_start+1);
6550 Set_Node_Length(ret,
6551 op == '{' ? (RExC_parse - parse_start) : 1);
6553 if (!SIZE_ONLY && RExC_extralen)
6554 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
6555 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
6557 RExC_whilem_seen++, RExC_extralen += 3;
6558 RExC_naughty += 4 + RExC_naughty; /* compound interest */
6567 vFAIL("Can't do {n,m} with n > m");
6569 ARG1_SET(ret, (U16)min);
6570 ARG2_SET(ret, (U16)max);
6582 #if 0 /* Now runtime fix should be reliable. */
6584 /* if this is reinstated, don't forget to put this back into perldiag:
6586 =item Regexp *+ operand could be empty at {#} in regex m/%s/
6588 (F) The part of the regexp subject to either the * or + quantifier
6589 could match an empty string. The {#} shows in the regular
6590 expression about where the problem was discovered.
6594 if (!(flags&HASWIDTH) && op != '?')
6595 vFAIL("Regexp *+ operand could be empty");
6598 parse_start = RExC_parse;
6599 nextchar(pRExC_state);
6601 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
6603 if (op == '*' && (flags&SIMPLE)) {
6604 reginsert(pRExC_state, STAR, ret, depth+1);
6608 else if (op == '*') {
6612 else if (op == '+' && (flags&SIMPLE)) {
6613 reginsert(pRExC_state, PLUS, ret, depth+1);
6617 else if (op == '+') {
6621 else if (op == '?') {
6626 if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
6627 ckWARN3reg(RExC_parse,
6628 "%.*s matches null string many times",
6629 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
6633 if (RExC_parse < RExC_end && *RExC_parse == '?') {
6634 nextchar(pRExC_state);
6635 reginsert(pRExC_state, MINMOD, ret, depth+1);
6636 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
6638 #ifndef REG_ALLOW_MINMOD_SUSPEND
6641 if (RExC_parse < RExC_end && *RExC_parse == '+') {
6643 nextchar(pRExC_state);
6644 ender = reg_node(pRExC_state, SUCCEED);
6645 REGTAIL(pRExC_state, ret, ender);
6646 reginsert(pRExC_state, SUSPEND, ret, depth+1);
6648 ender = reg_node(pRExC_state, TAIL);
6649 REGTAIL(pRExC_state, ret, ender);
6653 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
6655 vFAIL("Nested quantifiers");
6662 /* reg_namedseq(pRExC_state,UVp)
6664 This is expected to be called by a parser routine that has
6665 recognized '\N' and needs to handle the rest. RExC_parse is
6666 expected to point at the first char following the N at the time
6669 The \N may be inside (indicated by valuep not being NULL) or outside a
6672 \N may begin either a named sequence, or if outside a character class, mean
6673 to match a non-newline. For non single-quoted regexes, the tokenizer has
6674 attempted to decide which, and in the case of a named sequence converted it
6675 into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
6676 where c1... are the characters in the sequence. For single-quoted regexes,
6677 the tokenizer passes the \N sequence through unchanged; this code will not
6678 attempt to determine this nor expand those. The net effect is that if the
6679 beginning of the passed-in pattern isn't '{U+' or there is no '}', it
6680 signals that this \N occurrence means to match a non-newline.
6682 Only the \N{U+...} form should occur in a character class, for the same
6683 reason that '.' inside a character class means to just match a period: it
6684 just doesn't make sense.
6686 If valuep is non-null then it is assumed that we are parsing inside
6687 of a charclass definition and the first codepoint in the resolved
6688 string is returned via *valuep and the routine will return NULL.
6689 In this mode if a multichar string is returned from the charnames
6690 handler, a warning will be issued, and only the first char in the
6691 sequence will be examined. If the string returned is zero length
6692 then the value of *valuep is undefined and NON-NULL will
6693 be returned to indicate failure. (This will NOT be a valid pointer
6696 If valuep is null then it is assumed that we are parsing normal text and a
6697 new EXACT node is inserted into the program containing the resolved string,
6698 and a pointer to the new node is returned. But if the string is zero length
6699 a NOTHING node is emitted instead.
6701 On success RExC_parse is set to the char following the endbrace.
6702 Parsing failures will generate a fatal error via vFAIL(...)
6705 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep, I32 *flagp)
6707 char * endbrace; /* '}' following the name */
6708 regnode *ret = NULL;
6710 char* parse_start = RExC_parse - 2; /* points to the '\N' */
6714 GET_RE_DEBUG_FLAGS_DECL;
6716 PERL_ARGS_ASSERT_REG_NAMEDSEQ;
6720 /* The [^\n] meaning of \N ignores spaces and comments under the /x
6721 * modifier. The other meaning does not */
6722 p = (RExC_flags & RXf_PMf_EXTENDED)
6723 ? regwhite( pRExC_state, RExC_parse )
6726 /* Disambiguate between \N meaning a named character versus \N meaning
6727 * [^\n]. The former is assumed when it can't be the latter. */
6728 if (*p != '{' || regcurly(p)) {
6731 /* no bare \N in a charclass */
6732 vFAIL("\\N in a character class must be a named character: \\N{...}");
6734 nextchar(pRExC_state);
6735 ret = reg_node(pRExC_state, REG_ANY);
6736 *flagp |= HASWIDTH|SIMPLE;
6739 Set_Node_Length(ret, 1); /* MJD */
6743 /* Here, we have decided it should be a named sequence */
6745 /* The test above made sure that the next real character is a '{', but
6746 * under the /x modifier, it could be separated by space (or a comment and
6747 * \n) and this is not allowed (for consistency with \x{...} and the
6748 * tokenizer handling of \N{NAME}). */
6749 if (*RExC_parse != '{') {
6750 vFAIL("Missing braces on \\N{}");
6753 RExC_parse++; /* Skip past the '{' */
6755 if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
6756 || ! (endbrace == RExC_parse /* nothing between the {} */
6757 || (endbrace - RExC_parse >= 2 /* U+ (bad hex is checked below */
6758 && strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
6760 if (endbrace) RExC_parse = endbrace; /* position msg's '<--HERE' */
6761 vFAIL("\\N{NAME} must be resolved by the lexer");
6764 if (endbrace == RExC_parse) { /* empty: \N{} */
6766 RExC_parse = endbrace + 1;
6767 return reg_node(pRExC_state,NOTHING);
6771 ckWARNreg(RExC_parse,
6772 "Ignoring zero length \\N{} in character class"
6774 RExC_parse = endbrace + 1;
6777 return (regnode *) &RExC_parse; /* Invalid regnode pointer */
6780 REQUIRE_UTF8; /* named sequences imply Unicode semantics */
6781 RExC_parse += 2; /* Skip past the 'U+' */
6783 if (valuep) { /* In a bracketed char class */
6784 /* We only pay attention to the first char of
6785 multichar strings being returned. I kinda wonder
6786 if this makes sense as it does change the behaviour
6787 from earlier versions, OTOH that behaviour was broken
6788 as well. XXX Solution is to recharacterize as
6789 [rest-of-class]|multi1|multi2... */
6791 STRLEN length_of_hex;
6792 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6793 | PERL_SCAN_DISALLOW_PREFIX
6794 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6796 char * endchar = RExC_parse + strcspn(RExC_parse, ".}");
6797 if (endchar < endbrace) {
6798 ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
6801 length_of_hex = (STRLEN)(endchar - RExC_parse);
6802 *valuep = grok_hex(RExC_parse, &length_of_hex, &flags, NULL);
6804 /* The tokenizer should have guaranteed validity, but it's possible to
6805 * bypass it by using single quoting, so check */
6806 if (length_of_hex == 0
6807 || length_of_hex != (STRLEN)(endchar - RExC_parse) )
6809 RExC_parse += length_of_hex; /* Includes all the valid */
6810 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
6811 ? UTF8SKIP(RExC_parse)
6813 /* Guard against malformed utf8 */
6814 if (RExC_parse >= endchar) RExC_parse = endchar;
6815 vFAIL("Invalid hexadecimal number in \\N{U+...}");
6818 RExC_parse = endbrace + 1;
6819 if (endchar == endbrace) return NULL;
6821 ret = (regnode *) &RExC_parse; /* Invalid regnode pointer */
6823 else { /* Not a char class */
6824 char *s; /* String to put in generated EXACT node */
6825 STRLEN len = 0; /* Its current byte length */
6826 char *endchar; /* Points to '.' or '}' ending cur char in the input
6829 ret = reg_node(pRExC_state,
6830 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6833 /* Exact nodes can hold only a U8 length's of text = 255. Loop through
6834 * the input which is of the form now 'c1.c2.c3...}' until find the
6835 * ending brace or exceed length 255. The characters that exceed this
6836 * limit are dropped. The limit could be relaxed should it become
6837 * desirable by reparsing this as (?:\N{NAME}), so could generate
6838 * multiple EXACT nodes, as is done for just regular input. But this
6839 * is primarily a named character, and not intended to be a huge long
6840 * string, so 255 bytes should be good enough */
6842 STRLEN length_of_hex;
6843 I32 grok_flags = PERL_SCAN_ALLOW_UNDERSCORES
6844 | PERL_SCAN_DISALLOW_PREFIX
6845 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6846 UV cp; /* Ord of current character */
6848 /* Code points are separated by dots. If none, there is only one
6849 * code point, and is terminated by the brace */
6850 endchar = RExC_parse + strcspn(RExC_parse, ".}");
6852 /* The values are Unicode even on EBCDIC machines */
6853 length_of_hex = (STRLEN)(endchar - RExC_parse);
6854 cp = grok_hex(RExC_parse, &length_of_hex, &grok_flags, NULL);
6855 if ( length_of_hex == 0
6856 || length_of_hex != (STRLEN)(endchar - RExC_parse) )
6858 RExC_parse += length_of_hex; /* Includes all the valid */
6859 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
6860 ? UTF8SKIP(RExC_parse)
6862 /* Guard against malformed utf8 */
6863 if (RExC_parse >= endchar) RExC_parse = endchar;
6864 vFAIL("Invalid hexadecimal number in \\N{U+...}");
6867 if (! FOLD) { /* Not folding, just append to the string */
6870 /* Quit before adding this character if would exceed limit */
6871 if (len + UNISKIP(cp) > U8_MAX) break;
6873 unilen = reguni(pRExC_state, cp, s);
6878 } else { /* Folding, output the folded equivalent */
6879 STRLEN foldlen,numlen;
6880 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6881 cp = toFOLD_uni(cp, tmpbuf, &foldlen);
6883 /* Quit before exceeding size limit */
6884 if (len + foldlen > U8_MAX) break;
6886 for (foldbuf = tmpbuf;
6890 cp = utf8_to_uvchr(foldbuf, &numlen);
6892 const STRLEN unilen = reguni(pRExC_state, cp, s);
6895 /* In EBCDIC the numlen and unilen can differ. */
6897 if (numlen >= foldlen)
6901 break; /* "Can't happen." */
6905 /* Point to the beginning of the next character in the sequence. */
6906 RExC_parse = endchar + 1;
6908 /* Quit if no more characters */
6909 if (RExC_parse >= endbrace) break;
6914 if (RExC_parse < endbrace) {
6915 ckWARNreg(RExC_parse - 1,
6916 "Using just the first characters returned by \\N{}");
6919 RExC_size += STR_SZ(len);
6922 RExC_emit += STR_SZ(len);
6925 RExC_parse = endbrace + 1;
6927 *flagp |= HASWIDTH; /* Not SIMPLE, as that causes the engine to fail
6928 with malformed in t/re/pat_advanced.t */
6930 Set_Node_Cur_Length(ret); /* MJD */
6931 nextchar(pRExC_state);
6941 * It returns the code point in utf8 for the value in *encp.
6942 * value: a code value in the source encoding
6943 * encp: a pointer to an Encode object
6945 * If the result from Encode is not a single character,
6946 * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6949 S_reg_recode(pTHX_ const char value, SV **encp)
6952 SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
6953 const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
6954 const STRLEN newlen = SvCUR(sv);
6955 UV uv = UNICODE_REPLACEMENT;
6957 PERL_ARGS_ASSERT_REG_RECODE;
6961 ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6964 if (!newlen || numlen != newlen) {
6965 uv = UNICODE_REPLACEMENT;
6973 - regatom - the lowest level
6975 Try to identify anything special at the start of the pattern. If there
6976 is, then handle it as required. This may involve generating a single regop,
6977 such as for an assertion; or it may involve recursing, such as to
6978 handle a () structure.
6980 If the string doesn't start with something special then we gobble up
6981 as much literal text as we can.
6983 Once we have been able to handle whatever type of thing started the
6984 sequence, we return.
6986 Note: we have to be careful with escapes, as they can be both literal
6987 and special, and in the case of \10 and friends can either, depending
6988 on context. Specifically there are two seperate switches for handling
6989 escape sequences, with the one for handling literal escapes requiring
6990 a dummy entry for all of the special escapes that are actually handled
6995 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6998 register regnode *ret = NULL;
7000 char *parse_start = RExC_parse;
7001 GET_RE_DEBUG_FLAGS_DECL;
7002 DEBUG_PARSE("atom");
7003 *flagp = WORST; /* Tentatively. */
7005 PERL_ARGS_ASSERT_REGATOM;
7008 switch ((U8)*RExC_parse) {
7010 RExC_seen_zerolen++;
7011 nextchar(pRExC_state);
7012 if (RExC_flags & RXf_PMf_MULTILINE)
7013 ret = reg_node(pRExC_state, MBOL);
7014 else if (RExC_flags & RXf_PMf_SINGLELINE)
7015 ret = reg_node(pRExC_state, SBOL);
7017 ret = reg_node(pRExC_state, BOL);
7018 Set_Node_Length(ret, 1); /* MJD */
7021 nextchar(pRExC_state);
7023 RExC_seen_zerolen++;
7024 if (RExC_flags & RXf_PMf_MULTILINE)
7025 ret = reg_node(pRExC_state, MEOL);
7026 else if (RExC_flags & RXf_PMf_SINGLELINE)
7027 ret = reg_node(pRExC_state, SEOL);
7029 ret = reg_node(pRExC_state, EOL);
7030 Set_Node_Length(ret, 1); /* MJD */
7033 nextchar(pRExC_state);
7034 if (RExC_flags & RXf_PMf_SINGLELINE)
7035 ret = reg_node(pRExC_state, SANY);
7037 ret = reg_node(pRExC_state, REG_ANY);
7038 *flagp |= HASWIDTH|SIMPLE;
7040 Set_Node_Length(ret, 1); /* MJD */
7044 char * const oregcomp_parse = ++RExC_parse;
7045 ret = regclass(pRExC_state,depth+1);
7046 if (*RExC_parse != ']') {
7047 RExC_parse = oregcomp_parse;
7048 vFAIL("Unmatched [");
7050 nextchar(pRExC_state);
7051 *flagp |= HASWIDTH|SIMPLE;
7052 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
7056 nextchar(pRExC_state);
7057 ret = reg(pRExC_state, 1, &flags,depth+1);
7059 if (flags & TRYAGAIN) {
7060 if (RExC_parse == RExC_end) {
7061 /* Make parent create an empty node if needed. */
7069 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
7073 if (flags & TRYAGAIN) {
7077 vFAIL("Internal urp");
7078 /* Supposed to be caught earlier. */
7081 if (!regcurly(RExC_parse)) {
7090 vFAIL("Quantifier follows nothing");
7098 len=0; /* silence a spurious compiler warning */
7099 if ((cp = what_len_TRICKYFOLD_safe(RExC_parse,RExC_end,UTF,len))) {
7100 *flagp |= HASWIDTH; /* could be SIMPLE too, but needs a handler in regexec.regrepeat */
7101 RExC_parse+=len-1; /* we get one from nextchar() as well. :-( */
7102 ret = reganode(pRExC_state, FOLDCHAR, cp);
7103 Set_Node_Length(ret, 1); /* MJD */
7104 nextchar(pRExC_state); /* kill whitespace under /x */
7112 This switch handles escape sequences that resolve to some kind
7113 of special regop and not to literal text. Escape sequnces that
7114 resolve to literal text are handled below in the switch marked
7117 Every entry in this switch *must* have a corresponding entry
7118 in the literal escape switch. However, the opposite is not
7119 required, as the default for this switch is to jump to the
7120 literal text handling code.
7122 switch ((U8)*++RExC_parse) {
7127 /* Special Escapes */
7129 RExC_seen_zerolen++;
7130 ret = reg_node(pRExC_state, SBOL);
7132 goto finish_meta_pat;
7134 ret = reg_node(pRExC_state, GPOS);
7135 RExC_seen |= REG_SEEN_GPOS;
7137 goto finish_meta_pat;
7139 RExC_seen_zerolen++;
7140 ret = reg_node(pRExC_state, KEEPS);
7142 /* XXX:dmq : disabling in-place substitution seems to
7143 * be necessary here to avoid cases of memory corruption, as
7144 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
7146 RExC_seen |= REG_SEEN_LOOKBEHIND;
7147 goto finish_meta_pat;
7149 ret = reg_node(pRExC_state, SEOL);
7151 RExC_seen_zerolen++; /* Do not optimize RE away */
7152 goto finish_meta_pat;
7154 ret = reg_node(pRExC_state, EOS);
7156 RExC_seen_zerolen++; /* Do not optimize RE away */
7157 goto finish_meta_pat;
7159 ret = reg_node(pRExC_state, CANY);
7160 RExC_seen |= REG_SEEN_CANY;
7161 *flagp |= HASWIDTH|SIMPLE;
7162 goto finish_meta_pat;
7164 ret = reg_node(pRExC_state, CLUMP);
7166 goto finish_meta_pat;
7168 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
7169 *flagp |= HASWIDTH|SIMPLE;
7170 goto finish_meta_pat;
7172 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
7173 *flagp |= HASWIDTH|SIMPLE;
7174 goto finish_meta_pat;
7176 RExC_seen_zerolen++;
7177 RExC_seen |= REG_SEEN_LOOKBEHIND;
7178 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
7180 goto finish_meta_pat;
7182 RExC_seen_zerolen++;
7183 RExC_seen |= REG_SEEN_LOOKBEHIND;
7184 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
7186 goto finish_meta_pat;
7188 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
7189 *flagp |= HASWIDTH|SIMPLE;
7190 goto finish_meta_pat;
7192 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
7193 *flagp |= HASWIDTH|SIMPLE;
7194 goto finish_meta_pat;
7196 ret = reg_node(pRExC_state, DIGIT);
7197 *flagp |= HASWIDTH|SIMPLE;
7198 goto finish_meta_pat;
7200 ret = reg_node(pRExC_state, NDIGIT);
7201 *flagp |= HASWIDTH|SIMPLE;
7202 goto finish_meta_pat;
7204 ret = reg_node(pRExC_state, LNBREAK);
7205 *flagp |= HASWIDTH|SIMPLE;
7206 goto finish_meta_pat;
7208 ret = reg_node(pRExC_state, HORIZWS);
7209 *flagp |= HASWIDTH|SIMPLE;
7210 goto finish_meta_pat;
7212 ret = reg_node(pRExC_state, NHORIZWS);
7213 *flagp |= HASWIDTH|SIMPLE;
7214 goto finish_meta_pat;
7216 ret = reg_node(pRExC_state, VERTWS);
7217 *flagp |= HASWIDTH|SIMPLE;
7218 goto finish_meta_pat;
7220 ret = reg_node(pRExC_state, NVERTWS);
7221 *flagp |= HASWIDTH|SIMPLE;
7223 nextchar(pRExC_state);
7224 Set_Node_Length(ret, 2); /* MJD */
7229 char* const oldregxend = RExC_end;
7231 char* parse_start = RExC_parse - 2;
7234 if (RExC_parse[1] == '{') {
7235 /* a lovely hack--pretend we saw [\pX] instead */
7236 RExC_end = strchr(RExC_parse, '}');
7238 const U8 c = (U8)*RExC_parse;
7240 RExC_end = oldregxend;
7241 vFAIL2("Missing right brace on \\%c{}", c);
7246 RExC_end = RExC_parse + 2;
7247 if (RExC_end > oldregxend)
7248 RExC_end = oldregxend;
7252 ret = regclass(pRExC_state,depth+1);
7254 RExC_end = oldregxend;
7257 Set_Node_Offset(ret, parse_start + 2);
7258 Set_Node_Cur_Length(ret);
7259 nextchar(pRExC_state);
7260 *flagp |= HASWIDTH|SIMPLE;
7264 /* Handle \N and \N{NAME} here and not below because it can be
7265 multicharacter. join_exact() will join them up later on.
7266 Also this makes sure that things like /\N{BLAH}+/ and
7267 \N{BLAH} being multi char Just Happen. dmq*/
7269 ret= reg_namedseq(pRExC_state, NULL, flagp);
7271 case 'k': /* Handle \k<NAME> and \k'NAME' */
7274 char ch= RExC_parse[1];
7275 if (ch != '<' && ch != '\'' && ch != '{') {
7277 vFAIL2("Sequence %.2s... not terminated",parse_start);
7279 /* this pretty much dupes the code for (?P=...) in reg(), if
7280 you change this make sure you change that */
7281 char* name_start = (RExC_parse += 2);
7283 SV *sv_dat = reg_scan_name(pRExC_state,
7284 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7285 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
7286 if (RExC_parse == name_start || *RExC_parse != ch)
7287 vFAIL2("Sequence %.3s... not terminated",parse_start);
7290 num = add_data( pRExC_state, 1, "S" );
7291 RExC_rxi->data->data[num]=(void*)sv_dat;
7292 SvREFCNT_inc_simple_void(sv_dat);
7296 ret = reganode(pRExC_state,
7297 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
7301 /* override incorrect value set in reganode MJD */
7302 Set_Node_Offset(ret, parse_start+1);
7303 Set_Node_Cur_Length(ret); /* MJD */
7304 nextchar(pRExC_state);
7310 case '1': case '2': case '3': case '4':
7311 case '5': case '6': case '7': case '8': case '9':
7314 bool isg = *RExC_parse == 'g';
7319 if (*RExC_parse == '{') {
7323 if (*RExC_parse == '-') {
7327 if (hasbrace && !isDIGIT(*RExC_parse)) {
7328 if (isrel) RExC_parse--;
7330 goto parse_named_seq;
7332 num = atoi(RExC_parse);
7333 if (isg && num == 0)
7334 vFAIL("Reference to invalid group 0");
7336 num = RExC_npar - num;
7338 vFAIL("Reference to nonexistent or unclosed group");
7340 if (!isg && num > 9 && num >= RExC_npar)
7343 char * const parse_start = RExC_parse - 1; /* MJD */
7344 while (isDIGIT(*RExC_parse))
7346 if (parse_start == RExC_parse - 1)
7347 vFAIL("Unterminated \\g... pattern");
7349 if (*RExC_parse != '}')
7350 vFAIL("Unterminated \\g{...} pattern");
7354 if (num > (I32)RExC_rx->nparens)
7355 vFAIL("Reference to nonexistent group");
7358 ret = reganode(pRExC_state,
7359 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
7363 /* override incorrect value set in reganode MJD */
7364 Set_Node_Offset(ret, parse_start+1);
7365 Set_Node_Cur_Length(ret); /* MJD */
7367 nextchar(pRExC_state);
7372 if (RExC_parse >= RExC_end)
7373 FAIL("Trailing \\");
7376 /* Do not generate "unrecognized" warnings here, we fall
7377 back into the quick-grab loop below */
7384 if (RExC_flags & RXf_PMf_EXTENDED) {
7385 if ( reg_skipcomment( pRExC_state ) )
7392 register STRLEN len;
7397 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
7399 parse_start = RExC_parse - 1;
7405 ret = reg_node(pRExC_state,
7406 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
7408 for (len = 0, p = RExC_parse - 1;
7409 len < 127 && p < RExC_end;
7412 char * const oldp = p;
7414 if (RExC_flags & RXf_PMf_EXTENDED)
7415 p = regwhite( pRExC_state, p );
7420 if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
7421 goto normal_default;
7431 /* Literal Escapes Switch
7433 This switch is meant to handle escape sequences that
7434 resolve to a literal character.
7436 Every escape sequence that represents something
7437 else, like an assertion or a char class, is handled
7438 in the switch marked 'Special Escapes' above in this
7439 routine, but also has an entry here as anything that
7440 isn't explicitly mentioned here will be treated as
7441 an unescaped equivalent literal.
7445 /* These are all the special escapes. */
7449 if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
7450 goto normal_default;
7451 case 'A': /* Start assertion */
7452 case 'b': case 'B': /* Word-boundary assertion*/
7453 case 'C': /* Single char !DANGEROUS! */
7454 case 'd': case 'D': /* digit class */
7455 case 'g': case 'G': /* generic-backref, pos assertion */
7456 case 'h': case 'H': /* HORIZWS */
7457 case 'k': case 'K': /* named backref, keep marker */
7458 case 'N': /* named char sequence */
7459 case 'p': case 'P': /* Unicode property */
7460 case 'R': /* LNBREAK */
7461 case 's': case 'S': /* space class */
7462 case 'v': case 'V': /* VERTWS */
7463 case 'w': case 'W': /* word class */
7464 case 'X': /* eXtended Unicode "combining character sequence" */
7465 case 'z': case 'Z': /* End of line/string assertion */
7469 /* Anything after here is an escape that resolves to a
7470 literal. (Except digits, which may or may not)
7489 ender = ASCII_TO_NATIVE('\033');
7493 ender = ASCII_TO_NATIVE('\007');
7498 STRLEN brace_len = len;
7500 const char* error_msg;
7502 bool valid = grok_bslash_o(p,
7509 RExC_parse = p; /* going to die anyway; point
7510 to exact spot of failure */
7517 if (PL_encoding && ender < 0x100) {
7518 goto recode_encoding;
7527 char* const e = strchr(p, '}');
7531 vFAIL("Missing right brace on \\x{}");
7534 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7535 | PERL_SCAN_DISALLOW_PREFIX;
7536 STRLEN numlen = e - p - 1;
7537 ender = grok_hex(p + 1, &numlen, &flags, NULL);
7544 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7546 ender = grok_hex(p, &numlen, &flags, NULL);
7549 if (PL_encoding && ender < 0x100)
7550 goto recode_encoding;
7554 ender = grok_bslash_c(*p++, SIZE_ONLY);
7556 case '0': case '1': case '2': case '3':case '4':
7557 case '5': case '6': case '7': case '8':case '9':
7559 (isOCTAL(p[1]) && atoi(p) >= RExC_npar))
7561 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
7563 ender = grok_oct(p, &numlen, &flags, NULL);
7573 if (PL_encoding && ender < 0x100)
7574 goto recode_encoding;
7578 SV* enc = PL_encoding;
7579 ender = reg_recode((const char)(U8)ender, &enc);
7580 if (!enc && SIZE_ONLY)
7581 ckWARNreg(p, "Invalid escape in the specified encoding");
7587 FAIL("Trailing \\");
7590 if (!SIZE_ONLY&& isALPHA(*p))
7591 ckWARN2reg(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
7592 goto normal_default;
7597 if (UTF8_IS_START(*p) && UTF) {
7599 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
7600 &numlen, UTF8_ALLOW_DEFAULT);
7607 if ( RExC_flags & RXf_PMf_EXTENDED)
7608 p = regwhite( pRExC_state, p );
7610 /* Prime the casefolded buffer. */
7611 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
7613 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
7618 /* Emit all the Unicode characters. */
7620 for (foldbuf = tmpbuf;
7622 foldlen -= numlen) {
7623 ender = utf8_to_uvchr(foldbuf, &numlen);
7625 const STRLEN unilen = reguni(pRExC_state, ender, s);
7628 /* In EBCDIC the numlen
7629 * and unilen can differ. */
7631 if (numlen >= foldlen)
7635 break; /* "Can't happen." */
7639 const STRLEN unilen = reguni(pRExC_state, ender, s);
7648 REGC((char)ender, s++);
7654 /* Emit all the Unicode characters. */
7656 for (foldbuf = tmpbuf;
7658 foldlen -= numlen) {
7659 ender = utf8_to_uvchr(foldbuf, &numlen);
7661 const STRLEN unilen = reguni(pRExC_state, ender, s);
7664 /* In EBCDIC the numlen
7665 * and unilen can differ. */
7667 if (numlen >= foldlen)
7675 const STRLEN unilen = reguni(pRExC_state, ender, s);
7684 REGC((char)ender, s++);
7688 Set_Node_Cur_Length(ret); /* MJD */
7689 nextchar(pRExC_state);
7691 /* len is STRLEN which is unsigned, need to copy to signed */
7694 vFAIL("Internal disaster");
7698 if (len == 1 && UNI_IS_INVARIANT(ender))
7702 RExC_size += STR_SZ(len);
7705 RExC_emit += STR_SZ(len);
7715 S_regwhite( RExC_state_t *pRExC_state, char *p )
7717 const char *e = RExC_end;
7719 PERL_ARGS_ASSERT_REGWHITE;
7724 else if (*p == '#') {
7733 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7741 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
7742 Character classes ([:foo:]) can also be negated ([:^foo:]).
7743 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
7744 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
7745 but trigger failures because they are currently unimplemented. */
7747 #define POSIXCC_DONE(c) ((c) == ':')
7748 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
7749 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
7752 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
7755 I32 namedclass = OOB_NAMEDCLASS;
7757 PERL_ARGS_ASSERT_REGPPOSIXCC;
7759 if (value == '[' && RExC_parse + 1 < RExC_end &&
7760 /* I smell either [: or [= or [. -- POSIX has been here, right? */
7761 POSIXCC(UCHARAT(RExC_parse))) {
7762 const char c = UCHARAT(RExC_parse);
7763 char* const s = RExC_parse++;
7765 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
7767 if (RExC_parse == RExC_end)
7768 /* Grandfather lone [:, [=, [. */
7771 const char* const t = RExC_parse++; /* skip over the c */
7774 if (UCHARAT(RExC_parse) == ']') {
7775 const char *posixcc = s + 1;
7776 RExC_parse++; /* skip over the ending ] */
7779 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
7780 const I32 skip = t - posixcc;
7782 /* Initially switch on the length of the name. */
7785 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
7786 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
7789 /* Names all of length 5. */
7790 /* alnum alpha ascii blank cntrl digit graph lower
7791 print punct space upper */
7792 /* Offset 4 gives the best switch position. */
7793 switch (posixcc[4]) {
7795 if (memEQ(posixcc, "alph", 4)) /* alpha */
7796 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
7799 if (memEQ(posixcc, "spac", 4)) /* space */
7800 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
7803 if (memEQ(posixcc, "grap", 4)) /* graph */
7804 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
7807 if (memEQ(posixcc, "asci", 4)) /* ascii */
7808 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
7811 if (memEQ(posixcc, "blan", 4)) /* blank */
7812 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
7815 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
7816 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
7819 if (memEQ(posixcc, "alnu", 4)) /* alnum */
7820 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
7823 if (memEQ(posixcc, "lowe", 4)) /* lower */
7824 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
7825 else if (memEQ(posixcc, "uppe", 4)) /* upper */
7826 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
7829 if (memEQ(posixcc, "digi", 4)) /* digit */
7830 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
7831 else if (memEQ(posixcc, "prin", 4)) /* print */
7832 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
7833 else if (memEQ(posixcc, "punc", 4)) /* punct */
7834 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
7839 if (memEQ(posixcc, "xdigit", 6))
7840 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
7844 if (namedclass == OOB_NAMEDCLASS)
7845 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
7847 assert (posixcc[skip] == ':');
7848 assert (posixcc[skip+1] == ']');
7849 } else if (!SIZE_ONLY) {
7850 /* [[=foo=]] and [[.foo.]] are still future. */
7852 /* adjust RExC_parse so the warning shows after
7854 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
7856 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7859 /* Maternal grandfather:
7860 * "[:" ending in ":" but not in ":]" */
7870 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
7874 PERL_ARGS_ASSERT_CHECKPOSIXCC;
7876 if (POSIXCC(UCHARAT(RExC_parse))) {
7877 const char *s = RExC_parse;
7878 const char c = *s++;
7882 if (*s && c == *s && s[1] == ']') {
7884 "POSIX syntax [%c %c] belongs inside character classes",
7887 /* [[=foo=]] and [[.foo.]] are still future. */
7888 if (POSIXCC_NOTYET(c)) {
7889 /* adjust RExC_parse so the error shows after
7891 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
7893 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7900 #define _C_C_T_(NAME,TEST,WORD) \
7903 ANYOF_CLASS_SET(ret, ANYOF_##NAME); \
7905 for (value = 0; value < 256; value++) \
7907 ANYOF_BITMAP_SET(ret, value); \
7912 case ANYOF_N##NAME: \
7914 ANYOF_CLASS_SET(ret, ANYOF_N##NAME); \
7916 for (value = 0; value < 256; value++) \
7918 ANYOF_BITMAP_SET(ret, value); \
7924 #define _C_C_T_NOLOC_(NAME,TEST,WORD) \
7926 for (value = 0; value < 256; value++) \
7928 ANYOF_BITMAP_SET(ret, value); \
7932 case ANYOF_N##NAME: \
7933 for (value = 0; value < 256; value++) \
7935 ANYOF_BITMAP_SET(ret, value); \
7941 We dont use PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS as the direct test
7942 so that it is possible to override the option here without having to
7943 rebuild the entire core. as we are required to do if we change regcomp.h
7944 which is where PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS is defined.
7946 #if PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS
7947 #define BROKEN_UNICODE_CHARCLASS_MAPPINGS
7950 #ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
7951 #define POSIX_CC_UNI_NAME(CCNAME) CCNAME
7953 #define POSIX_CC_UNI_NAME(CCNAME) "Posix" CCNAME
7957 parse a class specification and produce either an ANYOF node that
7958 matches the pattern or if the pattern matches a single char only and
7959 that char is < 256 and we are case insensitive then we produce an
7964 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
7967 register UV nextvalue;
7968 register IV prevvalue = OOB_UNICODE;
7969 register IV range = 0;
7970 UV value = 0; /* XXX:dmq: needs to be referenceable (unfortunately) */
7971 register regnode *ret;
7974 char *rangebegin = NULL;
7975 bool need_class = 0;
7978 bool optimize_invert = TRUE;
7979 AV* unicode_alternate = NULL;
7981 UV literal_endpoint = 0;
7983 UV stored = 0; /* number of chars stored in the class */
7985 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
7986 case we need to change the emitted regop to an EXACT. */
7987 const char * orig_parse = RExC_parse;
7988 GET_RE_DEBUG_FLAGS_DECL;
7990 PERL_ARGS_ASSERT_REGCLASS;
7992 PERL_UNUSED_ARG(depth);
7995 DEBUG_PARSE("clas");
7997 /* Assume we are going to generate an ANYOF node. */
7998 ret = reganode(pRExC_state, ANYOF, 0);
8001 ANYOF_FLAGS(ret) = 0;
8003 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
8007 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
8011 RExC_size += ANYOF_SKIP;
8012 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
8015 RExC_emit += ANYOF_SKIP;
8017 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
8019 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
8020 ANYOF_BITMAP_ZERO(ret);
8021 listsv = newSVpvs("# comment\n");
8024 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
8026 if (!SIZE_ONLY && POSIXCC(nextvalue))
8027 checkposixcc(pRExC_state);
8029 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
8030 if (UCHARAT(RExC_parse) == ']')
8034 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
8038 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
8041 rangebegin = RExC_parse;
8043 value = utf8n_to_uvchr((U8*)RExC_parse,
8044 RExC_end - RExC_parse,
8045 &numlen, UTF8_ALLOW_DEFAULT);
8046 RExC_parse += numlen;
8049 value = UCHARAT(RExC_parse++);
8051 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
8052 if (value == '[' && POSIXCC(nextvalue))
8053 namedclass = regpposixcc(pRExC_state, value);
8054 else if (value == '\\') {
8056 value = utf8n_to_uvchr((U8*)RExC_parse,
8057 RExC_end - RExC_parse,
8058 &numlen, UTF8_ALLOW_DEFAULT);
8059 RExC_parse += numlen;
8062 value = UCHARAT(RExC_parse++);
8063 /* Some compilers cannot handle switching on 64-bit integer
8064 * values, therefore value cannot be an UV. Yes, this will
8065 * be a problem later if we want switch on Unicode.
8066 * A similar issue a little bit later when switching on
8067 * namedclass. --jhi */
8068 switch ((I32)value) {
8069 case 'w': namedclass = ANYOF_ALNUM; break;
8070 case 'W': namedclass = ANYOF_NALNUM; break;
8071 case 's': namedclass = ANYOF_SPACE; break;
8072 case 'S': namedclass = ANYOF_NSPACE; break;
8073 case 'd': namedclass = ANYOF_DIGIT; break;
8074 case 'D': namedclass = ANYOF_NDIGIT; break;
8075 case 'v': namedclass = ANYOF_VERTWS; break;
8076 case 'V': namedclass = ANYOF_NVERTWS; break;
8077 case 'h': namedclass = ANYOF_HORIZWS; break;
8078 case 'H': namedclass = ANYOF_NHORIZWS; break;
8079 case 'N': /* Handle \N{NAME} in class */
8081 /* We only pay attention to the first char of
8082 multichar strings being returned. I kinda wonder
8083 if this makes sense as it does change the behaviour
8084 from earlier versions, OTOH that behaviour was broken
8086 UV v; /* value is register so we cant & it /grrr */
8087 if (reg_namedseq(pRExC_state, &v, NULL)) {
8097 if (RExC_parse >= RExC_end)
8098 vFAIL2("Empty \\%c{}", (U8)value);
8099 if (*RExC_parse == '{') {
8100 const U8 c = (U8)value;
8101 e = strchr(RExC_parse++, '}');
8103 vFAIL2("Missing right brace on \\%c{}", c);
8104 while (isSPACE(UCHARAT(RExC_parse)))
8106 if (e == RExC_parse)
8107 vFAIL2("Empty \\%c{}", c);
8109 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
8117 if (UCHARAT(RExC_parse) == '^') {
8120 value = value == 'p' ? 'P' : 'p'; /* toggle */
8121 while (isSPACE(UCHARAT(RExC_parse))) {
8126 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
8127 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
8130 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8131 namedclass = ANYOF_MAX; /* no official name, but it's named */
8134 case 'n': value = '\n'; break;
8135 case 'r': value = '\r'; break;
8136 case 't': value = '\t'; break;
8137 case 'f': value = '\f'; break;
8138 case 'b': value = '\b'; break;
8139 case 'e': value = ASCII_TO_NATIVE('\033');break;
8140 case 'a': value = ASCII_TO_NATIVE('\007');break;
8142 RExC_parse--; /* function expects to be pointed at the 'o' */
8144 const char* error_msg;
8145 bool valid = grok_bslash_o(RExC_parse,
8150 RExC_parse += numlen;
8155 if (PL_encoding && value < 0x100) {
8156 goto recode_encoding;
8160 if (*RExC_parse == '{') {
8161 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
8162 | PERL_SCAN_DISALLOW_PREFIX;
8163 char * const e = strchr(RExC_parse++, '}');
8165 vFAIL("Missing right brace on \\x{}");
8167 numlen = e - RExC_parse;
8168 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
8172 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
8174 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
8175 RExC_parse += numlen;
8177 if (PL_encoding && value < 0x100)
8178 goto recode_encoding;
8181 value = grok_bslash_c(*RExC_parse++, SIZE_ONLY);
8183 case '0': case '1': case '2': case '3': case '4':
8184 case '5': case '6': case '7':
8186 /* Take 1-3 octal digits */
8187 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
8189 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
8190 RExC_parse += numlen;
8191 if (PL_encoding && value < 0x100)
8192 goto recode_encoding;
8197 SV* enc = PL_encoding;
8198 value = reg_recode((const char)(U8)value, &enc);
8199 if (!enc && SIZE_ONLY)
8200 ckWARNreg(RExC_parse,
8201 "Invalid escape in the specified encoding");
8205 /* Allow \_ to not give an error */
8206 if (!SIZE_ONLY && isALNUM(value) && value != '_') {
8207 ckWARN2reg(RExC_parse,
8208 "Unrecognized escape \\%c in character class passed through",
8213 } /* end of \blah */
8219 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
8221 if (!SIZE_ONLY && !need_class)
8222 ANYOF_CLASS_ZERO(ret);
8226 /* a bad range like a-\d, a-[:digit:] ? */
8230 RExC_parse >= rangebegin ?
8231 RExC_parse - rangebegin : 0;
8232 ckWARN4reg(RExC_parse,
8233 "False [] range \"%*.*s\"",
8236 if (prevvalue < 256) {
8237 ANYOF_BITMAP_SET(ret, prevvalue);
8238 ANYOF_BITMAP_SET(ret, '-');
8241 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8242 Perl_sv_catpvf(aTHX_ listsv,
8243 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
8247 range = 0; /* this was not a true range */
8253 const char *what = NULL;
8256 if (namedclass > OOB_NAMEDCLASS)
8257 optimize_invert = FALSE;
8258 /* Possible truncation here but in some 64-bit environments
8259 * the compiler gets heartburn about switch on 64-bit values.
8260 * A similar issue a little earlier when switching on value.
8262 switch ((I32)namedclass) {
8264 case _C_C_T_(ALNUMC, isALNUMC(value), POSIX_CC_UNI_NAME("Alnum"));
8265 case _C_C_T_(ALPHA, isALPHA(value), POSIX_CC_UNI_NAME("Alpha"));
8266 case _C_C_T_(BLANK, isBLANK(value), POSIX_CC_UNI_NAME("Blank"));
8267 case _C_C_T_(CNTRL, isCNTRL(value), POSIX_CC_UNI_NAME("Cntrl"));
8268 case _C_C_T_(GRAPH, isGRAPH(value), POSIX_CC_UNI_NAME("Graph"));
8269 case _C_C_T_(LOWER, isLOWER(value), POSIX_CC_UNI_NAME("Lower"));
8270 case _C_C_T_(PRINT, isPRINT(value), POSIX_CC_UNI_NAME("Print"));
8271 case _C_C_T_(PSXSPC, isPSXSPC(value), POSIX_CC_UNI_NAME("Space"));
8272 case _C_C_T_(PUNCT, isPUNCT(value), POSIX_CC_UNI_NAME("Punct"));
8273 case _C_C_T_(UPPER, isUPPER(value), POSIX_CC_UNI_NAME("Upper"));
8274 #ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
8275 case _C_C_T_(ALNUM, isALNUM(value), "Word");
8276 case _C_C_T_(SPACE, isSPACE(value), "SpacePerl");
8278 case _C_C_T_(SPACE, isSPACE(value), "PerlSpace");
8279 case _C_C_T_(ALNUM, isALNUM(value), "PerlWord");
8281 case _C_C_T_(XDIGIT, isXDIGIT(value), "XDigit");
8282 case _C_C_T_NOLOC_(VERTWS, is_VERTWS_latin1(&value), "VertSpace");
8283 case _C_C_T_NOLOC_(HORIZWS, is_HORIZWS_latin1(&value), "HorizSpace");
8286 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
8289 for (value = 0; value < 128; value++)
8290 ANYOF_BITMAP_SET(ret, value);
8292 for (value = 0; value < 256; value++) {
8294 ANYOF_BITMAP_SET(ret, value);
8303 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
8306 for (value = 128; value < 256; value++)
8307 ANYOF_BITMAP_SET(ret, value);
8309 for (value = 0; value < 256; value++) {
8310 if (!isASCII(value))
8311 ANYOF_BITMAP_SET(ret, value);
8320 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
8322 /* consecutive digits assumed */
8323 for (value = '0'; value <= '9'; value++)
8324 ANYOF_BITMAP_SET(ret, value);
8327 what = POSIX_CC_UNI_NAME("Digit");
8331 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
8333 /* consecutive digits assumed */
8334 for (value = 0; value < '0'; value++)
8335 ANYOF_BITMAP_SET(ret, value);
8336 for (value = '9' + 1; value < 256; value++)
8337 ANYOF_BITMAP_SET(ret, value);
8340 what = POSIX_CC_UNI_NAME("Digit");
8343 /* this is to handle \p and \P */
8346 vFAIL("Invalid [::] class");
8350 /* Strings such as "+utf8::isWord\n" */
8351 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
8354 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
8357 } /* end of namedclass \blah */
8360 if (prevvalue > (IV)value) /* b-a */ {
8361 const int w = RExC_parse - rangebegin;
8362 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
8363 range = 0; /* not a valid range */
8367 prevvalue = value; /* save the beginning of the range */
8368 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
8369 RExC_parse[1] != ']') {
8372 /* a bad range like \w-, [:word:]- ? */
8373 if (namedclass > OOB_NAMEDCLASS) {
8374 if (ckWARN(WARN_REGEXP)) {
8376 RExC_parse >= rangebegin ?
8377 RExC_parse - rangebegin : 0;
8379 "False [] range \"%*.*s\"",
8383 ANYOF_BITMAP_SET(ret, '-');
8385 range = 1; /* yeah, it's a range! */
8386 continue; /* but do it the next time */
8390 /* now is the next time */
8391 /*stored += (value - prevvalue + 1);*/
8393 if (prevvalue < 256) {
8394 const IV ceilvalue = value < 256 ? value : 255;
8397 /* In EBCDIC [\x89-\x91] should include
8398 * the \x8e but [i-j] should not. */
8399 if (literal_endpoint == 2 &&
8400 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
8401 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
8403 if (isLOWER(prevvalue)) {
8404 for (i = prevvalue; i <= ceilvalue; i++)
8405 if (isLOWER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
8407 ANYOF_BITMAP_SET(ret, i);
8410 for (i = prevvalue; i <= ceilvalue; i++)
8411 if (isUPPER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
8413 ANYOF_BITMAP_SET(ret, i);
8419 for (i = prevvalue; i <= ceilvalue; i++) {
8420 if (!ANYOF_BITMAP_TEST(ret,i)) {
8422 ANYOF_BITMAP_SET(ret, i);
8426 if (value > 255 || UTF) {
8427 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
8428 const UV natvalue = NATIVE_TO_UNI(value);
8429 stored+=2; /* can't optimize this class */
8430 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8431 if (prevnatvalue < natvalue) { /* what about > ? */
8432 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
8433 prevnatvalue, natvalue);
8435 else if (prevnatvalue == natvalue) {
8436 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
8438 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
8440 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
8442 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
8443 if (RExC_precomp[0] == ':' &&
8444 RExC_precomp[1] == '[' &&
8445 (f == 0xDF || f == 0x92)) {
8446 f = NATIVE_TO_UNI(f);
8449 /* If folding and foldable and a single
8450 * character, insert also the folded version
8451 * to the charclass. */
8453 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
8454 if ((RExC_precomp[0] == ':' &&
8455 RExC_precomp[1] == '[' &&
8457 (value == 0xFB05 || value == 0xFB06))) ?
8458 foldlen == ((STRLEN)UNISKIP(f) - 1) :
8459 foldlen == (STRLEN)UNISKIP(f) )
8461 if (foldlen == (STRLEN)UNISKIP(f))
8463 Perl_sv_catpvf(aTHX_ listsv,
8466 /* Any multicharacter foldings
8467 * require the following transform:
8468 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
8469 * where E folds into "pq" and F folds
8470 * into "rst", all other characters
8471 * fold to single characters. We save
8472 * away these multicharacter foldings,
8473 * to be later saved as part of the
8474 * additional "s" data. */
8477 if (!unicode_alternate)
8478 unicode_alternate = newAV();
8479 sv = newSVpvn_utf8((char*)foldbuf, foldlen,
8481 av_push(unicode_alternate, sv);
8485 /* If folding and the value is one of the Greek
8486 * sigmas insert a few more sigmas to make the
8487 * folding rules of the sigmas to work right.
8488 * Note that not all the possible combinations
8489 * are handled here: some of them are handled
8490 * by the standard folding rules, and some of
8491 * them (literal or EXACTF cases) are handled
8492 * during runtime in regexec.c:S_find_byclass(). */
8493 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
8494 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8495 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
8496 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8497 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
8499 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
8500 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8501 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
8506 literal_endpoint = 0;
8510 range = 0; /* this range (if it was one) is done now */
8514 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
8516 RExC_size += ANYOF_CLASS_ADD_SKIP;
8518 RExC_emit += ANYOF_CLASS_ADD_SKIP;
8524 /****** !SIZE_ONLY AFTER HERE *********/
8526 if( stored == 1 && (value < 128 || (value < 256 && !UTF))
8527 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
8529 /* optimize single char class to an EXACT node
8530 but *only* when its not a UTF/high char */
8531 const char * cur_parse= RExC_parse;
8532 RExC_emit = (regnode *)orig_emit;
8533 RExC_parse = (char *)orig_parse;
8534 ret = reg_node(pRExC_state,
8535 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
8536 RExC_parse = (char *)cur_parse;
8537 *STRING(ret)= (char)value;
8539 RExC_emit += STR_SZ(1);
8540 SvREFCNT_dec(listsv);
8543 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
8544 if ( /* If the only flag is folding (plus possibly inversion). */
8545 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
8547 for (value = 0; value < 256; ++value) {
8548 if (ANYOF_BITMAP_TEST(ret, value)) {
8549 UV fold = PL_fold[value];
8552 ANYOF_BITMAP_SET(ret, fold);
8555 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
8558 /* optimize inverted simple patterns (e.g. [^a-z]) */
8559 if (optimize_invert &&
8560 /* If the only flag is inversion. */
8561 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
8562 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
8563 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
8564 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
8567 AV * const av = newAV();
8569 /* The 0th element stores the character class description
8570 * in its textual form: used later (regexec.c:Perl_regclass_swash())
8571 * to initialize the appropriate swash (which gets stored in
8572 * the 1st element), and also useful for dumping the regnode.
8573 * The 2nd element stores the multicharacter foldings,
8574 * used later (regexec.c:S_reginclass()). */
8575 av_store(av, 0, listsv);
8576 av_store(av, 1, NULL);
8577 av_store(av, 2, MUTABLE_SV(unicode_alternate));
8578 rv = newRV_noinc(MUTABLE_SV(av));
8579 n = add_data(pRExC_state, 1, "s");
8580 RExC_rxi->data->data[n] = (void*)rv;
8588 /* reg_skipcomment()
8590 Absorbs an /x style # comments from the input stream.
8591 Returns true if there is more text remaining in the stream.
8592 Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
8593 terminates the pattern without including a newline.
8595 Note its the callers responsibility to ensure that we are
8601 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
8605 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
8607 while (RExC_parse < RExC_end)
8608 if (*RExC_parse++ == '\n') {
8613 /* we ran off the end of the pattern without ending
8614 the comment, so we have to add an \n when wrapping */
8615 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
8623 Advance that parse position, and optionall absorbs
8624 "whitespace" from the inputstream.
8626 Without /x "whitespace" means (?#...) style comments only,
8627 with /x this means (?#...) and # comments and whitespace proper.
8629 Returns the RExC_parse point from BEFORE the scan occurs.
8631 This is the /x friendly way of saying RExC_parse++.
8635 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
8637 char* const retval = RExC_parse++;
8639 PERL_ARGS_ASSERT_NEXTCHAR;
8642 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
8643 RExC_parse[2] == '#') {
8644 while (*RExC_parse != ')') {
8645 if (RExC_parse == RExC_end)
8646 FAIL("Sequence (?#... not terminated");
8652 if (RExC_flags & RXf_PMf_EXTENDED) {
8653 if (isSPACE(*RExC_parse)) {
8657 else if (*RExC_parse == '#') {
8658 if ( reg_skipcomment( pRExC_state ) )
8667 - reg_node - emit a node
8669 STATIC regnode * /* Location. */
8670 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
8673 register regnode *ptr;
8674 regnode * const ret = RExC_emit;
8675 GET_RE_DEBUG_FLAGS_DECL;
8677 PERL_ARGS_ASSERT_REG_NODE;
8680 SIZE_ALIGN(RExC_size);
8684 if (RExC_emit >= RExC_emit_bound)
8685 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
8687 NODE_ALIGN_FILL(ret);
8689 FILL_ADVANCE_NODE(ptr, op);
8690 REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, (ptr) - 1);
8691 #ifdef RE_TRACK_PATTERN_OFFSETS
8692 if (RExC_offsets) { /* MJD */
8693 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
8694 "reg_node", __LINE__,
8696 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
8697 ? "Overwriting end of array!\n" : "OK",
8698 (UV)(RExC_emit - RExC_emit_start),
8699 (UV)(RExC_parse - RExC_start),
8700 (UV)RExC_offsets[0]));
8701 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
8709 - reganode - emit a node with an argument
8711 STATIC regnode * /* Location. */
8712 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
8715 register regnode *ptr;
8716 regnode * const ret = RExC_emit;
8717 GET_RE_DEBUG_FLAGS_DECL;
8719 PERL_ARGS_ASSERT_REGANODE;
8722 SIZE_ALIGN(RExC_size);
8727 assert(2==regarglen[op]+1);
8729 Anything larger than this has to allocate the extra amount.
8730 If we changed this to be:
8732 RExC_size += (1 + regarglen[op]);
8734 then it wouldn't matter. Its not clear what side effect
8735 might come from that so its not done so far.
8740 if (RExC_emit >= RExC_emit_bound)
8741 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
8743 NODE_ALIGN_FILL(ret);
8745 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
8746 REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, (ptr) - 2);
8747 #ifdef RE_TRACK_PATTERN_OFFSETS
8748 if (RExC_offsets) { /* MJD */
8749 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
8753 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
8754 "Overwriting end of array!\n" : "OK",
8755 (UV)(RExC_emit - RExC_emit_start),
8756 (UV)(RExC_parse - RExC_start),
8757 (UV)RExC_offsets[0]));
8758 Set_Cur_Node_Offset;
8766 - reguni - emit (if appropriate) a Unicode character
8769 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
8773 PERL_ARGS_ASSERT_REGUNI;
8775 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
8779 - reginsert - insert an operator in front of already-emitted operand
8781 * Means relocating the operand.
8784 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
8787 register regnode *src;
8788 register regnode *dst;
8789 register regnode *place;
8790 const int offset = regarglen[(U8)op];
8791 const int size = NODE_STEP_REGNODE + offset;
8792 GET_RE_DEBUG_FLAGS_DECL;
8794 PERL_ARGS_ASSERT_REGINSERT;
8795 PERL_UNUSED_ARG(depth);
8796 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
8797 DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
8806 if (RExC_open_parens) {
8808 /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
8809 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
8810 if ( RExC_open_parens[paren] >= opnd ) {
8811 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
8812 RExC_open_parens[paren] += size;
8814 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
8816 if ( RExC_close_parens[paren] >= opnd ) {
8817 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
8818 RExC_close_parens[paren] += size;
8820 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
8825 while (src > opnd) {
8826 StructCopy(--src, --dst, regnode);
8827 #ifdef RE_TRACK_PATTERN_OFFSETS
8828 if (RExC_offsets) { /* MJD 20010112 */
8829 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
8833 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
8834 ? "Overwriting end of array!\n" : "OK",
8835 (UV)(src - RExC_emit_start),
8836 (UV)(dst - RExC_emit_start),
8837 (UV)RExC_offsets[0]));
8838 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
8839 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
8845 place = opnd; /* Op node, where operand used to be. */
8846 #ifdef RE_TRACK_PATTERN_OFFSETS
8847 if (RExC_offsets) { /* MJD */
8848 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
8852 (UV)(place - RExC_emit_start) > RExC_offsets[0]
8853 ? "Overwriting end of array!\n" : "OK",
8854 (UV)(place - RExC_emit_start),
8855 (UV)(RExC_parse - RExC_start),
8856 (UV)RExC_offsets[0]));
8857 Set_Node_Offset(place, RExC_parse);
8858 Set_Node_Length(place, 1);
8861 src = NEXTOPER(place);
8862 FILL_ADVANCE_NODE(place, op);
8863 REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, (place) - 1);
8864 Zero(src, offset, regnode);
8868 - regtail - set the next-pointer at the end of a node chain of p to val.
8869 - SEE ALSO: regtail_study
8871 /* TODO: All three parms should be const */
8873 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8876 register regnode *scan;
8877 GET_RE_DEBUG_FLAGS_DECL;
8879 PERL_ARGS_ASSERT_REGTAIL;
8881 PERL_UNUSED_ARG(depth);
8887 /* Find last node. */
8890 regnode * const temp = regnext(scan);
8892 SV * const mysv=sv_newmortal();
8893 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
8894 regprop(RExC_rx, mysv, scan);
8895 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
8896 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
8897 (temp == NULL ? "->" : ""),
8898 (temp == NULL ? PL_reg_name[OP(val)] : "")
8906 if (reg_off_by_arg[OP(scan)]) {
8907 ARG_SET(scan, val - scan);
8910 NEXT_OFF(scan) = val - scan;
8916 - regtail_study - set the next-pointer at the end of a node chain of p to val.
8917 - Look for optimizable sequences at the same time.
8918 - currently only looks for EXACT chains.
8920 This is expermental code. The idea is to use this routine to perform
8921 in place optimizations on branches and groups as they are constructed,
8922 with the long term intention of removing optimization from study_chunk so
8923 that it is purely analytical.
8925 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
8926 to control which is which.
8929 /* TODO: All four parms should be const */
8932 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8935 register regnode *scan;
8937 #ifdef EXPERIMENTAL_INPLACESCAN
8940 GET_RE_DEBUG_FLAGS_DECL;
8942 PERL_ARGS_ASSERT_REGTAIL_STUDY;
8948 /* Find last node. */
8952 regnode * const temp = regnext(scan);
8953 #ifdef EXPERIMENTAL_INPLACESCAN
8954 if (PL_regkind[OP(scan)] == EXACT)
8955 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
8963 if( exact == PSEUDO )
8965 else if ( exact != OP(scan) )
8974 SV * const mysv=sv_newmortal();
8975 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8976 regprop(RExC_rx, mysv, scan);
8977 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8978 SvPV_nolen_const(mysv),
8980 PL_reg_name[exact]);
8987 SV * const mysv_val=sv_newmortal();
8988 DEBUG_PARSE_MSG("");
8989 regprop(RExC_rx, mysv_val, val);
8990 PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
8991 SvPV_nolen_const(mysv_val),
8992 (IV)REG_NODE_NUM(val),
8996 if (reg_off_by_arg[OP(scan)]) {
8997 ARG_SET(scan, val - scan);
9000 NEXT_OFF(scan) = val - scan;
9008 - regcurly - a little FSA that accepts {\d+,?\d*}
9010 #ifndef PERL_IN_XSUB_RE
9012 Perl_regcurly(register const char *s)
9014 PERL_ARGS_ASSERT_REGCURLY;
9033 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
9037 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
9042 for (bit=0; bit<32; bit++) {
9043 if (flags & (1<<bit)) {
9045 PerlIO_printf(Perl_debug_log, "%s",lead);
9046 PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
9051 PerlIO_printf(Perl_debug_log, "\n");
9053 PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
9059 Perl_regdump(pTHX_ const regexp *r)
9063 SV * const sv = sv_newmortal();
9064 SV *dsv= sv_newmortal();
9066 GET_RE_DEBUG_FLAGS_DECL;
9068 PERL_ARGS_ASSERT_REGDUMP;
9070 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
9072 /* Header fields of interest. */
9073 if (r->anchored_substr) {
9074 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
9075 RE_SV_DUMPLEN(r->anchored_substr), 30);
9076 PerlIO_printf(Perl_debug_log,
9077 "anchored %s%s at %"IVdf" ",
9078 s, RE_SV_TAIL(r->anchored_substr),
9079 (IV)r->anchored_offset);
9080 } else if (r->anchored_utf8) {
9081 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
9082 RE_SV_DUMPLEN(r->anchored_utf8), 30);
9083 PerlIO_printf(Perl_debug_log,
9084 "anchored utf8 %s%s at %"IVdf" ",
9085 s, RE_SV_TAIL(r->anchored_utf8),
9086 (IV)r->anchored_offset);
9088 if (r->float_substr) {
9089 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
9090 RE_SV_DUMPLEN(r->float_substr), 30);
9091 PerlIO_printf(Perl_debug_log,
9092 "floating %s%s at %"IVdf"..%"UVuf" ",
9093 s, RE_SV_TAIL(r->float_substr),
9094 (IV)r->float_min_offset, (UV)r->float_max_offset);
9095 } else if (r->float_utf8) {
9096 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
9097 RE_SV_DUMPLEN(r->float_utf8), 30);
9098 PerlIO_printf(Perl_debug_log,
9099 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
9100 s, RE_SV_TAIL(r->float_utf8),
9101 (IV)r->float_min_offset, (UV)r->float_max_offset);
9103 if (r->check_substr || r->check_utf8)
9104 PerlIO_printf(Perl_debug_log,
9106 (r->check_substr == r->float_substr
9107 && r->check_utf8 == r->float_utf8
9108 ? "(checking floating" : "(checking anchored"));
9109 if (r->extflags & RXf_NOSCAN)
9110 PerlIO_printf(Perl_debug_log, " noscan");
9111 if (r->extflags & RXf_CHECK_ALL)
9112 PerlIO_printf(Perl_debug_log, " isall");
9113 if (r->check_substr || r->check_utf8)
9114 PerlIO_printf(Perl_debug_log, ") ");
9116 if (ri->regstclass) {
9117 regprop(r, sv, ri->regstclass);
9118 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
9120 if (r->extflags & RXf_ANCH) {
9121 PerlIO_printf(Perl_debug_log, "anchored");
9122 if (r->extflags & RXf_ANCH_BOL)
9123 PerlIO_printf(Perl_debug_log, "(BOL)");
9124 if (r->extflags & RXf_ANCH_MBOL)
9125 PerlIO_printf(Perl_debug_log, "(MBOL)");
9126 if (r->extflags & RXf_ANCH_SBOL)
9127 PerlIO_printf(Perl_debug_log, "(SBOL)");
9128 if (r->extflags & RXf_ANCH_GPOS)
9129 PerlIO_printf(Perl_debug_log, "(GPOS)");
9130 PerlIO_putc(Perl_debug_log, ' ');
9132 if (r->extflags & RXf_GPOS_SEEN)
9133 PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
9134 if (r->intflags & PREGf_SKIP)
9135 PerlIO_printf(Perl_debug_log, "plus ");
9136 if (r->intflags & PREGf_IMPLICIT)
9137 PerlIO_printf(Perl_debug_log, "implicit ");
9138 PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
9139 if (r->extflags & RXf_EVAL_SEEN)
9140 PerlIO_printf(Perl_debug_log, "with eval ");
9141 PerlIO_printf(Perl_debug_log, "\n");
9142 DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));
9144 PERL_ARGS_ASSERT_REGDUMP;
9145 PERL_UNUSED_CONTEXT;
9147 #endif /* DEBUGGING */
9151 - regprop - printable representation of opcode
9153 #define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
9156 Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
9157 if (flags & ANYOF_INVERT) \
9158 /*make sure the invert info is in each */ \
9159 sv_catpvs(sv, "^"); \
9165 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
9170 RXi_GET_DECL(prog,progi);
9171 GET_RE_DEBUG_FLAGS_DECL;
9173 PERL_ARGS_ASSERT_REGPROP;
9177 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
9178 /* It would be nice to FAIL() here, but this may be called from
9179 regexec.c, and it would be hard to supply pRExC_state. */
9180 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
9181 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
9183 k = PL_regkind[OP(o)];
9187 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
9188 * is a crude hack but it may be the best for now since
9189 * we have no flag "this EXACTish node was UTF-8"
9191 pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
9192 PERL_PV_ESCAPE_UNI_DETECT |
9193 PERL_PV_PRETTY_ELLIPSES |
9194 PERL_PV_PRETTY_LTGT |
9195 PERL_PV_PRETTY_NOCLEAR
9197 } else if (k == TRIE) {
9198 /* print the details of the trie in dumpuntil instead, as
9199 * progi->data isn't available here */
9200 const char op = OP(o);
9201 const U32 n = ARG(o);
9202 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
9203 (reg_ac_data *)progi->data->data[n] :
9205 const reg_trie_data * const trie
9206 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
9208 Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
9209 DEBUG_TRIE_COMPILE_r(
9210 Perl_sv_catpvf(aTHX_ sv,
9211 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
9212 (UV)trie->startstate,
9213 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
9214 (UV)trie->wordcount,
9217 (UV)TRIE_CHARCOUNT(trie),
9218 (UV)trie->uniquecharcount
9221 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
9223 int rangestart = -1;
9224 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
9226 for (i = 0; i <= 256; i++) {
9227 if (i < 256 && BITMAP_TEST(bitmap,i)) {
9228 if (rangestart == -1)
9230 } else if (rangestart != -1) {
9231 if (i <= rangestart + 3)
9232 for (; rangestart < i; rangestart++)
9233 put_byte(sv, rangestart);
9235 put_byte(sv, rangestart);
9237 put_byte(sv, i - 1);
9245 } else if (k == CURLY) {
9246 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
9247 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
9248 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
9250 else if (k == WHILEM && o->flags) /* Ordinal/of */
9251 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
9252 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
9253 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
9254 if ( RXp_PAREN_NAMES(prog) ) {
9255 if ( k != REF || OP(o) < NREF) {
9256 AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
9257 SV **name= av_fetch(list, ARG(o), 0 );
9259 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
9262 AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
9263 SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
9264 I32 *nums=(I32*)SvPVX(sv_dat);
9265 SV **name= av_fetch(list, nums[0], 0 );
9268 for ( n=0; n<SvIVX(sv_dat); n++ ) {
9269 Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
9270 (n ? "," : ""), (IV)nums[n]);
9272 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
9276 } else if (k == GOSUB)
9277 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
9278 else if (k == VERB) {
9280 Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
9281 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
9282 } else if (k == LOGICAL)
9283 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
9284 else if (k == FOLDCHAR)
9285 Perl_sv_catpvf(aTHX_ sv, "[0x%"UVXf"]", PTR2UV(ARG(o)) );
9286 else if (k == ANYOF) {
9287 int i, rangestart = -1;
9288 const U8 flags = ANYOF_FLAGS(o);
9291 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
9292 static const char * const anyofs[] = {
9325 if (flags & ANYOF_LOCALE)
9326 sv_catpvs(sv, "{loc}");
9327 if (flags & ANYOF_FOLD)
9328 sv_catpvs(sv, "{i}");
9329 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
9330 if (flags & ANYOF_INVERT)
9333 /* output what the standard cp 0-255 bitmap matches */
9334 for (i = 0; i <= 256; i++) {
9335 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
9336 if (rangestart == -1)
9338 } else if (rangestart != -1) {
9339 if (i <= rangestart + 3)
9340 for (; rangestart < i; rangestart++)
9341 put_byte(sv, rangestart);
9343 put_byte(sv, rangestart);
9345 put_byte(sv, i - 1);
9352 EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
9353 /* output any special charclass tests (used mostly under use locale) */
9354 if (o->flags & ANYOF_CLASS)
9355 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
9356 if (ANYOF_CLASS_TEST(o,i)) {
9357 sv_catpv(sv, anyofs[i]);
9361 EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
9363 /* output information about the unicode matching */
9364 if (flags & ANYOF_UNICODE)
9365 sv_catpvs(sv, "{unicode}");
9366 else if (flags & ANYOF_UNICODE_ALL)
9367 sv_catpvs(sv, "{unicode_all}");
9371 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
9375 U8 s[UTF8_MAXBYTES_CASE+1];
9377 for (i = 0; i <= 256; i++) { /* just the first 256 */
9378 uvchr_to_utf8(s, i);
9380 if (i < 256 && swash_fetch(sw, s, TRUE)) {
9381 if (rangestart == -1)
9383 } else if (rangestart != -1) {
9384 if (i <= rangestart + 3)
9385 for (; rangestart < i; rangestart++) {
9386 const U8 * const e = uvchr_to_utf8(s,rangestart);
9388 for(p = s; p < e; p++)
9392 const U8 *e = uvchr_to_utf8(s,rangestart);
9394 for (p = s; p < e; p++)
9397 e = uvchr_to_utf8(s, i-1);
9398 for (p = s; p < e; p++)
9405 sv_catpvs(sv, "..."); /* et cetera */
9409 char *s = savesvpv(lv);
9410 char * const origs = s;
9412 while (*s && *s != '\n')
9416 const char * const t = ++s;
9434 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
9436 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
9437 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
9439 PERL_UNUSED_CONTEXT;
9440 PERL_UNUSED_ARG(sv);
9442 PERL_UNUSED_ARG(prog);
9443 #endif /* DEBUGGING */
9447 Perl_re_intuit_string(pTHX_ REGEXP * const r)
9448 { /* Assume that RE_INTUIT is set */
9450 struct regexp *const prog = (struct regexp *)SvANY(r);
9451 GET_RE_DEBUG_FLAGS_DECL;
9453 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
9454 PERL_UNUSED_CONTEXT;
9458 const char * const s = SvPV_nolen_const(prog->check_substr
9459 ? prog->check_substr : prog->check_utf8);
9461 if (!PL_colorset) reginitcolors();
9462 PerlIO_printf(Perl_debug_log,
9463 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
9465 prog->check_substr ? "" : "utf8 ",
9466 PL_colors[5],PL_colors[0],
9469 (strlen(s) > 60 ? "..." : ""));
9472 return prog->check_substr ? prog->check_substr : prog->check_utf8;
9478 handles refcounting and freeing the perl core regexp structure. When
9479 it is necessary to actually free the structure the first thing it
9480 does is call the 'free' method of the regexp_engine associated to to
9481 the regexp, allowing the handling of the void *pprivate; member
9482 first. (This routine is not overridable by extensions, which is why
9483 the extensions free is called first.)
9485 See regdupe and regdupe_internal if you change anything here.
9487 #ifndef PERL_IN_XSUB_RE
9489 Perl_pregfree(pTHX_ REGEXP *r)
9495 Perl_pregfree2(pTHX_ REGEXP *rx)
9498 struct regexp *const r = (struct regexp *)SvANY(rx);
9499 GET_RE_DEBUG_FLAGS_DECL;
9501 PERL_ARGS_ASSERT_PREGFREE2;
9504 ReREFCNT_dec(r->mother_re);
9506 CALLREGFREE_PVT(rx); /* free the private data */
9507 SvREFCNT_dec(RXp_PAREN_NAMES(r));
9510 SvREFCNT_dec(r->anchored_substr);
9511 SvREFCNT_dec(r->anchored_utf8);
9512 SvREFCNT_dec(r->float_substr);
9513 SvREFCNT_dec(r->float_utf8);
9514 Safefree(r->substrs);
9516 RX_MATCH_COPY_FREE(rx);
9517 #ifdef PERL_OLD_COPY_ON_WRITE
9518 SvREFCNT_dec(r->saved_copy);
9525 This is a hacky workaround to the structural issue of match results
9526 being stored in the regexp structure which is in turn stored in
9527 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
9528 could be PL_curpm in multiple contexts, and could require multiple
9529 result sets being associated with the pattern simultaneously, such
9530 as when doing a recursive match with (??{$qr})
9532 The solution is to make a lightweight copy of the regexp structure
9533 when a qr// is returned from the code executed by (??{$qr}) this
9534 lightweight copy doesnt actually own any of its data except for
9535 the starp/end and the actual regexp structure itself.
9541 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
9544 struct regexp *const r = (struct regexp *)SvANY(rx);
9545 register const I32 npar = r->nparens+1;
9547 PERL_ARGS_ASSERT_REG_TEMP_COPY;
9550 ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
9551 ret = (struct regexp *)SvANY(ret_x);
9553 (void)ReREFCNT_inc(rx);
9554 /* We can take advantage of the existing "copied buffer" mechanism in SVs
9555 by pointing directly at the buffer, but flagging that the allocated
9556 space in the copy is zero. As we've just done a struct copy, it's now
9557 a case of zero-ing that, rather than copying the current length. */
9558 SvPV_set(ret_x, RX_WRAPPED(rx));
9559 SvFLAGS(ret_x) |= SvFLAGS(rx) & (SVf_POK|SVp_POK|SVf_UTF8);
9560 memcpy(&(ret->xpv_cur), &(r->xpv_cur),
9561 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
9562 SvLEN_set(ret_x, 0);
9563 SvSTASH_set(ret_x, NULL);
9564 SvMAGIC_set(ret_x, NULL);
9565 Newx(ret->offs, npar, regexp_paren_pair);
9566 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
9568 Newx(ret->substrs, 1, struct reg_substr_data);
9569 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
9571 SvREFCNT_inc_void(ret->anchored_substr);
9572 SvREFCNT_inc_void(ret->anchored_utf8);
9573 SvREFCNT_inc_void(ret->float_substr);
9574 SvREFCNT_inc_void(ret->float_utf8);
9576 /* check_substr and check_utf8, if non-NULL, point to either their
9577 anchored or float namesakes, and don't hold a second reference. */
9579 RX_MATCH_COPIED_off(ret_x);
9580 #ifdef PERL_OLD_COPY_ON_WRITE
9581 ret->saved_copy = NULL;
9583 ret->mother_re = rx;
9589 /* regfree_internal()
9591 Free the private data in a regexp. This is overloadable by
9592 extensions. Perl takes care of the regexp structure in pregfree(),
9593 this covers the *pprivate pointer which technically perldoesnt
9594 know about, however of course we have to handle the
9595 regexp_internal structure when no extension is in use.
9597 Note this is called before freeing anything in the regexp
9602 Perl_regfree_internal(pTHX_ REGEXP * const rx)
9605 struct regexp *const r = (struct regexp *)SvANY(rx);
9607 GET_RE_DEBUG_FLAGS_DECL;
9609 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
9615 SV *dsv= sv_newmortal();
9616 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
9617 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
9618 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
9619 PL_colors[4],PL_colors[5],s);
9622 #ifdef RE_TRACK_PATTERN_OFFSETS
9624 Safefree(ri->u.offsets); /* 20010421 MJD */
9627 int n = ri->data->count;
9628 PAD* new_comppad = NULL;
9633 /* If you add a ->what type here, update the comment in regcomp.h */
9634 switch (ri->data->what[n]) {
9639 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
9642 Safefree(ri->data->data[n]);
9645 new_comppad = MUTABLE_AV(ri->data->data[n]);
9648 if (new_comppad == NULL)
9649 Perl_croak(aTHX_ "panic: pregfree comppad");
9650 PAD_SAVE_LOCAL(old_comppad,
9651 /* Watch out for global destruction's random ordering. */
9652 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
9655 refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
9658 op_free((OP_4tree*)ri->data->data[n]);
9660 PAD_RESTORE_LOCAL(old_comppad);
9661 SvREFCNT_dec(MUTABLE_SV(new_comppad));
9667 { /* Aho Corasick add-on structure for a trie node.
9668 Used in stclass optimization only */
9670 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
9672 refcount = --aho->refcount;
9675 PerlMemShared_free(aho->states);
9676 PerlMemShared_free(aho->fail);
9677 /* do this last!!!! */
9678 PerlMemShared_free(ri->data->data[n]);
9679 PerlMemShared_free(ri->regstclass);
9685 /* trie structure. */
9687 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
9689 refcount = --trie->refcount;
9692 PerlMemShared_free(trie->charmap);
9693 PerlMemShared_free(trie->states);
9694 PerlMemShared_free(trie->trans);
9696 PerlMemShared_free(trie->bitmap);
9698 PerlMemShared_free(trie->jump);
9699 PerlMemShared_free(trie->wordinfo);
9700 /* do this last!!!! */
9701 PerlMemShared_free(ri->data->data[n]);
9706 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
9709 Safefree(ri->data->what);
9716 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
9717 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
9718 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
9721 re_dup - duplicate a regexp.
9723 This routine is expected to clone a given regexp structure. It is only
9724 compiled under USE_ITHREADS.
9726 After all of the core data stored in struct regexp is duplicated
9727 the regexp_engine.dupe method is used to copy any private data
9728 stored in the *pprivate pointer. This allows extensions to handle
9729 any duplication it needs to do.
9731 See pregfree() and regfree_internal() if you change anything here.
9733 #if defined(USE_ITHREADS)
9734 #ifndef PERL_IN_XSUB_RE
9736 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
9740 const struct regexp *r = (const struct regexp *)SvANY(sstr);
9741 struct regexp *ret = (struct regexp *)SvANY(dstr);
9743 PERL_ARGS_ASSERT_RE_DUP_GUTS;
9745 npar = r->nparens+1;
9746 Newx(ret->offs, npar, regexp_paren_pair);
9747 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
9749 /* no need to copy these */
9750 Newx(ret->swap, npar, regexp_paren_pair);
9754 /* Do it this way to avoid reading from *r after the StructCopy().
9755 That way, if any of the sv_dup_inc()s dislodge *r from the L1
9756 cache, it doesn't matter. */
9757 const bool anchored = r->check_substr
9758 ? r->check_substr == r->anchored_substr
9759 : r->check_utf8 == r->anchored_utf8;
9760 Newx(ret->substrs, 1, struct reg_substr_data);
9761 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
9763 ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
9764 ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
9765 ret->float_substr = sv_dup_inc(ret->float_substr, param);
9766 ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
9768 /* check_substr and check_utf8, if non-NULL, point to either their
9769 anchored or float namesakes, and don't hold a second reference. */
9771 if (ret->check_substr) {
9773 assert(r->check_utf8 == r->anchored_utf8);
9774 ret->check_substr = ret->anchored_substr;
9775 ret->check_utf8 = ret->anchored_utf8;
9777 assert(r->check_substr == r->float_substr);
9778 assert(r->check_utf8 == r->float_utf8);
9779 ret->check_substr = ret->float_substr;
9780 ret->check_utf8 = ret->float_utf8;
9782 } else if (ret->check_utf8) {
9784 ret->check_utf8 = ret->anchored_utf8;
9786 ret->check_utf8 = ret->float_utf8;
9791 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
9794 RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
9796 if (RX_MATCH_COPIED(dstr))
9797 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
9800 #ifdef PERL_OLD_COPY_ON_WRITE
9801 ret->saved_copy = NULL;
9804 if (ret->mother_re) {
9805 if (SvPVX_const(dstr) == SvPVX_const(ret->mother_re)) {
9806 /* Our storage points directly to our mother regexp, but that's
9807 1: a buffer in a different thread
9808 2: something we no longer hold a reference on
9809 so we need to copy it locally. */
9810 /* Note we need to sue SvCUR() on our mother_re, because it, in
9811 turn, may well be pointing to its own mother_re. */
9812 SvPV_set(dstr, SAVEPVN(SvPVX_const(ret->mother_re),
9813 SvCUR(ret->mother_re)+1));
9814 SvLEN_set(dstr, SvCUR(ret->mother_re)+1);
9816 ret->mother_re = NULL;
9820 #endif /* PERL_IN_XSUB_RE */
9825 This is the internal complement to regdupe() which is used to copy
9826 the structure pointed to by the *pprivate pointer in the regexp.
9827 This is the core version of the extension overridable cloning hook.
9828 The regexp structure being duplicated will be copied by perl prior
9829 to this and will be provided as the regexp *r argument, however
9830 with the /old/ structures pprivate pointer value. Thus this routine
9831 may override any copying normally done by perl.
9833 It returns a pointer to the new regexp_internal structure.
9837 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
9840 struct regexp *const r = (struct regexp *)SvANY(rx);
9841 regexp_internal *reti;
9845 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
9847 npar = r->nparens+1;
9850 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
9851 Copy(ri->program, reti->program, len+1, regnode);
9854 reti->regstclass = NULL;
9858 const int count = ri->data->count;
9861 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
9862 char, struct reg_data);
9863 Newx(d->what, count, U8);
9866 for (i = 0; i < count; i++) {
9867 d->what[i] = ri->data->what[i];
9868 switch (d->what[i]) {
9869 /* legal options are one of: sSfpontTua
9870 see also regcomp.h and pregfree() */
9871 case 'a': /* actually an AV, but the dup function is identical. */
9874 case 'p': /* actually an AV, but the dup function is identical. */
9875 case 'u': /* actually an HV, but the dup function is identical. */
9876 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
9879 /* This is cheating. */
9880 Newx(d->data[i], 1, struct regnode_charclass_class);
9881 StructCopy(ri->data->data[i], d->data[i],
9882 struct regnode_charclass_class);
9883 reti->regstclass = (regnode*)d->data[i];
9886 /* Compiled op trees are readonly and in shared memory,
9887 and can thus be shared without duplication. */
9889 d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
9893 /* Trie stclasses are readonly and can thus be shared
9894 * without duplication. We free the stclass in pregfree
9895 * when the corresponding reg_ac_data struct is freed.
9897 reti->regstclass= ri->regstclass;
9901 ((reg_trie_data*)ri->data->data[i])->refcount++;
9905 d->data[i] = ri->data->data[i];
9908 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
9917 reti->name_list_idx = ri->name_list_idx;
9919 #ifdef RE_TRACK_PATTERN_OFFSETS
9920 if (ri->u.offsets) {
9921 Newx(reti->u.offsets, 2*len+1, U32);
9922 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
9925 SetProgLen(reti,len);
9931 #endif /* USE_ITHREADS */
9933 #ifndef PERL_IN_XSUB_RE
9936 - regnext - dig the "next" pointer out of a node
9939 Perl_regnext(pTHX_ register regnode *p)
9942 register I32 offset;
9947 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
9948 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX);
9951 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
9960 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
9963 STRLEN l1 = strlen(pat1);
9964 STRLEN l2 = strlen(pat2);
9967 const char *message;
9969 PERL_ARGS_ASSERT_RE_CROAK2;
9975 Copy(pat1, buf, l1 , char);
9976 Copy(pat2, buf + l1, l2 , char);
9977 buf[l1 + l2] = '\n';
9978 buf[l1 + l2 + 1] = '\0';
9980 /* ANSI variant takes additional second argument */
9981 va_start(args, pat2);
9985 msv = vmess(buf, &args);
9987 message = SvPV_const(msv,l1);
9990 Copy(message, buf, l1 , char);
9991 buf[l1-1] = '\0'; /* Overwrite \n */
9992 Perl_croak(aTHX_ "%s", buf);
9995 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
9997 #ifndef PERL_IN_XSUB_RE
9999 Perl_save_re_context(pTHX)
10003 struct re_save_state *state;
10005 SAVEVPTR(PL_curcop);
10006 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
10008 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
10009 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
10010 SSPUSHUV(SAVEt_RE_STATE);
10012 Copy(&PL_reg_state, state, 1, struct re_save_state);
10014 PL_reg_start_tmp = 0;
10015 PL_reg_start_tmpl = 0;
10016 PL_reg_oldsaved = NULL;
10017 PL_reg_oldsavedlen = 0;
10018 PL_reg_maxiter = 0;
10019 PL_reg_leftiter = 0;
10020 PL_reg_poscache = NULL;
10021 PL_reg_poscache_size = 0;
10022 #ifdef PERL_OLD_COPY_ON_WRITE
10026 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
10028 const REGEXP * const rx = PM_GETRE(PL_curpm);
10031 for (i = 1; i <= RX_NPARENS(rx); i++) {
10032 char digits[TYPE_CHARS(long)];
10033 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
10034 GV *const *const gvp
10035 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
10038 GV * const gv = *gvp;
10039 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
10049 clear_re(pTHX_ void *r)
10052 ReREFCNT_dec((REGEXP *)r);
10058 S_put_byte(pTHX_ SV *sv, int c)
10060 PERL_ARGS_ASSERT_PUT_BYTE;
10062 /* Our definition of isPRINT() ignores locales, so only bytes that are
10063 not part of UTF-8 are considered printable. I assume that the same
10064 holds for UTF-EBCDIC.
10065 Also, code point 255 is not printable in either (it's E0 in EBCDIC,
10066 which Wikipedia says:
10068 EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
10069 ones (binary 1111 1111, hexadecimal FF). It is similar, but not
10070 identical, to the ASCII delete (DEL) or rubout control character.
10071 ) So the old condition can be simplified to !isPRINT(c) */
10073 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
10075 const char string = c;
10076 if (c == '-' || c == ']' || c == '\\' || c == '^')
10077 sv_catpvs(sv, "\\");
10078 sv_catpvn(sv, &string, 1);
10083 #define CLEAR_OPTSTART \
10084 if (optstart) STMT_START { \
10085 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
10089 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
10091 STATIC const regnode *
10092 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
10093 const regnode *last, const regnode *plast,
10094 SV* sv, I32 indent, U32 depth)
10097 register U8 op = PSEUDO; /* Arbitrary non-END op. */
10098 register const regnode *next;
10099 const regnode *optstart= NULL;
10101 RXi_GET_DECL(r,ri);
10102 GET_RE_DEBUG_FLAGS_DECL;
10104 PERL_ARGS_ASSERT_DUMPUNTIL;
10106 #ifdef DEBUG_DUMPUNTIL
10107 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
10108 last ? last-start : 0,plast ? plast-start : 0);
10111 if (plast && plast < last)
10114 while (PL_regkind[op] != END && (!last || node < last)) {
10115 /* While that wasn't END last time... */
10118 if (op == CLOSE || op == WHILEM)
10120 next = regnext((regnode *)node);
10123 if (OP(node) == OPTIMIZED) {
10124 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
10131 regprop(r, sv, node);
10132 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
10133 (int)(2*indent + 1), "", SvPVX_const(sv));
10135 if (OP(node) != OPTIMIZED) {
10136 if (next == NULL) /* Next ptr. */
10137 PerlIO_printf(Perl_debug_log, " (0)");
10138 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
10139 PerlIO_printf(Perl_debug_log, " (FAIL)");
10141 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
10142 (void)PerlIO_putc(Perl_debug_log, '\n');
10146 if (PL_regkind[(U8)op] == BRANCHJ) {
10149 register const regnode *nnode = (OP(next) == LONGJMP
10150 ? regnext((regnode *)next)
10152 if (last && nnode > last)
10154 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
10157 else if (PL_regkind[(U8)op] == BRANCH) {
10159 DUMPUNTIL(NEXTOPER(node), next);
10161 else if ( PL_regkind[(U8)op] == TRIE ) {
10162 const regnode *this_trie = node;
10163 const char op = OP(node);
10164 const U32 n = ARG(node);
10165 const reg_ac_data * const ac = op>=AHOCORASICK ?
10166 (reg_ac_data *)ri->data->data[n] :
10168 const reg_trie_data * const trie =
10169 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
10171 AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
10173 const regnode *nextbranch= NULL;
10176 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
10177 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
10179 PerlIO_printf(Perl_debug_log, "%*s%s ",
10180 (int)(2*(indent+3)), "",
10181 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
10182 PL_colors[0], PL_colors[1],
10183 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
10184 PERL_PV_PRETTY_ELLIPSES |
10185 PERL_PV_PRETTY_LTGT
10190 U16 dist= trie->jump[word_idx+1];
10191 PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
10192 (UV)((dist ? this_trie + dist : next) - start));
10195 nextbranch= this_trie + trie->jump[0];
10196 DUMPUNTIL(this_trie + dist, nextbranch);
10198 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
10199 nextbranch= regnext((regnode *)nextbranch);
10201 PerlIO_printf(Perl_debug_log, "\n");
10204 if (last && next > last)
10209 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
10210 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
10211 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
10213 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
10215 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
10217 else if ( op == PLUS || op == STAR) {
10218 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
10220 else if (op == ANYOF) {
10221 /* arglen 1 + class block */
10222 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
10223 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
10224 node = NEXTOPER(node);
10226 else if (PL_regkind[(U8)op] == EXACT) {
10227 /* Literal string, where present. */
10228 node += NODE_SZ_STR(node) - 1;
10229 node = NEXTOPER(node);
10232 node = NEXTOPER(node);
10233 node += regarglen[(U8)op];
10235 if (op == CURLYX || op == OPEN)
10239 #ifdef DEBUG_DUMPUNTIL
10240 PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
10245 #endif /* DEBUGGING */
10249 * c-indentation-style: bsd
10250 * c-basic-offset: 4
10251 * indent-tabs-mode: t
10254 * ex: set ts=8 sts=4 sw=4 noet: