5 * "A fair jaw-cracker dwarf-language must be." --Samwise Gamgee
8 /* This file contains functions for compiling a regular expression. See
9 * also regexec.c which funnily enough, contains functions for executing
10 * a regular expression.
12 * This file is also copied at build time to ext/re/re_comp.c, where
13 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
14 * This causes the main functions to be compiled under new names and with
15 * debugging support added, which makes "use re 'debug'" work.
18 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
19 * confused with the original package (see point 3 below). Thanks, Henry!
22 /* Additional note: this code is very heavily munged from Henry's version
23 * in places. In some spots I've traded clarity for efficiency, so don't
24 * blame Henry for some of the lack of readability.
27 /* The names of the functions have been changed from regcomp and
28 * regexec to pregcomp and pregexec in order to avoid conflicts
29 * with the POSIX routines of the same names.
32 #ifdef PERL_EXT_RE_BUILD
37 * pregcomp and pregexec -- regsub and regerror are not used in perl
39 * Copyright (c) 1986 by University of Toronto.
40 * Written by Henry Spencer. Not derived from licensed software.
42 * Permission is granted to anyone to use this software for any
43 * purpose on any computer system, and to redistribute it freely,
44 * subject to the following restrictions:
46 * 1. The author is not responsible for the consequences of use of
47 * this software, no matter how awful, even if they arise
50 * 2. The origin of this software must not be misrepresented, either
51 * by explicit claim or by omission.
53 * 3. Altered versions must be plainly marked as such, and must not
54 * be misrepresented as being the original software.
57 **** Alterations to Henry's code are...
59 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
60 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 by Larry Wall and others
62 **** You may distribute under the terms of either the GNU General Public
63 **** License or the Artistic License, as specified in the README file.
66 * Beware that some of this code is subtly aware of the way operator
67 * precedence is structured in regular expressions. Serious changes in
68 * regular-expression syntax might require a total rethink.
71 #define PERL_IN_REGCOMP_C
74 #ifndef PERL_IN_XSUB_RE
79 #ifdef PERL_IN_XSUB_RE
90 # if defined(BUGGY_MSC6)
91 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
92 # pragma optimize("a",off)
93 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
94 # pragma optimize("w",on )
95 # endif /* BUGGY_MSC6 */
102 typedef struct RExC_state_t {
103 U32 flags; /* are we folding, multilining? */
104 char *precomp; /* uncompiled string. */
105 regexp *rx; /* perl core regexp structure */
106 regexp_internal *rxi; /* internal data for regexp object pprivate field */
107 char *start; /* Start of input for compile */
108 char *end; /* End of input for compile */
109 char *parse; /* Input-scan pointer. */
110 I32 whilem_seen; /* number of WHILEM in this expr */
111 regnode *emit_start; /* Start of emitted-code area */
112 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
113 I32 naughty; /* How bad is this pattern? */
114 I32 sawback; /* Did we see \1, ...? */
116 I32 size; /* Code size. */
117 I32 npar; /* Capture buffer count, (OPEN). */
118 I32 cpar; /* Capture buffer count, (CLOSE). */
119 I32 nestroot; /* root parens we are in - used by accept */
123 regnode **open_parens; /* pointers to open parens */
124 regnode **close_parens; /* pointers to close parens */
125 regnode *opend; /* END node in program */
127 HV *charnames; /* cache of named sequences */
128 HV *paren_names; /* Paren names */
130 regnode **recurse; /* Recurse regops */
131 I32 recurse_count; /* Number of recurse regops */
133 char *starttry; /* -Dr: where regtry was called. */
134 #define RExC_starttry (pRExC_state->starttry)
137 const char *lastparse;
139 AV *paren_name_list; /* idx -> name */
140 #define RExC_lastparse (pRExC_state->lastparse)
141 #define RExC_lastnum (pRExC_state->lastnum)
142 #define RExC_paren_name_list (pRExC_state->paren_name_list)
146 #define RExC_flags (pRExC_state->flags)
147 #define RExC_precomp (pRExC_state->precomp)
148 #define RExC_rx (pRExC_state->rx)
149 #define RExC_rxi (pRExC_state->rxi)
150 #define RExC_start (pRExC_state->start)
151 #define RExC_end (pRExC_state->end)
152 #define RExC_parse (pRExC_state->parse)
153 #define RExC_whilem_seen (pRExC_state->whilem_seen)
154 #ifdef RE_TRACK_PATTERN_OFFSETS
155 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
157 #define RExC_emit (pRExC_state->emit)
158 #define RExC_emit_start (pRExC_state->emit_start)
159 #define RExC_naughty (pRExC_state->naughty)
160 #define RExC_sawback (pRExC_state->sawback)
161 #define RExC_seen (pRExC_state->seen)
162 #define RExC_size (pRExC_state->size)
163 #define RExC_npar (pRExC_state->npar)
164 #define RExC_nestroot (pRExC_state->nestroot)
165 #define RExC_extralen (pRExC_state->extralen)
166 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
167 #define RExC_seen_evals (pRExC_state->seen_evals)
168 #define RExC_utf8 (pRExC_state->utf8)
169 #define RExC_charnames (pRExC_state->charnames)
170 #define RExC_open_parens (pRExC_state->open_parens)
171 #define RExC_close_parens (pRExC_state->close_parens)
172 #define RExC_opend (pRExC_state->opend)
173 #define RExC_paren_names (pRExC_state->paren_names)
174 #define RExC_recurse (pRExC_state->recurse)
175 #define RExC_recurse_count (pRExC_state->recurse_count)
178 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
179 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
180 ((*s) == '{' && regcurly(s)))
183 #undef SPSTART /* dratted cpp namespace... */
186 * Flags to be passed up and down.
188 #define WORST 0 /* Worst case. */
189 #define HASWIDTH 0x01 /* Known to match non-null strings. */
190 #define SIMPLE 0x02 /* Simple enough to be STAR/PLUS operand. */
191 #define SPSTART 0x04 /* Starts with * or +. */
192 #define TRYAGAIN 0x08 /* Weeded out a declaration. */
193 #define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
195 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
197 /* whether trie related optimizations are enabled */
198 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
199 #define TRIE_STUDY_OPT
200 #define FULL_TRIE_STUDY
206 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
207 #define PBITVAL(paren) (1 << ((paren) & 7))
208 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
209 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
210 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
213 /* About scan_data_t.
215 During optimisation we recurse through the regexp program performing
216 various inplace (keyhole style) optimisations. In addition study_chunk
217 and scan_commit populate this data structure with information about
218 what strings MUST appear in the pattern. We look for the longest
219 string that must appear for at a fixed location, and we look for the
220 longest string that may appear at a floating location. So for instance
225 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
226 strings (because they follow a .* construct). study_chunk will identify
227 both FOO and BAR as being the longest fixed and floating strings respectively.
229 The strings can be composites, for instance
233 will result in a composite fixed substring 'foo'.
235 For each string some basic information is maintained:
237 - offset or min_offset
238 This is the position the string must appear at, or not before.
239 It also implicitly (when combined with minlenp) tells us how many
240 character must match before the string we are searching.
241 Likewise when combined with minlenp and the length of the string
242 tells us how many characters must appear after the string we have
246 Only used for floating strings. This is the rightmost point that
247 the string can appear at. Ifset to I32 max it indicates that the
248 string can occur infinitely far to the right.
251 A pointer to the minimum length of the pattern that the string
252 was found inside. This is important as in the case of positive
253 lookahead or positive lookbehind we can have multiple patterns
258 The minimum length of the pattern overall is 3, the minimum length
259 of the lookahead part is 3, but the minimum length of the part that
260 will actually match is 1. So 'FOO's minimum length is 3, but the
261 minimum length for the F is 1. This is important as the minimum length
262 is used to determine offsets in front of and behind the string being
263 looked for. Since strings can be composites this is the length of the
264 pattern at the time it was commited with a scan_commit. Note that
265 the length is calculated by study_chunk, so that the minimum lengths
266 are not known until the full pattern has been compiled, thus the
267 pointer to the value.
271 In the case of lookbehind the string being searched for can be
272 offset past the start point of the final matching string.
273 If this value was just blithely removed from the min_offset it would
274 invalidate some of the calculations for how many chars must match
275 before or after (as they are derived from min_offset and minlen and
276 the length of the string being searched for).
277 When the final pattern is compiled and the data is moved from the
278 scan_data_t structure into the regexp structure the information
279 about lookbehind is factored in, with the information that would
280 have been lost precalculated in the end_shift field for the
283 The fields pos_min and pos_delta are used to store the minimum offset
284 and the delta to the maximum offset at the current point in the pattern.
288 typedef struct scan_data_t {
289 /*I32 len_min; unused */
290 /*I32 len_delta; unused */
294 I32 last_end; /* min value, <0 unless valid. */
297 SV **longest; /* Either &l_fixed, or &l_float. */
298 SV *longest_fixed; /* longest fixed string found in pattern */
299 I32 offset_fixed; /* offset where it starts */
300 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
301 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
302 SV *longest_float; /* longest floating string found in pattern */
303 I32 offset_float_min; /* earliest point in string it can appear */
304 I32 offset_float_max; /* latest point in string it can appear */
305 I32 *minlen_float; /* pointer to the minlen relevent to the string */
306 I32 lookbehind_float; /* is the position of the string modified by LB */
310 struct regnode_charclass_class *start_class;
314 * Forward declarations for pregcomp()'s friends.
317 static const scan_data_t zero_scan_data =
318 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
320 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
321 #define SF_BEFORE_SEOL 0x0001
322 #define SF_BEFORE_MEOL 0x0002
323 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
324 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
327 # define SF_FIX_SHIFT_EOL (0+2)
328 # define SF_FL_SHIFT_EOL (0+4)
330 # define SF_FIX_SHIFT_EOL (+2)
331 # define SF_FL_SHIFT_EOL (+4)
334 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
335 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
337 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
338 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
339 #define SF_IS_INF 0x0040
340 #define SF_HAS_PAR 0x0080
341 #define SF_IN_PAR 0x0100
342 #define SF_HAS_EVAL 0x0200
343 #define SCF_DO_SUBSTR 0x0400
344 #define SCF_DO_STCLASS_AND 0x0800
345 #define SCF_DO_STCLASS_OR 0x1000
346 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
347 #define SCF_WHILEM_VISITED_POS 0x2000
349 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
350 #define SCF_SEEN_ACCEPT 0x8000
352 #define UTF (RExC_utf8 != 0)
353 #define LOC ((RExC_flags & RXf_PMf_LOCALE) != 0)
354 #define FOLD ((RExC_flags & RXf_PMf_FOLD) != 0)
356 #define OOB_UNICODE 12345678
357 #define OOB_NAMEDCLASS -1
359 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
360 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
363 /* length of regex to show in messages that don't mark a position within */
364 #define RegexLengthToShowInErrorMessages 127
367 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
368 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
369 * op/pragma/warn/regcomp.
371 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
372 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
374 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
377 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
378 * arg. Show regex, up to a maximum length. If it's too long, chop and add
381 #define _FAIL(code) STMT_START { \
382 const char *ellipses = ""; \
383 IV len = RExC_end - RExC_precomp; \
386 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
387 if (len > RegexLengthToShowInErrorMessages) { \
388 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
389 len = RegexLengthToShowInErrorMessages - 10; \
395 #define FAIL(msg) _FAIL( \
396 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
397 msg, (int)len, RExC_precomp, ellipses))
399 #define FAIL2(msg,arg) _FAIL( \
400 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
401 arg, (int)len, RExC_precomp, ellipses))
404 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
406 #define Simple_vFAIL(m) STMT_START { \
407 const IV offset = RExC_parse - RExC_precomp; \
408 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
409 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
413 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
415 #define vFAIL(m) STMT_START { \
417 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
422 * Like Simple_vFAIL(), but accepts two arguments.
424 #define Simple_vFAIL2(m,a1) STMT_START { \
425 const IV offset = RExC_parse - RExC_precomp; \
426 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
427 (int)offset, RExC_precomp, RExC_precomp + offset); \
431 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
433 #define vFAIL2(m,a1) STMT_START { \
435 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
436 Simple_vFAIL2(m, a1); \
441 * Like Simple_vFAIL(), but accepts three arguments.
443 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
444 const IV offset = RExC_parse - RExC_precomp; \
445 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
446 (int)offset, RExC_precomp, RExC_precomp + offset); \
450 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
452 #define vFAIL3(m,a1,a2) STMT_START { \
454 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
455 Simple_vFAIL3(m, a1, a2); \
459 * Like Simple_vFAIL(), but accepts four arguments.
461 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
462 const IV offset = RExC_parse - RExC_precomp; \
463 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
464 (int)offset, RExC_precomp, RExC_precomp + offset); \
467 #define vWARN(loc,m) STMT_START { \
468 const IV offset = loc - RExC_precomp; \
469 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
470 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
473 #define vWARNdep(loc,m) STMT_START { \
474 const IV offset = loc - RExC_precomp; \
475 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
476 "%s" REPORT_LOCATION, \
477 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
481 #define vWARN2(loc, m, a1) STMT_START { \
482 const IV offset = loc - RExC_precomp; \
483 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
484 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
487 #define vWARN3(loc, m, a1, a2) STMT_START { \
488 const IV offset = loc - RExC_precomp; \
489 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
490 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
493 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
494 const IV offset = loc - RExC_precomp; \
495 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
496 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
499 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
500 const IV offset = loc - RExC_precomp; \
501 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
502 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
506 /* Allow for side effects in s */
507 #define REGC(c,s) STMT_START { \
508 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
511 /* Macros for recording node offsets. 20001227 mjd@plover.com
512 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
513 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
514 * Element 0 holds the number n.
515 * Position is 1 indexed.
517 #ifndef RE_TRACK_PATTERN_OFFSETS
518 #define Set_Node_Offset_To_R(node,byte)
519 #define Set_Node_Offset(node,byte)
520 #define Set_Cur_Node_Offset
521 #define Set_Node_Length_To_R(node,len)
522 #define Set_Node_Length(node,len)
523 #define Set_Node_Cur_Length(node)
524 #define Node_Offset(n)
525 #define Node_Length(n)
526 #define Set_Node_Offset_Length(node,offset,len)
527 #define ProgLen(ri) ri->u.proglen
528 #define SetProgLen(ri,x) ri->u.proglen = x
530 #define ProgLen(ri) ri->u.offsets[0]
531 #define SetProgLen(ri,x) ri->u.offsets[0] = x
532 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
534 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
535 __LINE__, (int)(node), (int)(byte))); \
537 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
539 RExC_offsets[2*(node)-1] = (byte); \
544 #define Set_Node_Offset(node,byte) \
545 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
546 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
548 #define Set_Node_Length_To_R(node,len) STMT_START { \
550 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
551 __LINE__, (int)(node), (int)(len))); \
553 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
555 RExC_offsets[2*(node)] = (len); \
560 #define Set_Node_Length(node,len) \
561 Set_Node_Length_To_R((node)-RExC_emit_start, len)
562 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
563 #define Set_Node_Cur_Length(node) \
564 Set_Node_Length(node, RExC_parse - parse_start)
566 /* Get offsets and lengths */
567 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
568 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
570 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
571 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
572 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
576 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
577 #define EXPERIMENTAL_INPLACESCAN
578 #endif /*RE_TRACK_PATTERN_OFFSETS*/
580 #define DEBUG_STUDYDATA(str,data,depth) \
581 DEBUG_OPTIMISE_MORE_r(if(data){ \
582 PerlIO_printf(Perl_debug_log, \
583 "%*s" str "Pos:%"IVdf"/%"IVdf \
584 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
585 (int)(depth)*2, "", \
586 (IV)((data)->pos_min), \
587 (IV)((data)->pos_delta), \
588 (UV)((data)->flags), \
589 (IV)((data)->whilem_c), \
590 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
591 is_inf ? "INF " : "" \
593 if ((data)->last_found) \
594 PerlIO_printf(Perl_debug_log, \
595 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
596 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
597 SvPVX_const((data)->last_found), \
598 (IV)((data)->last_end), \
599 (IV)((data)->last_start_min), \
600 (IV)((data)->last_start_max), \
601 ((data)->longest && \
602 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
603 SvPVX_const((data)->longest_fixed), \
604 (IV)((data)->offset_fixed), \
605 ((data)->longest && \
606 (data)->longest==&((data)->longest_float)) ? "*" : "", \
607 SvPVX_const((data)->longest_float), \
608 (IV)((data)->offset_float_min), \
609 (IV)((data)->offset_float_max) \
611 PerlIO_printf(Perl_debug_log,"\n"); \
614 static void clear_re(pTHX_ void *r);
616 /* Mark that we cannot extend a found fixed substring at this point.
617 Update the longest found anchored substring and the longest found
618 floating substrings if needed. */
621 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
623 const STRLEN l = CHR_SVLEN(data->last_found);
624 const STRLEN old_l = CHR_SVLEN(*data->longest);
625 GET_RE_DEBUG_FLAGS_DECL;
627 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
628 SvSetMagicSV(*data->longest, data->last_found);
629 if (*data->longest == data->longest_fixed) {
630 data->offset_fixed = l ? data->last_start_min : data->pos_min;
631 if (data->flags & SF_BEFORE_EOL)
633 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
635 data->flags &= ~SF_FIX_BEFORE_EOL;
636 data->minlen_fixed=minlenp;
637 data->lookbehind_fixed=0;
639 else { /* *data->longest == data->longest_float */
640 data->offset_float_min = l ? data->last_start_min : data->pos_min;
641 data->offset_float_max = (l
642 ? data->last_start_max
643 : data->pos_min + data->pos_delta);
644 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
645 data->offset_float_max = I32_MAX;
646 if (data->flags & SF_BEFORE_EOL)
648 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
650 data->flags &= ~SF_FL_BEFORE_EOL;
651 data->minlen_float=minlenp;
652 data->lookbehind_float=0;
655 SvCUR_set(data->last_found, 0);
657 SV * const sv = data->last_found;
658 if (SvUTF8(sv) && SvMAGICAL(sv)) {
659 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
665 data->flags &= ~SF_BEFORE_EOL;
666 DEBUG_STUDYDATA("commit: ",data,0);
669 /* Can match anything (initialization) */
671 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
673 ANYOF_CLASS_ZERO(cl);
674 ANYOF_BITMAP_SETALL(cl);
675 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
677 cl->flags |= ANYOF_LOCALE;
680 /* Can match anything (initialization) */
682 S_cl_is_anything(const struct regnode_charclass_class *cl)
686 for (value = 0; value <= ANYOF_MAX; value += 2)
687 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
689 if (!(cl->flags & ANYOF_UNICODE_ALL))
691 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
696 /* Can match anything (initialization) */
698 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
700 Zero(cl, 1, struct regnode_charclass_class);
702 cl_anything(pRExC_state, cl);
706 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
708 Zero(cl, 1, struct regnode_charclass_class);
710 cl_anything(pRExC_state, cl);
712 cl->flags |= ANYOF_LOCALE;
715 /* 'And' a given class with another one. Can create false positives */
716 /* We assume that cl is not inverted */
718 S_cl_and(struct regnode_charclass_class *cl,
719 const struct regnode_charclass_class *and_with)
722 assert(and_with->type == ANYOF);
723 if (!(and_with->flags & ANYOF_CLASS)
724 && !(cl->flags & ANYOF_CLASS)
725 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
726 && !(and_with->flags & ANYOF_FOLD)
727 && !(cl->flags & ANYOF_FOLD)) {
730 if (and_with->flags & ANYOF_INVERT)
731 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
732 cl->bitmap[i] &= ~and_with->bitmap[i];
734 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
735 cl->bitmap[i] &= and_with->bitmap[i];
736 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
737 if (!(and_with->flags & ANYOF_EOS))
738 cl->flags &= ~ANYOF_EOS;
740 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
741 !(and_with->flags & ANYOF_INVERT)) {
742 cl->flags &= ~ANYOF_UNICODE_ALL;
743 cl->flags |= ANYOF_UNICODE;
744 ARG_SET(cl, ARG(and_with));
746 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
747 !(and_with->flags & ANYOF_INVERT))
748 cl->flags &= ~ANYOF_UNICODE_ALL;
749 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
750 !(and_with->flags & ANYOF_INVERT))
751 cl->flags &= ~ANYOF_UNICODE;
754 /* 'OR' a given class with another one. Can create false positives */
755 /* We assume that cl is not inverted */
757 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
759 if (or_with->flags & ANYOF_INVERT) {
761 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
762 * <= (B1 | !B2) | (CL1 | !CL2)
763 * which is wasteful if CL2 is small, but we ignore CL2:
764 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
765 * XXXX Can we handle case-fold? Unclear:
766 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
767 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
769 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
770 && !(or_with->flags & ANYOF_FOLD)
771 && !(cl->flags & ANYOF_FOLD) ) {
774 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
775 cl->bitmap[i] |= ~or_with->bitmap[i];
776 } /* XXXX: logic is complicated otherwise */
778 cl_anything(pRExC_state, cl);
781 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
782 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
783 && (!(or_with->flags & ANYOF_FOLD)
784 || (cl->flags & ANYOF_FOLD)) ) {
787 /* OR char bitmap and class bitmap separately */
788 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
789 cl->bitmap[i] |= or_with->bitmap[i];
790 if (or_with->flags & ANYOF_CLASS) {
791 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
792 cl->classflags[i] |= or_with->classflags[i];
793 cl->flags |= ANYOF_CLASS;
796 else { /* XXXX: logic is complicated, leave it along for a moment. */
797 cl_anything(pRExC_state, cl);
800 if (or_with->flags & ANYOF_EOS)
801 cl->flags |= ANYOF_EOS;
803 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
804 ARG(cl) != ARG(or_with)) {
805 cl->flags |= ANYOF_UNICODE_ALL;
806 cl->flags &= ~ANYOF_UNICODE;
808 if (or_with->flags & ANYOF_UNICODE_ALL) {
809 cl->flags |= ANYOF_UNICODE_ALL;
810 cl->flags &= ~ANYOF_UNICODE;
814 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
815 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
816 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
817 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
822 dump_trie(trie,widecharmap,revcharmap)
823 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
824 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
826 These routines dump out a trie in a somewhat readable format.
827 The _interim_ variants are used for debugging the interim
828 tables that are used to generate the final compressed
829 representation which is what dump_trie expects.
831 Part of the reason for their existance is to provide a form
832 of documentation as to how the different representations function.
837 Dumps the final compressed table form of the trie to Perl_debug_log.
838 Used for debugging make_trie().
842 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
843 AV *revcharmap, U32 depth)
846 SV *sv=sv_newmortal();
847 int colwidth= widecharmap ? 6 : 4;
848 GET_RE_DEBUG_FLAGS_DECL;
851 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
852 (int)depth * 2 + 2,"",
853 "Match","Base","Ofs" );
855 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
856 SV ** const tmp = av_fetch( revcharmap, state, 0);
858 PerlIO_printf( Perl_debug_log, "%*s",
860 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
861 PL_colors[0], PL_colors[1],
862 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
863 PERL_PV_ESCAPE_FIRSTCHAR
868 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
869 (int)depth * 2 + 2,"");
871 for( state = 0 ; state < trie->uniquecharcount ; state++ )
872 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
873 PerlIO_printf( Perl_debug_log, "\n");
875 for( state = 1 ; state < trie->statecount ; state++ ) {
876 const U32 base = trie->states[ state ].trans.base;
878 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
880 if ( trie->states[ state ].wordnum ) {
881 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
883 PerlIO_printf( Perl_debug_log, "%6s", "" );
886 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
891 while( ( base + ofs < trie->uniquecharcount ) ||
892 ( base + ofs - trie->uniquecharcount < trie->lasttrans
893 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
896 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
898 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
899 if ( ( base + ofs >= trie->uniquecharcount ) &&
900 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
901 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
903 PerlIO_printf( Perl_debug_log, "%*"UVXf,
905 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
907 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
911 PerlIO_printf( Perl_debug_log, "]");
914 PerlIO_printf( Perl_debug_log, "\n" );
918 Dumps a fully constructed but uncompressed trie in list form.
919 List tries normally only are used for construction when the number of
920 possible chars (trie->uniquecharcount) is very high.
921 Used for debugging make_trie().
924 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
925 HV *widecharmap, AV *revcharmap, U32 next_alloc,
929 SV *sv=sv_newmortal();
930 int colwidth= widecharmap ? 6 : 4;
931 GET_RE_DEBUG_FLAGS_DECL;
932 /* print out the table precompression. */
933 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
934 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
935 "------:-----+-----------------\n" );
937 for( state=1 ; state < next_alloc ; state ++ ) {
940 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
941 (int)depth * 2 + 2,"", (UV)state );
942 if ( ! trie->states[ state ].wordnum ) {
943 PerlIO_printf( Perl_debug_log, "%5s| ","");
945 PerlIO_printf( Perl_debug_log, "W%4x| ",
946 trie->states[ state ].wordnum
949 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
950 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
952 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
954 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
955 PL_colors[0], PL_colors[1],
956 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
957 PERL_PV_ESCAPE_FIRSTCHAR
959 TRIE_LIST_ITEM(state,charid).forid,
960 (UV)TRIE_LIST_ITEM(state,charid).newstate
963 PerlIO_printf(Perl_debug_log, "\n%*s| ",
964 (int)((depth * 2) + 14), "");
967 PerlIO_printf( Perl_debug_log, "\n");
972 Dumps a fully constructed but uncompressed trie in table form.
973 This is the normal DFA style state transition table, with a few
974 twists to facilitate compression later.
975 Used for debugging make_trie().
978 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
979 HV *widecharmap, AV *revcharmap, U32 next_alloc,
984 SV *sv=sv_newmortal();
985 int colwidth= widecharmap ? 6 : 4;
986 GET_RE_DEBUG_FLAGS_DECL;
989 print out the table precompression so that we can do a visual check
990 that they are identical.
993 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
995 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
996 SV ** const tmp = av_fetch( revcharmap, charid, 0);
998 PerlIO_printf( Perl_debug_log, "%*s",
1000 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1001 PL_colors[0], PL_colors[1],
1002 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1003 PERL_PV_ESCAPE_FIRSTCHAR
1009 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1011 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1012 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1015 PerlIO_printf( Perl_debug_log, "\n" );
1017 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1019 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1020 (int)depth * 2 + 2,"",
1021 (UV)TRIE_NODENUM( state ) );
1023 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1024 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1026 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1028 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1030 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1031 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1033 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1034 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1041 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1042 startbranch: the first branch in the whole branch sequence
1043 first : start branch of sequence of branch-exact nodes.
1044 May be the same as startbranch
1045 last : Thing following the last branch.
1046 May be the same as tail.
1047 tail : item following the branch sequence
1048 count : words in the sequence
1049 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1050 depth : indent depth
1052 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1054 A trie is an N'ary tree where the branches are determined by digital
1055 decomposition of the key. IE, at the root node you look up the 1st character and
1056 follow that branch repeat until you find the end of the branches. Nodes can be
1057 marked as "accepting" meaning they represent a complete word. Eg:
1061 would convert into the following structure. Numbers represent states, letters
1062 following numbers represent valid transitions on the letter from that state, if
1063 the number is in square brackets it represents an accepting state, otherwise it
1064 will be in parenthesis.
1066 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1070 (1) +-i->(6)-+-s->[7]
1072 +-s->(3)-+-h->(4)-+-e->[5]
1074 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1076 This shows that when matching against the string 'hers' we will begin at state 1
1077 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1078 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1079 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1080 single traverse. We store a mapping from accepting to state to which word was
1081 matched, and then when we have multiple possibilities we try to complete the
1082 rest of the regex in the order in which they occured in the alternation.
1084 The only prior NFA like behaviour that would be changed by the TRIE support is
1085 the silent ignoring of duplicate alternations which are of the form:
1087 / (DUPE|DUPE) X? (?{ ... }) Y /x
1089 Thus EVAL blocks follwing a trie may be called a different number of times with
1090 and without the optimisation. With the optimisations dupes will be silently
1091 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1092 the following demonstrates:
1094 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1096 which prints out 'word' three times, but
1098 'words'=~/(word|word|word)(?{ print $1 })S/
1100 which doesnt print it out at all. This is due to other optimisations kicking in.
1102 Example of what happens on a structural level:
1104 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1106 1: CURLYM[1] {1,32767}(18)
1117 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1118 and should turn into:
1120 1: CURLYM[1] {1,32767}(18)
1122 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1130 Cases where tail != last would be like /(?foo|bar)baz/:
1140 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1141 and would end up looking like:
1144 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1151 d = uvuni_to_utf8_flags(d, uv, 0);
1153 is the recommended Unicode-aware way of saying
1158 #define TRIE_STORE_REVCHAR \
1160 SV *tmp = newSVpvs(""); \
1161 if (UTF) SvUTF8_on(tmp); \
1162 Perl_sv_catpvf( aTHX_ tmp, "%c", (int)uvc ); \
1163 av_push( revcharmap, tmp ); \
1166 #define TRIE_READ_CHAR STMT_START { \
1170 if ( foldlen > 0 ) { \
1171 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1176 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1177 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1178 foldlen -= UNISKIP( uvc ); \
1179 scan = foldbuf + UNISKIP( uvc ); \
1182 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1192 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1193 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1194 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1195 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1197 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1198 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1199 TRIE_LIST_CUR( state )++; \
1202 #define TRIE_LIST_NEW(state) STMT_START { \
1203 Newxz( trie->states[ state ].trans.list, \
1204 4, reg_trie_trans_le ); \
1205 TRIE_LIST_CUR( state ) = 1; \
1206 TRIE_LIST_LEN( state ) = 4; \
1209 #define TRIE_HANDLE_WORD(state) STMT_START { \
1210 U16 dupe= trie->states[ state ].wordnum; \
1211 regnode * const noper_next = regnext( noper ); \
1213 if (trie->wordlen) \
1214 trie->wordlen[ curword ] = wordlen; \
1216 /* store the word for dumping */ \
1218 if (OP(noper) != NOTHING) \
1219 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1221 tmp = newSVpvn( "", 0 ); \
1222 if ( UTF ) SvUTF8_on( tmp ); \
1223 av_push( trie_words, tmp ); \
1228 if ( noper_next < tail ) { \
1230 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1231 trie->jump[curword] = (U16)(noper_next - convert); \
1233 jumper = noper_next; \
1235 nextbranch= regnext(cur); \
1239 /* So it's a dupe. This means we need to maintain a */\
1240 /* linked-list from the first to the next. */\
1241 /* we only allocate the nextword buffer when there */\
1242 /* a dupe, so first time we have to do the allocation */\
1243 if (!trie->nextword) \
1244 trie->nextword = (U16 *) \
1245 PerlMemShared_calloc( word_count + 1, sizeof(U16)); \
1246 while ( trie->nextword[dupe] ) \
1247 dupe= trie->nextword[dupe]; \
1248 trie->nextword[dupe]= curword; \
1250 /* we haven't inserted this word yet. */ \
1251 trie->states[ state ].wordnum = curword; \
1256 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1257 ( ( base + charid >= ucharcount \
1258 && base + charid < ubound \
1259 && state == trie->trans[ base - ucharcount + charid ].check \
1260 && trie->trans[ base - ucharcount + charid ].next ) \
1261 ? trie->trans[ base - ucharcount + charid ].next \
1262 : ( state==1 ? special : 0 ) \
1266 #define MADE_JUMP_TRIE 2
1267 #define MADE_EXACT_TRIE 4
1270 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1273 /* first pass, loop through and scan words */
1274 reg_trie_data *trie;
1275 HV *widecharmap = NULL;
1276 AV *revcharmap = newAV();
1278 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1283 regnode *jumper = NULL;
1284 regnode *nextbranch = NULL;
1285 regnode *convert = NULL;
1286 /* we just use folder as a flag in utf8 */
1287 const U8 * const folder = ( flags == EXACTF
1289 : ( flags == EXACTFL
1296 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1297 AV *trie_words = NULL;
1298 /* along with revcharmap, this only used during construction but both are
1299 * useful during debugging so we store them in the struct when debugging.
1302 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1303 STRLEN trie_charcount=0;
1305 SV *re_trie_maxbuff;
1306 GET_RE_DEBUG_FLAGS_DECL;
1308 PERL_UNUSED_ARG(depth);
1311 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1313 trie->startstate = 1;
1314 trie->wordcount = word_count;
1315 RExC_rxi->data->data[ data_slot ] = (void*)trie;
1316 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1317 if (!(UTF && folder))
1318 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1320 trie_words = newAV();
1323 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1324 if (!SvIOK(re_trie_maxbuff)) {
1325 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1328 PerlIO_printf( Perl_debug_log,
1329 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1330 (int)depth * 2 + 2, "",
1331 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1332 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1336 /* Find the node we are going to overwrite */
1337 if ( first == startbranch && OP( last ) != BRANCH ) {
1338 /* whole branch chain */
1341 /* branch sub-chain */
1342 convert = NEXTOPER( first );
1345 /* -- First loop and Setup --
1347 We first traverse the branches and scan each word to determine if it
1348 contains widechars, and how many unique chars there are, this is
1349 important as we have to build a table with at least as many columns as we
1352 We use an array of integers to represent the character codes 0..255
1353 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1354 native representation of the character value as the key and IV's for the
1357 *TODO* If we keep track of how many times each character is used we can
1358 remap the columns so that the table compression later on is more
1359 efficient in terms of memory by ensuring most common value is in the
1360 middle and the least common are on the outside. IMO this would be better
1361 than a most to least common mapping as theres a decent chance the most
1362 common letter will share a node with the least common, meaning the node
1363 will not be compressable. With a middle is most common approach the worst
1364 case is when we have the least common nodes twice.
1368 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1369 regnode * const noper = NEXTOPER( cur );
1370 const U8 *uc = (U8*)STRING( noper );
1371 const U8 * const e = uc + STR_LEN( noper );
1373 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1374 const U8 *scan = (U8*)NULL;
1375 U32 wordlen = 0; /* required init */
1378 if (OP(noper) == NOTHING) {
1383 TRIE_BITMAP_SET(trie,*uc);
1384 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1386 for ( ; uc < e ; uc += len ) {
1387 TRIE_CHARCOUNT(trie)++;
1391 if ( !trie->charmap[ uvc ] ) {
1392 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1394 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1400 widecharmap = newHV();
1402 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1405 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1407 if ( !SvTRUE( *svpp ) ) {
1408 sv_setiv( *svpp, ++trie->uniquecharcount );
1413 if( cur == first ) {
1416 } else if (chars < trie->minlen) {
1418 } else if (chars > trie->maxlen) {
1422 } /* end first pass */
1423 DEBUG_TRIE_COMPILE_r(
1424 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1425 (int)depth * 2 + 2,"",
1426 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1427 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1428 (int)trie->minlen, (int)trie->maxlen )
1430 trie->wordlen = (U32 *) PerlMemShared_calloc( word_count, sizeof(U32) );
1433 We now know what we are dealing with in terms of unique chars and
1434 string sizes so we can calculate how much memory a naive
1435 representation using a flat table will take. If it's over a reasonable
1436 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1437 conservative but potentially much slower representation using an array
1440 At the end we convert both representations into the same compressed
1441 form that will be used in regexec.c for matching with. The latter
1442 is a form that cannot be used to construct with but has memory
1443 properties similar to the list form and access properties similar
1444 to the table form making it both suitable for fast searches and
1445 small enough that its feasable to store for the duration of a program.
1447 See the comment in the code where the compressed table is produced
1448 inplace from the flat tabe representation for an explanation of how
1449 the compression works.
1454 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1456 Second Pass -- Array Of Lists Representation
1458 Each state will be represented by a list of charid:state records
1459 (reg_trie_trans_le) the first such element holds the CUR and LEN
1460 points of the allocated array. (See defines above).
1462 We build the initial structure using the lists, and then convert
1463 it into the compressed table form which allows faster lookups
1464 (but cant be modified once converted).
1467 STRLEN transcount = 1;
1469 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1470 "%*sCompiling trie using list compiler\n",
1471 (int)depth * 2 + 2, ""));
1473 trie->states = (reg_trie_state *)
1474 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1475 sizeof(reg_trie_state) );
1479 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1481 regnode * const noper = NEXTOPER( cur );
1482 U8 *uc = (U8*)STRING( noper );
1483 const U8 * const e = uc + STR_LEN( noper );
1484 U32 state = 1; /* required init */
1485 U16 charid = 0; /* sanity init */
1486 U8 *scan = (U8*)NULL; /* sanity init */
1487 STRLEN foldlen = 0; /* required init */
1488 U32 wordlen = 0; /* required init */
1489 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1491 if (OP(noper) != NOTHING) {
1492 for ( ; uc < e ; uc += len ) {
1497 charid = trie->charmap[ uvc ];
1499 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1503 charid=(U16)SvIV( *svpp );
1506 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1513 if ( !trie->states[ state ].trans.list ) {
1514 TRIE_LIST_NEW( state );
1516 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1517 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1518 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1523 newstate = next_alloc++;
1524 TRIE_LIST_PUSH( state, charid, newstate );
1529 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1533 TRIE_HANDLE_WORD(state);
1535 } /* end second pass */
1537 /* next alloc is the NEXT state to be allocated */
1538 trie->statecount = next_alloc;
1539 trie->states = (reg_trie_state *)
1540 PerlMemShared_realloc( trie->states,
1542 * sizeof(reg_trie_state) );
1544 /* and now dump it out before we compress it */
1545 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1546 revcharmap, next_alloc,
1550 trie->trans = (reg_trie_trans *)
1551 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1558 for( state=1 ; state < next_alloc ; state ++ ) {
1562 DEBUG_TRIE_COMPILE_MORE_r(
1563 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1567 if (trie->states[state].trans.list) {
1568 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1572 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1573 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1574 if ( forid < minid ) {
1576 } else if ( forid > maxid ) {
1580 if ( transcount < tp + maxid - minid + 1) {
1582 trie->trans = (reg_trie_trans *)
1583 PerlMemShared_realloc( trie->trans,
1585 * sizeof(reg_trie_trans) );
1586 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1588 base = trie->uniquecharcount + tp - minid;
1589 if ( maxid == minid ) {
1591 for ( ; zp < tp ; zp++ ) {
1592 if ( ! trie->trans[ zp ].next ) {
1593 base = trie->uniquecharcount + zp - minid;
1594 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1595 trie->trans[ zp ].check = state;
1601 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1602 trie->trans[ tp ].check = state;
1607 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1608 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1609 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1610 trie->trans[ tid ].check = state;
1612 tp += ( maxid - minid + 1 );
1614 Safefree(trie->states[ state ].trans.list);
1617 DEBUG_TRIE_COMPILE_MORE_r(
1618 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1621 trie->states[ state ].trans.base=base;
1623 trie->lasttrans = tp + 1;
1627 Second Pass -- Flat Table Representation.
1629 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1630 We know that we will need Charcount+1 trans at most to store the data
1631 (one row per char at worst case) So we preallocate both structures
1632 assuming worst case.
1634 We then construct the trie using only the .next slots of the entry
1637 We use the .check field of the first entry of the node temporarily to
1638 make compression both faster and easier by keeping track of how many non
1639 zero fields are in the node.
1641 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1644 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1645 number representing the first entry of the node, and state as a
1646 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1647 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1648 are 2 entrys per node. eg:
1656 The table is internally in the right hand, idx form. However as we also
1657 have to deal with the states array which is indexed by nodenum we have to
1658 use TRIE_NODENUM() to convert.
1661 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1662 "%*sCompiling trie using table compiler\n",
1663 (int)depth * 2 + 2, ""));
1665 trie->trans = (reg_trie_trans *)
1666 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1667 * trie->uniquecharcount + 1,
1668 sizeof(reg_trie_trans) );
1669 trie->states = (reg_trie_state *)
1670 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1671 sizeof(reg_trie_state) );
1672 next_alloc = trie->uniquecharcount + 1;
1675 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1677 regnode * const noper = NEXTOPER( cur );
1678 const U8 *uc = (U8*)STRING( noper );
1679 const U8 * const e = uc + STR_LEN( noper );
1681 U32 state = 1; /* required init */
1683 U16 charid = 0; /* sanity init */
1684 U32 accept_state = 0; /* sanity init */
1685 U8 *scan = (U8*)NULL; /* sanity init */
1687 STRLEN foldlen = 0; /* required init */
1688 U32 wordlen = 0; /* required init */
1689 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1691 if ( OP(noper) != NOTHING ) {
1692 for ( ; uc < e ; uc += len ) {
1697 charid = trie->charmap[ uvc ];
1699 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1700 charid = svpp ? (U16)SvIV(*svpp) : 0;
1704 if ( !trie->trans[ state + charid ].next ) {
1705 trie->trans[ state + charid ].next = next_alloc;
1706 trie->trans[ state ].check++;
1707 next_alloc += trie->uniquecharcount;
1709 state = trie->trans[ state + charid ].next;
1711 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1713 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1716 accept_state = TRIE_NODENUM( state );
1717 TRIE_HANDLE_WORD(accept_state);
1719 } /* end second pass */
1721 /* and now dump it out before we compress it */
1722 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1724 next_alloc, depth+1));
1728 * Inplace compress the table.*
1730 For sparse data sets the table constructed by the trie algorithm will
1731 be mostly 0/FAIL transitions or to put it another way mostly empty.
1732 (Note that leaf nodes will not contain any transitions.)
1734 This algorithm compresses the tables by eliminating most such
1735 transitions, at the cost of a modest bit of extra work during lookup:
1737 - Each states[] entry contains a .base field which indicates the
1738 index in the state[] array wheres its transition data is stored.
1740 - If .base is 0 there are no valid transitions from that node.
1742 - If .base is nonzero then charid is added to it to find an entry in
1745 -If trans[states[state].base+charid].check!=state then the
1746 transition is taken to be a 0/Fail transition. Thus if there are fail
1747 transitions at the front of the node then the .base offset will point
1748 somewhere inside the previous nodes data (or maybe even into a node
1749 even earlier), but the .check field determines if the transition is
1753 The following process inplace converts the table to the compressed
1754 table: We first do not compress the root node 1,and mark its all its
1755 .check pointers as 1 and set its .base pointer as 1 as well. This
1756 allows to do a DFA construction from the compressed table later, and
1757 ensures that any .base pointers we calculate later are greater than
1760 - We set 'pos' to indicate the first entry of the second node.
1762 - We then iterate over the columns of the node, finding the first and
1763 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1764 and set the .check pointers accordingly, and advance pos
1765 appropriately and repreat for the next node. Note that when we copy
1766 the next pointers we have to convert them from the original
1767 NODEIDX form to NODENUM form as the former is not valid post
1770 - If a node has no transitions used we mark its base as 0 and do not
1771 advance the pos pointer.
1773 - If a node only has one transition we use a second pointer into the
1774 structure to fill in allocated fail transitions from other states.
1775 This pointer is independent of the main pointer and scans forward
1776 looking for null transitions that are allocated to a state. When it
1777 finds one it writes the single transition into the "hole". If the
1778 pointer doesnt find one the single transition is appended as normal.
1780 - Once compressed we can Renew/realloc the structures to release the
1783 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1784 specifically Fig 3.47 and the associated pseudocode.
1788 const U32 laststate = TRIE_NODENUM( next_alloc );
1791 trie->statecount = laststate;
1793 for ( state = 1 ; state < laststate ; state++ ) {
1795 const U32 stateidx = TRIE_NODEIDX( state );
1796 const U32 o_used = trie->trans[ stateidx ].check;
1797 U32 used = trie->trans[ stateidx ].check;
1798 trie->trans[ stateidx ].check = 0;
1800 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1801 if ( flag || trie->trans[ stateidx + charid ].next ) {
1802 if ( trie->trans[ stateidx + charid ].next ) {
1804 for ( ; zp < pos ; zp++ ) {
1805 if ( ! trie->trans[ zp ].next ) {
1809 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1810 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1811 trie->trans[ zp ].check = state;
1812 if ( ++zp > pos ) pos = zp;
1819 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1821 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1822 trie->trans[ pos ].check = state;
1827 trie->lasttrans = pos + 1;
1828 trie->states = (reg_trie_state *)
1829 PerlMemShared_realloc( trie->states, laststate
1830 * sizeof(reg_trie_state) );
1831 DEBUG_TRIE_COMPILE_MORE_r(
1832 PerlIO_printf( Perl_debug_log,
1833 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1834 (int)depth * 2 + 2,"",
1835 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1838 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1841 } /* end table compress */
1843 DEBUG_TRIE_COMPILE_MORE_r(
1844 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1845 (int)depth * 2 + 2, "",
1846 (UV)trie->statecount,
1847 (UV)trie->lasttrans)
1849 /* resize the trans array to remove unused space */
1850 trie->trans = (reg_trie_trans *)
1851 PerlMemShared_realloc( trie->trans, trie->lasttrans
1852 * sizeof(reg_trie_trans) );
1854 /* and now dump out the compressed format */
1855 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
1857 { /* Modify the program and insert the new TRIE node*/
1858 U8 nodetype =(U8)(flags & 0xFF);
1862 regnode *optimize = NULL;
1863 #ifdef RE_TRACK_PATTERN_OFFSETS
1866 U32 mjd_nodelen = 0;
1867 #endif /* RE_TRACK_PATTERN_OFFSETS */
1868 #endif /* DEBUGGING */
1870 This means we convert either the first branch or the first Exact,
1871 depending on whether the thing following (in 'last') is a branch
1872 or not and whther first is the startbranch (ie is it a sub part of
1873 the alternation or is it the whole thing.)
1874 Assuming its a sub part we conver the EXACT otherwise we convert
1875 the whole branch sequence, including the first.
1877 /* Find the node we are going to overwrite */
1878 if ( first != startbranch || OP( last ) == BRANCH ) {
1879 /* branch sub-chain */
1880 NEXT_OFF( first ) = (U16)(last - first);
1881 #ifdef RE_TRACK_PATTERN_OFFSETS
1883 mjd_offset= Node_Offset((convert));
1884 mjd_nodelen= Node_Length((convert));
1887 /* whole branch chain */
1889 #ifdef RE_TRACK_PATTERN_OFFSETS
1892 const regnode *nop = NEXTOPER( convert );
1893 mjd_offset= Node_Offset((nop));
1894 mjd_nodelen= Node_Length((nop));
1898 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1899 (int)depth * 2 + 2, "",
1900 (UV)mjd_offset, (UV)mjd_nodelen)
1903 /* But first we check to see if there is a common prefix we can
1904 split out as an EXACT and put in front of the TRIE node. */
1905 trie->startstate= 1;
1906 if ( trie->bitmap && !widecharmap && !trie->jump ) {
1908 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1912 const U32 base = trie->states[ state ].trans.base;
1914 if ( trie->states[state].wordnum )
1917 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1918 if ( ( base + ofs >= trie->uniquecharcount ) &&
1919 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1920 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1922 if ( ++count > 1 ) {
1923 SV **tmp = av_fetch( revcharmap, ofs, 0);
1924 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1925 if ( state == 1 ) break;
1927 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1929 PerlIO_printf(Perl_debug_log,
1930 "%*sNew Start State=%"UVuf" Class: [",
1931 (int)depth * 2 + 2, "",
1934 SV ** const tmp = av_fetch( revcharmap, idx, 0);
1935 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1937 TRIE_BITMAP_SET(trie,*ch);
1939 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1941 PerlIO_printf(Perl_debug_log, (char*)ch)
1945 TRIE_BITMAP_SET(trie,*ch);
1947 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1948 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1954 SV **tmp = av_fetch( revcharmap, idx, 0);
1955 char *ch = SvPV_nolen( *tmp );
1957 SV *sv=sv_newmortal();
1958 PerlIO_printf( Perl_debug_log,
1959 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1960 (int)depth * 2 + 2, "",
1962 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
1963 PL_colors[0], PL_colors[1],
1964 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1965 PERL_PV_ESCAPE_FIRSTCHAR
1970 OP( convert ) = nodetype;
1971 str=STRING(convert);
1982 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1988 regnode *n = convert+NODE_SZ_STR(convert);
1989 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1990 trie->startstate = state;
1991 trie->minlen -= (state - 1);
1992 trie->maxlen -= (state - 1);
1994 regnode *fix = convert;
1995 U32 word = trie->wordcount;
1997 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1998 while( ++fix < n ) {
1999 Set_Node_Offset_Length(fix, 0, 0);
2002 SV ** const tmp = av_fetch( trie_words, word, 0 );
2004 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2005 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2007 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2014 NEXT_OFF(convert) = (U16)(tail - convert);
2015 DEBUG_r(optimize= n);
2021 if ( trie->maxlen ) {
2022 NEXT_OFF( convert ) = (U16)(tail - convert);
2023 ARG_SET( convert, data_slot );
2024 /* Store the offset to the first unabsorbed branch in
2025 jump[0], which is otherwise unused by the jump logic.
2026 We use this when dumping a trie and during optimisation. */
2028 trie->jump[0] = (U16)(nextbranch - convert);
2031 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
2032 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2034 OP( convert ) = TRIEC;
2035 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2036 PerlMemShared_free(trie->bitmap);
2039 OP( convert ) = TRIE;
2041 /* store the type in the flags */
2042 convert->flags = nodetype;
2046 + regarglen[ OP( convert ) ];
2048 /* XXX We really should free up the resource in trie now,
2049 as we won't use them - (which resources?) dmq */
2051 /* needed for dumping*/
2052 DEBUG_r(if (optimize) {
2053 regnode *opt = convert;
2055 while ( ++opt < optimize) {
2056 Set_Node_Offset_Length(opt,0,0);
2059 Try to clean up some of the debris left after the
2062 while( optimize < jumper ) {
2063 mjd_nodelen += Node_Length((optimize));
2064 OP( optimize ) = OPTIMIZED;
2065 Set_Node_Offset_Length(optimize,0,0);
2068 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2070 } /* end node insert */
2071 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2073 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2074 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2076 SvREFCNT_dec(revcharmap);
2080 : trie->startstate>1
2086 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2088 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2090 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2091 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2094 We find the fail state for each state in the trie, this state is the longest proper
2095 suffix of the current states 'word' that is also a proper prefix of another word in our
2096 trie. State 1 represents the word '' and is the thus the default fail state. This allows
2097 the DFA not to have to restart after its tried and failed a word at a given point, it
2098 simply continues as though it had been matching the other word in the first place.
2100 'abcdgu'=~/abcdefg|cdgu/
2101 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2102 fail, which would bring use to the state representing 'd' in the second word where we would
2103 try 'g' and succeed, prodceding to match 'cdgu'.
2105 /* add a fail transition */
2106 const U32 trie_offset = ARG(source);
2107 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2109 const U32 ucharcount = trie->uniquecharcount;
2110 const U32 numstates = trie->statecount;
2111 const U32 ubound = trie->lasttrans + ucharcount;
2115 U32 base = trie->states[ 1 ].trans.base;
2118 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2119 GET_RE_DEBUG_FLAGS_DECL;
2121 PERL_UNUSED_ARG(depth);
2125 ARG_SET( stclass, data_slot );
2126 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2127 RExC_rxi->data->data[ data_slot ] = (void*)aho;
2128 aho->trie=trie_offset;
2129 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2130 Copy( trie->states, aho->states, numstates, reg_trie_state );
2131 Newxz( q, numstates, U32);
2132 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2135 /* initialize fail[0..1] to be 1 so that we always have
2136 a valid final fail state */
2137 fail[ 0 ] = fail[ 1 ] = 1;
2139 for ( charid = 0; charid < ucharcount ; charid++ ) {
2140 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2142 q[ q_write ] = newstate;
2143 /* set to point at the root */
2144 fail[ q[ q_write++ ] ]=1;
2147 while ( q_read < q_write) {
2148 const U32 cur = q[ q_read++ % numstates ];
2149 base = trie->states[ cur ].trans.base;
2151 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2152 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2154 U32 fail_state = cur;
2157 fail_state = fail[ fail_state ];
2158 fail_base = aho->states[ fail_state ].trans.base;
2159 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2161 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2162 fail[ ch_state ] = fail_state;
2163 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2165 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2167 q[ q_write++ % numstates] = ch_state;
2171 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2172 when we fail in state 1, this allows us to use the
2173 charclass scan to find a valid start char. This is based on the principle
2174 that theres a good chance the string being searched contains lots of stuff
2175 that cant be a start char.
2177 fail[ 0 ] = fail[ 1 ] = 0;
2178 DEBUG_TRIE_COMPILE_r({
2179 PerlIO_printf(Perl_debug_log,
2180 "%*sStclass Failtable (%"UVuf" states): 0",
2181 (int)(depth * 2), "", (UV)numstates
2183 for( q_read=1; q_read<numstates; q_read++ ) {
2184 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2186 PerlIO_printf(Perl_debug_log, "\n");
2189 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2194 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2195 * These need to be revisited when a newer toolchain becomes available.
2197 #if defined(__sparc64__) && defined(__GNUC__)
2198 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2199 # undef SPARC64_GCC_WORKAROUND
2200 # define SPARC64_GCC_WORKAROUND 1
2204 #define DEBUG_PEEP(str,scan,depth) \
2205 DEBUG_OPTIMISE_r({if (scan){ \
2206 SV * const mysv=sv_newmortal(); \
2207 regnode *Next = regnext(scan); \
2208 regprop(RExC_rx, mysv, scan); \
2209 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2210 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2211 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2218 #define JOIN_EXACT(scan,min,flags) \
2219 if (PL_regkind[OP(scan)] == EXACT) \
2220 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2223 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2224 /* Merge several consecutive EXACTish nodes into one. */
2225 regnode *n = regnext(scan);
2227 regnode *next = scan + NODE_SZ_STR(scan);
2231 regnode *stop = scan;
2232 GET_RE_DEBUG_FLAGS_DECL;
2234 PERL_UNUSED_ARG(depth);
2236 #ifndef EXPERIMENTAL_INPLACESCAN
2237 PERL_UNUSED_ARG(flags);
2238 PERL_UNUSED_ARG(val);
2240 DEBUG_PEEP("join",scan,depth);
2242 /* Skip NOTHING, merge EXACT*. */
2244 ( PL_regkind[OP(n)] == NOTHING ||
2245 (stringok && (OP(n) == OP(scan))))
2247 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2249 if (OP(n) == TAIL || n > next)
2251 if (PL_regkind[OP(n)] == NOTHING) {
2252 DEBUG_PEEP("skip:",n,depth);
2253 NEXT_OFF(scan) += NEXT_OFF(n);
2254 next = n + NODE_STEP_REGNODE;
2261 else if (stringok) {
2262 const unsigned int oldl = STR_LEN(scan);
2263 regnode * const nnext = regnext(n);
2265 DEBUG_PEEP("merg",n,depth);
2268 if (oldl + STR_LEN(n) > U8_MAX)
2270 NEXT_OFF(scan) += NEXT_OFF(n);
2271 STR_LEN(scan) += STR_LEN(n);
2272 next = n + NODE_SZ_STR(n);
2273 /* Now we can overwrite *n : */
2274 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2282 #ifdef EXPERIMENTAL_INPLACESCAN
2283 if (flags && !NEXT_OFF(n)) {
2284 DEBUG_PEEP("atch", val, depth);
2285 if (reg_off_by_arg[OP(n)]) {
2286 ARG_SET(n, val - n);
2289 NEXT_OFF(n) = val - n;
2296 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2298 Two problematic code points in Unicode casefolding of EXACT nodes:
2300 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2301 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2307 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2308 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2310 This means that in case-insensitive matching (or "loose matching",
2311 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2312 length of the above casefolded versions) can match a target string
2313 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2314 This would rather mess up the minimum length computation.
2316 What we'll do is to look for the tail four bytes, and then peek
2317 at the preceding two bytes to see whether we need to decrease
2318 the minimum length by four (six minus two).
2320 Thanks to the design of UTF-8, there cannot be false matches:
2321 A sequence of valid UTF-8 bytes cannot be a subsequence of
2322 another valid sequence of UTF-8 bytes.
2325 char * const s0 = STRING(scan), *s, *t;
2326 char * const s1 = s0 + STR_LEN(scan) - 1;
2327 char * const s2 = s1 - 4;
2328 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2329 const char t0[] = "\xaf\x49\xaf\x42";
2331 const char t0[] = "\xcc\x88\xcc\x81";
2333 const char * const t1 = t0 + 3;
2336 s < s2 && (t = ninstr(s, s1, t0, t1));
2339 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2340 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2342 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2343 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2351 n = scan + NODE_SZ_STR(scan);
2353 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2360 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2364 /* REx optimizer. Converts nodes into quickier variants "in place".
2365 Finds fixed substrings. */
2367 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2368 to the position after last scanned or to NULL. */
2370 #define INIT_AND_WITHP \
2371 assert(!and_withp); \
2372 Newx(and_withp,1,struct regnode_charclass_class); \
2373 SAVEFREEPV(and_withp)
2375 /* this is a chain of data about sub patterns we are processing that
2376 need to be handled seperately/specially in study_chunk. Its so
2377 we can simulate recursion without losing state. */
2379 typedef struct scan_frame {
2380 regnode *last; /* last node to process in this frame */
2381 regnode *next; /* next node to process when last is reached */
2382 struct scan_frame *prev; /*previous frame*/
2383 I32 stop; /* what stopparen do we use */
2387 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2390 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2391 I32 *minlenp, I32 *deltap,
2396 struct regnode_charclass_class *and_withp,
2397 U32 flags, U32 depth)
2398 /* scanp: Start here (read-write). */
2399 /* deltap: Write maxlen-minlen here. */
2400 /* last: Stop before this one. */
2401 /* data: string data about the pattern */
2402 /* stopparen: treat close N as END */
2403 /* recursed: which subroutines have we recursed into */
2404 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2407 I32 min = 0, pars = 0, code;
2408 regnode *scan = *scanp, *next;
2410 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2411 int is_inf_internal = 0; /* The studied chunk is infinite */
2412 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2413 scan_data_t data_fake;
2414 SV *re_trie_maxbuff = NULL;
2415 regnode *first_non_open = scan;
2416 I32 stopmin = I32_MAX;
2417 scan_frame *frame = NULL;
2419 GET_RE_DEBUG_FLAGS_DECL;
2422 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2426 while (first_non_open && OP(first_non_open) == OPEN)
2427 first_non_open=regnext(first_non_open);
2432 while ( scan && OP(scan) != END && scan < last ){
2433 /* Peephole optimizer: */
2434 DEBUG_STUDYDATA("Peep:", data,depth);
2435 DEBUG_PEEP("Peep",scan,depth);
2436 JOIN_EXACT(scan,&min,0);
2438 /* Follow the next-chain of the current node and optimize
2439 away all the NOTHINGs from it. */
2440 if (OP(scan) != CURLYX) {
2441 const int max = (reg_off_by_arg[OP(scan)]
2443 /* I32 may be smaller than U16 on CRAYs! */
2444 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2445 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2449 /* Skip NOTHING and LONGJMP. */
2450 while ((n = regnext(n))
2451 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2452 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2453 && off + noff < max)
2455 if (reg_off_by_arg[OP(scan)])
2458 NEXT_OFF(scan) = off;
2463 /* The principal pseudo-switch. Cannot be a switch, since we
2464 look into several different things. */
2465 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2466 || OP(scan) == IFTHEN) {
2467 next = regnext(scan);
2469 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2471 if (OP(next) == code || code == IFTHEN) {
2472 /* NOTE - There is similar code to this block below for handling
2473 TRIE nodes on a re-study. If you change stuff here check there
2475 I32 max1 = 0, min1 = I32_MAX, num = 0;
2476 struct regnode_charclass_class accum;
2477 regnode * const startbranch=scan;
2479 if (flags & SCF_DO_SUBSTR)
2480 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2481 if (flags & SCF_DO_STCLASS)
2482 cl_init_zero(pRExC_state, &accum);
2484 while (OP(scan) == code) {
2485 I32 deltanext, minnext, f = 0, fake;
2486 struct regnode_charclass_class this_class;
2489 data_fake.flags = 0;
2491 data_fake.whilem_c = data->whilem_c;
2492 data_fake.last_closep = data->last_closep;
2495 data_fake.last_closep = &fake;
2497 data_fake.pos_delta = delta;
2498 next = regnext(scan);
2499 scan = NEXTOPER(scan);
2501 scan = NEXTOPER(scan);
2502 if (flags & SCF_DO_STCLASS) {
2503 cl_init(pRExC_state, &this_class);
2504 data_fake.start_class = &this_class;
2505 f = SCF_DO_STCLASS_AND;
2507 if (flags & SCF_WHILEM_VISITED_POS)
2508 f |= SCF_WHILEM_VISITED_POS;
2510 /* we suppose the run is continuous, last=next...*/
2511 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2513 stopparen, recursed, NULL, f,depth+1);
2516 if (max1 < minnext + deltanext)
2517 max1 = minnext + deltanext;
2518 if (deltanext == I32_MAX)
2519 is_inf = is_inf_internal = 1;
2521 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2523 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2524 if ( stopmin > minnext)
2525 stopmin = min + min1;
2526 flags &= ~SCF_DO_SUBSTR;
2528 data->flags |= SCF_SEEN_ACCEPT;
2531 if (data_fake.flags & SF_HAS_EVAL)
2532 data->flags |= SF_HAS_EVAL;
2533 data->whilem_c = data_fake.whilem_c;
2535 if (flags & SCF_DO_STCLASS)
2536 cl_or(pRExC_state, &accum, &this_class);
2538 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2540 if (flags & SCF_DO_SUBSTR) {
2541 data->pos_min += min1;
2542 data->pos_delta += max1 - min1;
2543 if (max1 != min1 || is_inf)
2544 data->longest = &(data->longest_float);
2547 delta += max1 - min1;
2548 if (flags & SCF_DO_STCLASS_OR) {
2549 cl_or(pRExC_state, data->start_class, &accum);
2551 cl_and(data->start_class, and_withp);
2552 flags &= ~SCF_DO_STCLASS;
2555 else if (flags & SCF_DO_STCLASS_AND) {
2557 cl_and(data->start_class, &accum);
2558 flags &= ~SCF_DO_STCLASS;
2561 /* Switch to OR mode: cache the old value of
2562 * data->start_class */
2564 StructCopy(data->start_class, and_withp,
2565 struct regnode_charclass_class);
2566 flags &= ~SCF_DO_STCLASS_AND;
2567 StructCopy(&accum, data->start_class,
2568 struct regnode_charclass_class);
2569 flags |= SCF_DO_STCLASS_OR;
2570 data->start_class->flags |= ANYOF_EOS;
2574 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2577 Assuming this was/is a branch we are dealing with: 'scan' now
2578 points at the item that follows the branch sequence, whatever
2579 it is. We now start at the beginning of the sequence and look
2586 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2588 If we can find such a subseqence we need to turn the first
2589 element into a trie and then add the subsequent branch exact
2590 strings to the trie.
2594 1. patterns where the whole set of branch can be converted.
2596 2. patterns where only a subset can be converted.
2598 In case 1 we can replace the whole set with a single regop
2599 for the trie. In case 2 we need to keep the start and end
2602 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2603 becomes BRANCH TRIE; BRANCH X;
2605 There is an additional case, that being where there is a
2606 common prefix, which gets split out into an EXACT like node
2607 preceding the TRIE node.
2609 If x(1..n)==tail then we can do a simple trie, if not we make
2610 a "jump" trie, such that when we match the appropriate word
2611 we "jump" to the appopriate tail node. Essentailly we turn
2612 a nested if into a case structure of sorts.
2617 if (!re_trie_maxbuff) {
2618 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2619 if (!SvIOK(re_trie_maxbuff))
2620 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2622 if ( SvIV(re_trie_maxbuff)>=0 ) {
2624 regnode *first = (regnode *)NULL;
2625 regnode *last = (regnode *)NULL;
2626 regnode *tail = scan;
2631 SV * const mysv = sv_newmortal(); /* for dumping */
2633 /* var tail is used because there may be a TAIL
2634 regop in the way. Ie, the exacts will point to the
2635 thing following the TAIL, but the last branch will
2636 point at the TAIL. So we advance tail. If we
2637 have nested (?:) we may have to move through several
2641 while ( OP( tail ) == TAIL ) {
2642 /* this is the TAIL generated by (?:) */
2643 tail = regnext( tail );
2648 regprop(RExC_rx, mysv, tail );
2649 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2650 (int)depth * 2 + 2, "",
2651 "Looking for TRIE'able sequences. Tail node is: ",
2652 SvPV_nolen_const( mysv )
2658 step through the branches, cur represents each
2659 branch, noper is the first thing to be matched
2660 as part of that branch and noper_next is the
2661 regnext() of that node. if noper is an EXACT
2662 and noper_next is the same as scan (our current
2663 position in the regex) then the EXACT branch is
2664 a possible optimization target. Once we have
2665 two or more consequetive such branches we can
2666 create a trie of the EXACT's contents and stich
2667 it in place. If the sequence represents all of
2668 the branches we eliminate the whole thing and
2669 replace it with a single TRIE. If it is a
2670 subsequence then we need to stitch it in. This
2671 means the first branch has to remain, and needs
2672 to be repointed at the item on the branch chain
2673 following the last branch optimized. This could
2674 be either a BRANCH, in which case the
2675 subsequence is internal, or it could be the
2676 item following the branch sequence in which
2677 case the subsequence is at the end.
2681 /* dont use tail as the end marker for this traverse */
2682 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2683 regnode * const noper = NEXTOPER( cur );
2684 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2685 regnode * const noper_next = regnext( noper );
2689 regprop(RExC_rx, mysv, cur);
2690 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2691 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2693 regprop(RExC_rx, mysv, noper);
2694 PerlIO_printf( Perl_debug_log, " -> %s",
2695 SvPV_nolen_const(mysv));
2698 regprop(RExC_rx, mysv, noper_next );
2699 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2700 SvPV_nolen_const(mysv));
2702 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2703 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2705 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2706 : PL_regkind[ OP( noper ) ] == EXACT )
2707 || OP(noper) == NOTHING )
2709 && noper_next == tail
2714 if ( !first || optype == NOTHING ) {
2715 if (!first) first = cur;
2716 optype = OP( noper );
2722 make_trie( pRExC_state,
2723 startbranch, first, cur, tail, count,
2726 if ( PL_regkind[ OP( noper ) ] == EXACT
2728 && noper_next == tail
2733 optype = OP( noper );
2743 regprop(RExC_rx, mysv, cur);
2744 PerlIO_printf( Perl_debug_log,
2745 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2746 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2750 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2751 #ifdef TRIE_STUDY_OPT
2752 if ( ((made == MADE_EXACT_TRIE &&
2753 startbranch == first)
2754 || ( first_non_open == first )) &&
2756 flags |= SCF_TRIE_RESTUDY;
2757 if ( startbranch == first
2760 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2770 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2771 scan = NEXTOPER(NEXTOPER(scan));
2772 } else /* single branch is optimized. */
2773 scan = NEXTOPER(scan);
2775 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2776 scan_frame *newframe = NULL;
2781 if (OP(scan) != SUSPEND) {
2782 /* set the pointer */
2783 if (OP(scan) == GOSUB) {
2785 RExC_recurse[ARG2L(scan)] = scan;
2786 start = RExC_open_parens[paren-1];
2787 end = RExC_close_parens[paren-1];
2790 start = RExC_rxi->program + 1;
2794 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2795 SAVEFREEPV(recursed);
2797 if (!PAREN_TEST(recursed,paren+1)) {
2798 PAREN_SET(recursed,paren+1);
2799 Newx(newframe,1,scan_frame);
2801 if (flags & SCF_DO_SUBSTR) {
2802 SCAN_COMMIT(pRExC_state,data,minlenp);
2803 data->longest = &(data->longest_float);
2805 is_inf = is_inf_internal = 1;
2806 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2807 cl_anything(pRExC_state, data->start_class);
2808 flags &= ~SCF_DO_STCLASS;
2811 Newx(newframe,1,scan_frame);
2814 end = regnext(scan);
2819 SAVEFREEPV(newframe);
2820 newframe->next = regnext(scan);
2821 newframe->last = last;
2822 newframe->stop = stopparen;
2823 newframe->prev = frame;
2833 else if (OP(scan) == EXACT) {
2834 I32 l = STR_LEN(scan);
2837 const U8 * const s = (U8*)STRING(scan);
2838 l = utf8_length(s, s + l);
2839 uc = utf8_to_uvchr(s, NULL);
2841 uc = *((U8*)STRING(scan));
2844 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2845 /* The code below prefers earlier match for fixed
2846 offset, later match for variable offset. */
2847 if (data->last_end == -1) { /* Update the start info. */
2848 data->last_start_min = data->pos_min;
2849 data->last_start_max = is_inf
2850 ? I32_MAX : data->pos_min + data->pos_delta;
2852 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2854 SvUTF8_on(data->last_found);
2856 SV * const sv = data->last_found;
2857 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2858 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2859 if (mg && mg->mg_len >= 0)
2860 mg->mg_len += utf8_length((U8*)STRING(scan),
2861 (U8*)STRING(scan)+STR_LEN(scan));
2863 data->last_end = data->pos_min + l;
2864 data->pos_min += l; /* As in the first entry. */
2865 data->flags &= ~SF_BEFORE_EOL;
2867 if (flags & SCF_DO_STCLASS_AND) {
2868 /* Check whether it is compatible with what we know already! */
2872 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2873 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2874 && (!(data->start_class->flags & ANYOF_FOLD)
2875 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2878 ANYOF_CLASS_ZERO(data->start_class);
2879 ANYOF_BITMAP_ZERO(data->start_class);
2881 ANYOF_BITMAP_SET(data->start_class, uc);
2882 data->start_class->flags &= ~ANYOF_EOS;
2884 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2886 else if (flags & SCF_DO_STCLASS_OR) {
2887 /* false positive possible if the class is case-folded */
2889 ANYOF_BITMAP_SET(data->start_class, uc);
2891 data->start_class->flags |= ANYOF_UNICODE_ALL;
2892 data->start_class->flags &= ~ANYOF_EOS;
2893 cl_and(data->start_class, and_withp);
2895 flags &= ~SCF_DO_STCLASS;
2897 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2898 I32 l = STR_LEN(scan);
2899 UV uc = *((U8*)STRING(scan));
2901 /* Search for fixed substrings supports EXACT only. */
2902 if (flags & SCF_DO_SUBSTR) {
2904 SCAN_COMMIT(pRExC_state, data, minlenp);
2907 const U8 * const s = (U8 *)STRING(scan);
2908 l = utf8_length(s, s + l);
2909 uc = utf8_to_uvchr(s, NULL);
2912 if (flags & SCF_DO_SUBSTR)
2914 if (flags & SCF_DO_STCLASS_AND) {
2915 /* Check whether it is compatible with what we know already! */
2919 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2920 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2921 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2923 ANYOF_CLASS_ZERO(data->start_class);
2924 ANYOF_BITMAP_ZERO(data->start_class);
2926 ANYOF_BITMAP_SET(data->start_class, uc);
2927 data->start_class->flags &= ~ANYOF_EOS;
2928 data->start_class->flags |= ANYOF_FOLD;
2929 if (OP(scan) == EXACTFL)
2930 data->start_class->flags |= ANYOF_LOCALE;
2933 else if (flags & SCF_DO_STCLASS_OR) {
2934 if (data->start_class->flags & ANYOF_FOLD) {
2935 /* false positive possible if the class is case-folded.
2936 Assume that the locale settings are the same... */
2938 ANYOF_BITMAP_SET(data->start_class, uc);
2939 data->start_class->flags &= ~ANYOF_EOS;
2941 cl_and(data->start_class, and_withp);
2943 flags &= ~SCF_DO_STCLASS;
2945 else if (strchr((const char*)PL_varies,OP(scan))) {
2946 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2947 I32 f = flags, pos_before = 0;
2948 regnode * const oscan = scan;
2949 struct regnode_charclass_class this_class;
2950 struct regnode_charclass_class *oclass = NULL;
2951 I32 next_is_eval = 0;
2953 switch (PL_regkind[OP(scan)]) {
2954 case WHILEM: /* End of (?:...)* . */
2955 scan = NEXTOPER(scan);
2958 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2959 next = NEXTOPER(scan);
2960 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2962 maxcount = REG_INFTY;
2963 next = regnext(scan);
2964 scan = NEXTOPER(scan);
2968 if (flags & SCF_DO_SUBSTR)
2973 if (flags & SCF_DO_STCLASS) {
2975 maxcount = REG_INFTY;
2976 next = regnext(scan);
2977 scan = NEXTOPER(scan);
2980 is_inf = is_inf_internal = 1;
2981 scan = regnext(scan);
2982 if (flags & SCF_DO_SUBSTR) {
2983 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2984 data->longest = &(data->longest_float);
2986 goto optimize_curly_tail;
2988 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
2989 && (scan->flags == stopparen))
2994 mincount = ARG1(scan);
2995 maxcount = ARG2(scan);
2997 next = regnext(scan);
2998 if (OP(scan) == CURLYX) {
2999 I32 lp = (data ? *(data->last_closep) : 0);
3000 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3002 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3003 next_is_eval = (OP(scan) == EVAL);
3005 if (flags & SCF_DO_SUBSTR) {
3006 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3007 pos_before = data->pos_min;
3011 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3013 data->flags |= SF_IS_INF;
3015 if (flags & SCF_DO_STCLASS) {
3016 cl_init(pRExC_state, &this_class);
3017 oclass = data->start_class;
3018 data->start_class = &this_class;
3019 f |= SCF_DO_STCLASS_AND;
3020 f &= ~SCF_DO_STCLASS_OR;
3022 /* These are the cases when once a subexpression
3023 fails at a particular position, it cannot succeed
3024 even after backtracking at the enclosing scope.
3026 XXXX what if minimal match and we are at the
3027 initial run of {n,m}? */
3028 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
3029 f &= ~SCF_WHILEM_VISITED_POS;
3031 /* This will finish on WHILEM, setting scan, or on NULL: */
3032 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3033 last, data, stopparen, recursed, NULL,
3035 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3037 if (flags & SCF_DO_STCLASS)
3038 data->start_class = oclass;
3039 if (mincount == 0 || minnext == 0) {
3040 if (flags & SCF_DO_STCLASS_OR) {
3041 cl_or(pRExC_state, data->start_class, &this_class);
3043 else if (flags & SCF_DO_STCLASS_AND) {
3044 /* Switch to OR mode: cache the old value of
3045 * data->start_class */
3047 StructCopy(data->start_class, and_withp,
3048 struct regnode_charclass_class);
3049 flags &= ~SCF_DO_STCLASS_AND;
3050 StructCopy(&this_class, data->start_class,
3051 struct regnode_charclass_class);
3052 flags |= SCF_DO_STCLASS_OR;
3053 data->start_class->flags |= ANYOF_EOS;
3055 } else { /* Non-zero len */
3056 if (flags & SCF_DO_STCLASS_OR) {
3057 cl_or(pRExC_state, data->start_class, &this_class);
3058 cl_and(data->start_class, and_withp);
3060 else if (flags & SCF_DO_STCLASS_AND)
3061 cl_and(data->start_class, &this_class);
3062 flags &= ~SCF_DO_STCLASS;
3064 if (!scan) /* It was not CURLYX, but CURLY. */
3066 if ( /* ? quantifier ok, except for (?{ ... }) */
3067 (next_is_eval || !(mincount == 0 && maxcount == 1))
3068 && (minnext == 0) && (deltanext == 0)
3069 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3070 && maxcount <= REG_INFTY/3 /* Complement check for big count */
3071 && ckWARN(WARN_REGEXP))
3074 "Quantifier unexpected on zero-length expression");
3077 min += minnext * mincount;
3078 is_inf_internal |= ((maxcount == REG_INFTY
3079 && (minnext + deltanext) > 0)
3080 || deltanext == I32_MAX);
3081 is_inf |= is_inf_internal;
3082 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3084 /* Try powerful optimization CURLYX => CURLYN. */
3085 if ( OP(oscan) == CURLYX && data
3086 && data->flags & SF_IN_PAR
3087 && !(data->flags & SF_HAS_EVAL)
3088 && !deltanext && minnext == 1 ) {
3089 /* Try to optimize to CURLYN. */
3090 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3091 regnode * const nxt1 = nxt;
3098 if (!strchr((const char*)PL_simple,OP(nxt))
3099 && !(PL_regkind[OP(nxt)] == EXACT
3100 && STR_LEN(nxt) == 1))
3106 if (OP(nxt) != CLOSE)
3108 if (RExC_open_parens) {
3109 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3110 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3112 /* Now we know that nxt2 is the only contents: */
3113 oscan->flags = (U8)ARG(nxt);
3115 OP(nxt1) = NOTHING; /* was OPEN. */
3118 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3119 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
3120 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
3121 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3122 OP(nxt + 1) = OPTIMIZED; /* was count. */
3123 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
3128 /* Try optimization CURLYX => CURLYM. */
3129 if ( OP(oscan) == CURLYX && data
3130 && !(data->flags & SF_HAS_PAR)
3131 && !(data->flags & SF_HAS_EVAL)
3132 && !deltanext /* atom is fixed width */
3133 && minnext != 0 /* CURLYM can't handle zero width */
3135 /* XXXX How to optimize if data == 0? */
3136 /* Optimize to a simpler form. */
3137 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3141 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3142 && (OP(nxt2) != WHILEM))
3144 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3145 /* Need to optimize away parenths. */
3146 if (data->flags & SF_IN_PAR) {
3147 /* Set the parenth number. */
3148 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3150 if (OP(nxt) != CLOSE)
3151 FAIL("Panic opt close");
3152 oscan->flags = (U8)ARG(nxt);
3153 if (RExC_open_parens) {
3154 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3155 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3157 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3158 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3161 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3162 OP(nxt + 1) = OPTIMIZED; /* was count. */
3163 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3164 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3167 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3168 regnode *nnxt = regnext(nxt1);
3171 if (reg_off_by_arg[OP(nxt1)])
3172 ARG_SET(nxt1, nxt2 - nxt1);
3173 else if (nxt2 - nxt1 < U16_MAX)
3174 NEXT_OFF(nxt1) = nxt2 - nxt1;
3176 OP(nxt) = NOTHING; /* Cannot beautify */
3181 /* Optimize again: */
3182 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3183 NULL, stopparen, recursed, NULL, 0,depth+1);
3188 else if ((OP(oscan) == CURLYX)
3189 && (flags & SCF_WHILEM_VISITED_POS)
3190 /* See the comment on a similar expression above.
3191 However, this time it not a subexpression
3192 we care about, but the expression itself. */
3193 && (maxcount == REG_INFTY)
3194 && data && ++data->whilem_c < 16) {
3195 /* This stays as CURLYX, we can put the count/of pair. */
3196 /* Find WHILEM (as in regexec.c) */
3197 regnode *nxt = oscan + NEXT_OFF(oscan);
3199 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3201 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3202 | (RExC_whilem_seen << 4)); /* On WHILEM */
3204 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3206 if (flags & SCF_DO_SUBSTR) {
3207 SV *last_str = NULL;
3208 int counted = mincount != 0;
3210 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3211 #if defined(SPARC64_GCC_WORKAROUND)
3214 const char *s = NULL;
3217 if (pos_before >= data->last_start_min)
3220 b = data->last_start_min;
3223 s = SvPV_const(data->last_found, l);
3224 old = b - data->last_start_min;
3227 I32 b = pos_before >= data->last_start_min
3228 ? pos_before : data->last_start_min;
3230 const char * const s = SvPV_const(data->last_found, l);
3231 I32 old = b - data->last_start_min;
3235 old = utf8_hop((U8*)s, old) - (U8*)s;
3238 /* Get the added string: */
3239 last_str = newSVpvn(s + old, l);
3241 SvUTF8_on(last_str);
3242 if (deltanext == 0 && pos_before == b) {
3243 /* What was added is a constant string */
3245 SvGROW(last_str, (mincount * l) + 1);
3246 repeatcpy(SvPVX(last_str) + l,
3247 SvPVX_const(last_str), l, mincount - 1);
3248 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3249 /* Add additional parts. */
3250 SvCUR_set(data->last_found,
3251 SvCUR(data->last_found) - l);
3252 sv_catsv(data->last_found, last_str);
3254 SV * sv = data->last_found;
3256 SvUTF8(sv) && SvMAGICAL(sv) ?
3257 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3258 if (mg && mg->mg_len >= 0)
3259 mg->mg_len += CHR_SVLEN(last_str);
3261 data->last_end += l * (mincount - 1);
3264 /* start offset must point into the last copy */
3265 data->last_start_min += minnext * (mincount - 1);
3266 data->last_start_max += is_inf ? I32_MAX
3267 : (maxcount - 1) * (minnext + data->pos_delta);
3270 /* It is counted once already... */
3271 data->pos_min += minnext * (mincount - counted);
3272 data->pos_delta += - counted * deltanext +
3273 (minnext + deltanext) * maxcount - minnext * mincount;
3274 if (mincount != maxcount) {
3275 /* Cannot extend fixed substrings found inside
3277 SCAN_COMMIT(pRExC_state,data,minlenp);
3278 if (mincount && last_str) {
3279 SV * const sv = data->last_found;
3280 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3281 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3285 sv_setsv(sv, last_str);
3286 data->last_end = data->pos_min;
3287 data->last_start_min =
3288 data->pos_min - CHR_SVLEN(last_str);
3289 data->last_start_max = is_inf
3291 : data->pos_min + data->pos_delta
3292 - CHR_SVLEN(last_str);
3294 data->longest = &(data->longest_float);
3296 SvREFCNT_dec(last_str);
3298 if (data && (fl & SF_HAS_EVAL))
3299 data->flags |= SF_HAS_EVAL;
3300 optimize_curly_tail:
3301 if (OP(oscan) != CURLYX) {
3302 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3304 NEXT_OFF(oscan) += NEXT_OFF(next);
3307 default: /* REF and CLUMP only? */
3308 if (flags & SCF_DO_SUBSTR) {
3309 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3310 data->longest = &(data->longest_float);
3312 is_inf = is_inf_internal = 1;
3313 if (flags & SCF_DO_STCLASS_OR)
3314 cl_anything(pRExC_state, data->start_class);
3315 flags &= ~SCF_DO_STCLASS;
3319 else if (strchr((const char*)PL_simple,OP(scan))) {
3322 if (flags & SCF_DO_SUBSTR) {
3323 SCAN_COMMIT(pRExC_state,data,minlenp);
3327 if (flags & SCF_DO_STCLASS) {
3328 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3330 /* Some of the logic below assumes that switching
3331 locale on will only add false positives. */
3332 switch (PL_regkind[OP(scan)]) {
3336 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3337 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3338 cl_anything(pRExC_state, data->start_class);
3341 if (OP(scan) == SANY)
3343 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3344 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3345 || (data->start_class->flags & ANYOF_CLASS));
3346 cl_anything(pRExC_state, data->start_class);
3348 if (flags & SCF_DO_STCLASS_AND || !value)
3349 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3352 if (flags & SCF_DO_STCLASS_AND)
3353 cl_and(data->start_class,
3354 (struct regnode_charclass_class*)scan);
3356 cl_or(pRExC_state, data->start_class,
3357 (struct regnode_charclass_class*)scan);
3360 if (flags & SCF_DO_STCLASS_AND) {
3361 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3362 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3363 for (value = 0; value < 256; value++)
3364 if (!isALNUM(value))
3365 ANYOF_BITMAP_CLEAR(data->start_class, value);
3369 if (data->start_class->flags & ANYOF_LOCALE)
3370 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3372 for (value = 0; value < 256; value++)
3374 ANYOF_BITMAP_SET(data->start_class, value);
3379 if (flags & SCF_DO_STCLASS_AND) {
3380 if (data->start_class->flags & ANYOF_LOCALE)
3381 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3384 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3385 data->start_class->flags |= ANYOF_LOCALE;
3389 if (flags & SCF_DO_STCLASS_AND) {
3390 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3391 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3392 for (value = 0; value < 256; value++)
3394 ANYOF_BITMAP_CLEAR(data->start_class, value);
3398 if (data->start_class->flags & ANYOF_LOCALE)
3399 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3401 for (value = 0; value < 256; value++)
3402 if (!isALNUM(value))
3403 ANYOF_BITMAP_SET(data->start_class, value);
3408 if (flags & SCF_DO_STCLASS_AND) {
3409 if (data->start_class->flags & ANYOF_LOCALE)
3410 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3413 data->start_class->flags |= ANYOF_LOCALE;
3414 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3418 if (flags & SCF_DO_STCLASS_AND) {
3419 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3420 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3421 for (value = 0; value < 256; value++)
3422 if (!isSPACE(value))
3423 ANYOF_BITMAP_CLEAR(data->start_class, value);
3427 if (data->start_class->flags & ANYOF_LOCALE)
3428 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3430 for (value = 0; value < 256; value++)
3432 ANYOF_BITMAP_SET(data->start_class, value);
3437 if (flags & SCF_DO_STCLASS_AND) {
3438 if (data->start_class->flags & ANYOF_LOCALE)
3439 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3442 data->start_class->flags |= ANYOF_LOCALE;
3443 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3447 if (flags & SCF_DO_STCLASS_AND) {
3448 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3449 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3450 for (value = 0; value < 256; value++)
3452 ANYOF_BITMAP_CLEAR(data->start_class, value);
3456 if (data->start_class->flags & ANYOF_LOCALE)
3457 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3459 for (value = 0; value < 256; value++)
3460 if (!isSPACE(value))
3461 ANYOF_BITMAP_SET(data->start_class, value);
3466 if (flags & SCF_DO_STCLASS_AND) {
3467 if (data->start_class->flags & ANYOF_LOCALE) {
3468 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3469 for (value = 0; value < 256; value++)
3470 if (!isSPACE(value))
3471 ANYOF_BITMAP_CLEAR(data->start_class, value);
3475 data->start_class->flags |= ANYOF_LOCALE;
3476 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3480 if (flags & SCF_DO_STCLASS_AND) {
3481 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3482 for (value = 0; value < 256; value++)
3483 if (!isDIGIT(value))
3484 ANYOF_BITMAP_CLEAR(data->start_class, value);
3487 if (data->start_class->flags & ANYOF_LOCALE)
3488 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3490 for (value = 0; value < 256; value++)
3492 ANYOF_BITMAP_SET(data->start_class, value);
3497 if (flags & SCF_DO_STCLASS_AND) {
3498 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3499 for (value = 0; value < 256; value++)
3501 ANYOF_BITMAP_CLEAR(data->start_class, value);
3504 if (data->start_class->flags & ANYOF_LOCALE)
3505 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3507 for (value = 0; value < 256; value++)
3508 if (!isDIGIT(value))
3509 ANYOF_BITMAP_SET(data->start_class, value);
3514 if (flags & SCF_DO_STCLASS_OR)
3515 cl_and(data->start_class, and_withp);
3516 flags &= ~SCF_DO_STCLASS;
3519 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3520 data->flags |= (OP(scan) == MEOL
3524 else if ( PL_regkind[OP(scan)] == BRANCHJ
3525 /* Lookbehind, or need to calculate parens/evals/stclass: */
3526 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3527 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3528 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3529 || OP(scan) == UNLESSM )
3531 /* Negative Lookahead/lookbehind
3532 In this case we can't do fixed string optimisation.
3535 I32 deltanext, minnext, fake = 0;
3537 struct regnode_charclass_class intrnl;
3540 data_fake.flags = 0;
3542 data_fake.whilem_c = data->whilem_c;
3543 data_fake.last_closep = data->last_closep;
3546 data_fake.last_closep = &fake;
3547 data_fake.pos_delta = delta;
3548 if ( flags & SCF_DO_STCLASS && !scan->flags
3549 && OP(scan) == IFMATCH ) { /* Lookahead */
3550 cl_init(pRExC_state, &intrnl);
3551 data_fake.start_class = &intrnl;
3552 f |= SCF_DO_STCLASS_AND;
3554 if (flags & SCF_WHILEM_VISITED_POS)
3555 f |= SCF_WHILEM_VISITED_POS;
3556 next = regnext(scan);
3557 nscan = NEXTOPER(NEXTOPER(scan));
3558 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
3559 last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3562 FAIL("Variable length lookbehind not implemented");
3564 else if (minnext > (I32)U8_MAX) {
3565 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3567 scan->flags = (U8)minnext;
3570 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3572 if (data_fake.flags & SF_HAS_EVAL)
3573 data->flags |= SF_HAS_EVAL;
3574 data->whilem_c = data_fake.whilem_c;
3576 if (f & SCF_DO_STCLASS_AND) {
3577 const int was = (data->start_class->flags & ANYOF_EOS);
3579 cl_and(data->start_class, &intrnl);
3581 data->start_class->flags |= ANYOF_EOS;
3584 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3586 /* Positive Lookahead/lookbehind
3587 In this case we can do fixed string optimisation,
3588 but we must be careful about it. Note in the case of
3589 lookbehind the positions will be offset by the minimum
3590 length of the pattern, something we won't know about
3591 until after the recurse.
3593 I32 deltanext, fake = 0;
3595 struct regnode_charclass_class intrnl;
3597 /* We use SAVEFREEPV so that when the full compile
3598 is finished perl will clean up the allocated
3599 minlens when its all done. This was we don't
3600 have to worry about freeing them when we know
3601 they wont be used, which would be a pain.
3604 Newx( minnextp, 1, I32 );
3605 SAVEFREEPV(minnextp);
3608 StructCopy(data, &data_fake, scan_data_t);
3609 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3612 SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
3613 data_fake.last_found=newSVsv(data->last_found);
3617 data_fake.last_closep = &fake;
3618 data_fake.flags = 0;
3619 data_fake.pos_delta = delta;
3621 data_fake.flags |= SF_IS_INF;
3622 if ( flags & SCF_DO_STCLASS && !scan->flags
3623 && OP(scan) == IFMATCH ) { /* Lookahead */
3624 cl_init(pRExC_state, &intrnl);
3625 data_fake.start_class = &intrnl;
3626 f |= SCF_DO_STCLASS_AND;
3628 if (flags & SCF_WHILEM_VISITED_POS)
3629 f |= SCF_WHILEM_VISITED_POS;
3630 next = regnext(scan);
3631 nscan = NEXTOPER(NEXTOPER(scan));
3633 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
3634 last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3637 FAIL("Variable length lookbehind not implemented");
3639 else if (*minnextp > (I32)U8_MAX) {
3640 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3642 scan->flags = (U8)*minnextp;
3647 if (f & SCF_DO_STCLASS_AND) {
3648 const int was = (data->start_class->flags & ANYOF_EOS);
3650 cl_and(data->start_class, &intrnl);
3652 data->start_class->flags |= ANYOF_EOS;
3655 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3657 if (data_fake.flags & SF_HAS_EVAL)
3658 data->flags |= SF_HAS_EVAL;
3659 data->whilem_c = data_fake.whilem_c;
3660 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3661 if (RExC_rx->minlen<*minnextp)
3662 RExC_rx->minlen=*minnextp;
3663 SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
3664 SvREFCNT_dec(data_fake.last_found);
3666 if ( data_fake.minlen_fixed != minlenp )
3668 data->offset_fixed= data_fake.offset_fixed;
3669 data->minlen_fixed= data_fake.minlen_fixed;
3670 data->lookbehind_fixed+= scan->flags;
3672 if ( data_fake.minlen_float != minlenp )
3674 data->minlen_float= data_fake.minlen_float;
3675 data->offset_float_min=data_fake.offset_float_min;
3676 data->offset_float_max=data_fake.offset_float_max;
3677 data->lookbehind_float+= scan->flags;
3686 else if (OP(scan) == OPEN) {
3687 if (stopparen != (I32)ARG(scan))
3690 else if (OP(scan) == CLOSE) {
3691 if (stopparen == (I32)ARG(scan)) {
3694 if ((I32)ARG(scan) == is_par) {
3695 next = regnext(scan);
3697 if ( next && (OP(next) != WHILEM) && next < last)
3698 is_par = 0; /* Disable optimization */
3701 *(data->last_closep) = ARG(scan);
3703 else if (OP(scan) == EVAL) {
3705 data->flags |= SF_HAS_EVAL;
3707 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3708 if (flags & SCF_DO_SUBSTR) {
3709 SCAN_COMMIT(pRExC_state,data,minlenp);
3710 flags &= ~SCF_DO_SUBSTR;
3712 if (data && OP(scan)==ACCEPT) {
3713 data->flags |= SCF_SEEN_ACCEPT;
3718 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3720 if (flags & SCF_DO_SUBSTR) {
3721 SCAN_COMMIT(pRExC_state,data,minlenp);
3722 data->longest = &(data->longest_float);
3724 is_inf = is_inf_internal = 1;
3725 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3726 cl_anything(pRExC_state, data->start_class);
3727 flags &= ~SCF_DO_STCLASS;
3729 else if (OP(scan) == GPOS) {
3730 if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
3731 !(delta || is_inf || (data && data->pos_delta)))
3733 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
3734 RExC_rx->extflags |= RXf_ANCH_GPOS;
3735 if (RExC_rx->gofs < (U32)min)
3736 RExC_rx->gofs = min;
3738 RExC_rx->extflags |= RXf_GPOS_FLOAT;
3742 #ifdef TRIE_STUDY_OPT
3743 #ifdef FULL_TRIE_STUDY
3744 else if (PL_regkind[OP(scan)] == TRIE) {
3745 /* NOTE - There is similar code to this block above for handling
3746 BRANCH nodes on the initial study. If you change stuff here
3748 regnode *trie_node= scan;
3749 regnode *tail= regnext(scan);
3750 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3751 I32 max1 = 0, min1 = I32_MAX;
3752 struct regnode_charclass_class accum;
3754 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3755 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3756 if (flags & SCF_DO_STCLASS)
3757 cl_init_zero(pRExC_state, &accum);
3763 const regnode *nextbranch= NULL;
3766 for ( word=1 ; word <= trie->wordcount ; word++)
3768 I32 deltanext=0, minnext=0, f = 0, fake;
3769 struct regnode_charclass_class this_class;
3771 data_fake.flags = 0;
3773 data_fake.whilem_c = data->whilem_c;
3774 data_fake.last_closep = data->last_closep;
3777 data_fake.last_closep = &fake;
3778 data_fake.pos_delta = delta;
3779 if (flags & SCF_DO_STCLASS) {
3780 cl_init(pRExC_state, &this_class);
3781 data_fake.start_class = &this_class;
3782 f = SCF_DO_STCLASS_AND;
3784 if (flags & SCF_WHILEM_VISITED_POS)
3785 f |= SCF_WHILEM_VISITED_POS;
3787 if (trie->jump[word]) {
3789 nextbranch = trie_node + trie->jump[0];
3790 scan= trie_node + trie->jump[word];
3791 /* We go from the jump point to the branch that follows
3792 it. Note this means we need the vestigal unused branches
3793 even though they arent otherwise used.
3795 minnext = study_chunk(pRExC_state, &scan, minlenp,
3796 &deltanext, (regnode *)nextbranch, &data_fake,
3797 stopparen, recursed, NULL, f,depth+1);
3799 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3800 nextbranch= regnext((regnode*)nextbranch);
3802 if (min1 > (I32)(minnext + trie->minlen))
3803 min1 = minnext + trie->minlen;
3804 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3805 max1 = minnext + deltanext + trie->maxlen;
3806 if (deltanext == I32_MAX)
3807 is_inf = is_inf_internal = 1;
3809 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3811 if (data_fake.flags & SCF_SEEN_ACCEPT) {
3812 if ( stopmin > min + min1)
3813 stopmin = min + min1;
3814 flags &= ~SCF_DO_SUBSTR;
3816 data->flags |= SCF_SEEN_ACCEPT;
3819 if (data_fake.flags & SF_HAS_EVAL)
3820 data->flags |= SF_HAS_EVAL;
3821 data->whilem_c = data_fake.whilem_c;
3823 if (flags & SCF_DO_STCLASS)
3824 cl_or(pRExC_state, &accum, &this_class);
3827 if (flags & SCF_DO_SUBSTR) {
3828 data->pos_min += min1;
3829 data->pos_delta += max1 - min1;
3830 if (max1 != min1 || is_inf)
3831 data->longest = &(data->longest_float);
3834 delta += max1 - min1;
3835 if (flags & SCF_DO_STCLASS_OR) {
3836 cl_or(pRExC_state, data->start_class, &accum);
3838 cl_and(data->start_class, and_withp);
3839 flags &= ~SCF_DO_STCLASS;
3842 else if (flags & SCF_DO_STCLASS_AND) {
3844 cl_and(data->start_class, &accum);
3845 flags &= ~SCF_DO_STCLASS;
3848 /* Switch to OR mode: cache the old value of
3849 * data->start_class */
3851 StructCopy(data->start_class, and_withp,
3852 struct regnode_charclass_class);
3853 flags &= ~SCF_DO_STCLASS_AND;
3854 StructCopy(&accum, data->start_class,
3855 struct regnode_charclass_class);
3856 flags |= SCF_DO_STCLASS_OR;
3857 data->start_class->flags |= ANYOF_EOS;
3864 else if (PL_regkind[OP(scan)] == TRIE) {
3865 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3868 min += trie->minlen;
3869 delta += (trie->maxlen - trie->minlen);
3870 flags &= ~SCF_DO_STCLASS; /* xxx */
3871 if (flags & SCF_DO_SUBSTR) {
3872 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3873 data->pos_min += trie->minlen;
3874 data->pos_delta += (trie->maxlen - trie->minlen);
3875 if (trie->maxlen != trie->minlen)
3876 data->longest = &(data->longest_float);
3878 if (trie->jump) /* no more substrings -- for now /grr*/
3879 flags &= ~SCF_DO_SUBSTR;
3881 #endif /* old or new */
3882 #endif /* TRIE_STUDY_OPT */
3883 /* Else: zero-length, ignore. */
3884 scan = regnext(scan);
3889 stopparen = frame->stop;
3890 frame = frame->prev;
3891 goto fake_study_recurse;
3896 DEBUG_STUDYDATA("pre-fin:",data,depth);
3899 *deltap = is_inf_internal ? I32_MAX : delta;
3900 if (flags & SCF_DO_SUBSTR && is_inf)
3901 data->pos_delta = I32_MAX - data->pos_min;
3902 if (is_par > (I32)U8_MAX)
3904 if (is_par && pars==1 && data) {
3905 data->flags |= SF_IN_PAR;
3906 data->flags &= ~SF_HAS_PAR;
3908 else if (pars && data) {
3909 data->flags |= SF_HAS_PAR;
3910 data->flags &= ~SF_IN_PAR;
3912 if (flags & SCF_DO_STCLASS_OR)
3913 cl_and(data->start_class, and_withp);
3914 if (flags & SCF_TRIE_RESTUDY)
3915 data->flags |= SCF_TRIE_RESTUDY;
3917 DEBUG_STUDYDATA("post-fin:",data,depth);
3919 return min < stopmin ? min : stopmin;
3923 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
3925 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
3927 Renewc(RExC_rxi->data,
3928 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
3929 char, struct reg_data);
3931 Renew(RExC_rxi->data->what, count + n, U8);
3933 Newx(RExC_rxi->data->what, n, U8);
3934 RExC_rxi->data->count = count + n;
3935 Copy(s, RExC_rxi->data->what + count, n, U8);
3939 /*XXX: todo make this not included in a non debugging perl */
3940 #ifndef PERL_IN_XSUB_RE
3942 Perl_reginitcolors(pTHX)
3945 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3947 char *t = savepv(s);
3951 t = strchr(t, '\t');
3957 PL_colors[i] = t = (char *)"";
3962 PL_colors[i++] = (char *)"";
3969 #ifdef TRIE_STUDY_OPT
3970 #define CHECK_RESTUDY_GOTO \
3972 (data.flags & SCF_TRIE_RESTUDY) \
3976 #define CHECK_RESTUDY_GOTO
3980 - pregcomp - compile a regular expression into internal code
3982 * We can't allocate space until we know how big the compiled form will be,
3983 * but we can't compile it (and thus know how big it is) until we've got a
3984 * place to put the code. So we cheat: we compile it twice, once with code
3985 * generation turned off and size counting turned on, and once "for real".
3986 * This also means that we don't allocate space until we are sure that the
3987 * thing really will compile successfully, and we never have to move the
3988 * code and thus invalidate pointers into it. (Note that it has to be in
3989 * one piece because free() must be able to free it all.) [NB: not true in perl]
3991 * Beware that the optimization-preparation code in here knows about some
3992 * of the structure of the compiled regexp. [I'll say.]
3997 #ifndef PERL_IN_XSUB_RE
3998 #define RE_ENGINE_PTR &PL_core_reg_engine
4000 extern const struct regexp_engine my_reg_engine;
4001 #define RE_ENGINE_PTR &my_reg_engine
4004 #ifndef PERL_IN_XSUB_RE
4006 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
4009 HV * const table = GvHV(PL_hintgv);
4010 /* Dispatch a request to compile a regexp to correct
4013 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
4014 GET_RE_DEBUG_FLAGS_DECL;
4015 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
4016 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
4018 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4021 return CALLREGCOMP_ENG(eng, exp, xend, pm);
4024 return Perl_re_compile(aTHX_ exp, xend, pm);
4029 Perl_re_compile(pTHX_ char *exp, char *xend, PMOP *pm)
4033 register regexp_internal *ri;
4041 RExC_state_t RExC_state;
4042 RExC_state_t * const pRExC_state = &RExC_state;
4043 #ifdef TRIE_STUDY_OPT
4045 RExC_state_t copyRExC_state;
4047 GET_RE_DEBUG_FLAGS_DECL;
4048 DEBUG_r(if (!PL_colorset) reginitcolors());
4051 FAIL("NULL regexp argument");
4053 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
4057 SV *dsv= sv_newmortal();
4058 RE_PV_QUOTED_DECL(s, RExC_utf8,
4059 dsv, RExC_precomp, (xend - exp), 60);
4060 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
4061 PL_colors[4],PL_colors[5],s);
4063 RExC_flags = pm->op_pmflags;
4067 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
4068 RExC_seen_evals = 0;
4071 /* First pass: determine size, legality. */
4079 RExC_emit = &PL_regdummy;
4080 RExC_whilem_seen = 0;
4081 RExC_charnames = NULL;
4082 RExC_open_parens = NULL;
4083 RExC_close_parens = NULL;
4085 RExC_paren_names = NULL;
4087 RExC_paren_name_list = NULL;
4089 RExC_recurse = NULL;
4090 RExC_recurse_count = 0;
4092 #if 0 /* REGC() is (currently) a NOP at the first pass.
4093 * Clever compilers notice this and complain. --jhi */
4094 REGC((U8)REG_MAGIC, (char*)RExC_emit);
4096 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4097 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4098 RExC_precomp = NULL;
4102 PerlIO_printf(Perl_debug_log,
4103 "Required size %"IVdf" nodes\n"
4104 "Starting second pass (creation)\n",
4107 RExC_lastparse=NULL;
4109 /* Small enough for pointer-storage convention?
4110 If extralen==0, this means that we will not need long jumps. */
4111 if (RExC_size >= 0x10000L && RExC_extralen)
4112 RExC_size += RExC_extralen;
4115 if (RExC_whilem_seen > 15)
4116 RExC_whilem_seen = 15;
4119 /* Make room for a sentinel value at the end of the program */
4123 /* Allocate space and zero-initialize. Note, the two step process
4124 of zeroing when in debug mode, thus anything assigned has to
4125 happen after that */
4126 Newxz(r, 1, regexp);
4127 Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
4128 char, regexp_internal);
4129 if ( r == NULL || ri == NULL )
4130 FAIL("Regexp out of space");
4132 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4133 Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
4135 /* bulk initialize base fields with 0. */
4136 Zero(ri, sizeof(regexp_internal), char);
4139 /* non-zero initialization begins here */
4141 r->engine= RE_ENGINE_PTR;
4143 r->prelen = xend - exp;
4144 r->extflags = pm->op_pmflags & RXf_PMf_COMPILETIME;
4146 bool has_k = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
4147 bool has_minus = ((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD);
4148 bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
4149 U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD) >> 12);
4150 const char *fptr = STD_PAT_MODS; /*"msix"*/
4152 r->wraplen = r->prelen + has_minus + has_k + has_runon
4153 + (sizeof(STD_PAT_MODS) - 1)
4154 + (sizeof("(?:)") - 1);
4156 Newx(r->wrapped, r->wraplen, char );
4160 *p++ = KEEPCOPY_PAT_MOD; /*'k'*/
4162 char *r = p + (sizeof(STD_PAT_MODS) - 1) + has_minus - 1;
4163 char *colon = r + 1;
4166 while((ch = *fptr++)) {
4180 Copy(RExC_precomp, p, r->prelen, char);
4189 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4191 if (RExC_seen & REG_SEEN_RECURSE) {
4192 Newxz(RExC_open_parens, RExC_npar,regnode *);
4193 SAVEFREEPV(RExC_open_parens);
4194 Newxz(RExC_close_parens,RExC_npar,regnode *);
4195 SAVEFREEPV(RExC_close_parens);
4198 /* Useful during FAIL. */
4199 #ifdef RE_TRACK_PATTERN_OFFSETS
4200 Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4201 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4202 "%s %"UVuf" bytes for offset annotations.\n",
4203 ri->u.offsets ? "Got" : "Couldn't get",
4204 (UV)((2*RExC_size+1) * sizeof(U32))));
4206 SetProgLen(ri,RExC_size);
4210 /* Second pass: emit code. */
4211 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
4216 RExC_emit_start = ri->program;
4217 RExC_emit = ri->program;
4219 /* put a sentinal on the end of the program so we can check for
4221 ri->program[RExC_size].type = 255;
4223 /* Store the count of eval-groups for security checks: */
4224 RExC_rx->seen_evals = RExC_seen_evals;
4225 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4226 if (reg(pRExC_state, 0, &flags,1) == NULL)
4229 /* XXXX To minimize changes to RE engine we always allocate
4230 3-units-long substrs field. */
4231 Newx(r->substrs, 1, struct reg_substr_data);
4232 if (RExC_recurse_count) {
4233 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4234 SAVEFREEPV(RExC_recurse);
4238 r->minlen = minlen = sawplus = sawopen = 0;
4239 Zero(r->substrs, 1, struct reg_substr_data);
4241 #ifdef TRIE_STUDY_OPT
4244 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4246 RExC_state = copyRExC_state;
4247 if (seen & REG_TOP_LEVEL_BRANCHES)
4248 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4250 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4251 if (data.last_found) {
4252 SvREFCNT_dec(data.longest_fixed);
4253 SvREFCNT_dec(data.longest_float);
4254 SvREFCNT_dec(data.last_found);
4256 StructCopy(&zero_scan_data, &data, scan_data_t);
4258 StructCopy(&zero_scan_data, &data, scan_data_t);
4259 copyRExC_state = RExC_state;
4262 StructCopy(&zero_scan_data, &data, scan_data_t);
4265 /* Dig out information for optimizations. */
4266 r->extflags = pm->op_pmflags & RXf_PMf_COMPILETIME; /* Again? */
4267 pm->op_pmflags = RExC_flags;
4269 r->extflags |= RXf_UTF8; /* Unicode in it? */
4270 ri->regstclass = NULL;
4271 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
4272 r->intflags |= PREGf_NAUGHTY;
4273 scan = ri->program + 1; /* First BRANCH. */
4275 /* testing for BRANCH here tells us whether there is "must appear"
4276 data in the pattern. If there is then we can use it for optimisations */
4277 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
4279 STRLEN longest_float_length, longest_fixed_length;
4280 struct regnode_charclass_class ch_class; /* pointed to by data */
4282 I32 last_close = 0; /* pointed to by data */
4285 /* Skip introductions and multiplicators >= 1. */
4286 while ((OP(first) == OPEN && (sawopen = 1)) ||
4287 /* An OR of *one* alternative - should not happen now. */
4288 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
4289 /* for now we can't handle lookbehind IFMATCH*/
4290 (OP(first) == IFMATCH && !first->flags) ||
4291 (OP(first) == PLUS) ||
4292 (OP(first) == MINMOD) ||
4293 /* An {n,m} with n>0 */
4294 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
4297 if (OP(first) == PLUS)
4300 first += regarglen[OP(first)];
4301 if (OP(first) == IFMATCH) {
4302 first = NEXTOPER(first);
4303 first += EXTRA_STEP_2ARGS;
4304 } else /* XXX possible optimisation for /(?=)/ */
4305 first = NEXTOPER(first);
4308 /* Starting-point info. */
4310 DEBUG_PEEP("first:",first,0);
4311 /* Ignore EXACT as we deal with it later. */
4312 if (PL_regkind[OP(first)] == EXACT) {
4313 if (OP(first) == EXACT)
4314 NOOP; /* Empty, get anchored substr later. */
4315 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4316 ri->regstclass = first;
4319 else if (PL_regkind[OP(first)] == TRIE &&
4320 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
4323 /* this can happen only on restudy */
4324 if ( OP(first) == TRIE ) {
4325 struct regnode_1 *trieop = (struct regnode_1 *)
4326 PerlMemShared_calloc(1, sizeof(struct regnode_1));
4327 StructCopy(first,trieop,struct regnode_1);
4328 trie_op=(regnode *)trieop;
4330 struct regnode_charclass *trieop = (struct regnode_charclass *)
4331 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
4332 StructCopy(first,trieop,struct regnode_charclass);
4333 trie_op=(regnode *)trieop;
4336 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4337 ri->regstclass = trie_op;
4340 else if (strchr((const char*)PL_simple,OP(first)))
4341 ri->regstclass = first;
4342 else if (PL_regkind[OP(first)] == BOUND ||
4343 PL_regkind[OP(first)] == NBOUND)
4344 ri->regstclass = first;
4345 else if (PL_regkind[OP(first)] == BOL) {
4346 r->extflags |= (OP(first) == MBOL
4348 : (OP(first) == SBOL
4351 first = NEXTOPER(first);
4354 else if (OP(first) == GPOS) {
4355 r->extflags |= RXf_ANCH_GPOS;
4356 first = NEXTOPER(first);
4359 else if ((!sawopen || !RExC_sawback) &&
4360 (OP(first) == STAR &&
4361 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4362 !(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
4364 /* turn .* into ^.* with an implied $*=1 */
4366 (OP(NEXTOPER(first)) == REG_ANY)
4369 r->extflags |= type;
4370 r->intflags |= PREGf_IMPLICIT;
4371 first = NEXTOPER(first);
4374 if (sawplus && (!sawopen || !RExC_sawback)
4375 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4376 /* x+ must match at the 1st pos of run of x's */
4377 r->intflags |= PREGf_SKIP;
4379 /* Scan is after the zeroth branch, first is atomic matcher. */
4380 #ifdef TRIE_STUDY_OPT
4383 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4384 (IV)(first - scan + 1))
4388 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4389 (IV)(first - scan + 1))
4395 * If there's something expensive in the r.e., find the
4396 * longest literal string that must appear and make it the
4397 * regmust. Resolve ties in favor of later strings, since
4398 * the regstart check works with the beginning of the r.e.
4399 * and avoiding duplication strengthens checking. Not a
4400 * strong reason, but sufficient in the absence of others.
4401 * [Now we resolve ties in favor of the earlier string if
4402 * it happens that c_offset_min has been invalidated, since the
4403 * earlier string may buy us something the later one won't.]
4406 data.longest_fixed = newSVpvs("");
4407 data.longest_float = newSVpvs("");
4408 data.last_found = newSVpvs("");
4409 data.longest = &(data.longest_fixed);
4411 if (!ri->regstclass) {
4412 cl_init(pRExC_state, &ch_class);
4413 data.start_class = &ch_class;
4414 stclass_flag = SCF_DO_STCLASS_AND;
4415 } else /* XXXX Check for BOUND? */
4417 data.last_closep = &last_close;
4419 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4420 &data, -1, NULL, NULL,
4421 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4427 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4428 && data.last_start_min == 0 && data.last_end > 0
4429 && !RExC_seen_zerolen
4430 && !(RExC_seen & REG_SEEN_VERBARG)
4431 && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
4432 r->extflags |= RXf_CHECK_ALL;
4433 scan_commit(pRExC_state, &data,&minlen,0);
4434 SvREFCNT_dec(data.last_found);
4436 /* Note that code very similar to this but for anchored string
4437 follows immediately below, changes may need to be made to both.
4440 longest_float_length = CHR_SVLEN(data.longest_float);
4441 if (longest_float_length
4442 || (data.flags & SF_FL_BEFORE_EOL
4443 && (!(data.flags & SF_FL_BEFORE_MEOL)
4444 || (RExC_flags & RXf_PMf_MULTILINE))))
4448 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4449 && data.offset_fixed == data.offset_float_min
4450 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4451 goto remove_float; /* As in (a)+. */
4453 /* copy the information about the longest float from the reg_scan_data
4454 over to the program. */
4455 if (SvUTF8(data.longest_float)) {
4456 r->float_utf8 = data.longest_float;
4457 r->float_substr = NULL;
4459 r->float_substr = data.longest_float;
4460 r->float_utf8 = NULL;
4462 /* float_end_shift is how many chars that must be matched that
4463 follow this item. We calculate it ahead of time as once the
4464 lookbehind offset is added in we lose the ability to correctly
4466 ml = data.minlen_float ? *(data.minlen_float)
4467 : (I32)longest_float_length;
4468 r->float_end_shift = ml - data.offset_float_min
4469 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4470 + data.lookbehind_float;
4471 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4472 r->float_max_offset = data.offset_float_max;
4473 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4474 r->float_max_offset -= data.lookbehind_float;
4476 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4477 && (!(data.flags & SF_FL_BEFORE_MEOL)
4478 || (RExC_flags & RXf_PMf_MULTILINE)));
4479 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4483 r->float_substr = r->float_utf8 = NULL;
4484 SvREFCNT_dec(data.longest_float);
4485 longest_float_length = 0;
4488 /* Note that code very similar to this but for floating string
4489 is immediately above, changes may need to be made to both.
4492 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4493 if (longest_fixed_length
4494 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4495 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4496 || (RExC_flags & RXf_PMf_MULTILINE))))
4500 /* copy the information about the longest fixed
4501 from the reg_scan_data over to the program. */
4502 if (SvUTF8(data.longest_fixed)) {
4503 r->anchored_utf8 = data.longest_fixed;
4504 r->anchored_substr = NULL;
4506 r->anchored_substr = data.longest_fixed;
4507 r->anchored_utf8 = NULL;
4509 /* fixed_end_shift is how many chars that must be matched that
4510 follow this item. We calculate it ahead of time as once the
4511 lookbehind offset is added in we lose the ability to correctly
4513 ml = data.minlen_fixed ? *(data.minlen_fixed)
4514 : (I32)longest_fixed_length;
4515 r->anchored_end_shift = ml - data.offset_fixed
4516 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4517 + data.lookbehind_fixed;
4518 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4520 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4521 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4522 || (RExC_flags & RXf_PMf_MULTILINE)));
4523 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4526 r->anchored_substr = r->anchored_utf8 = NULL;
4527 SvREFCNT_dec(data.longest_fixed);
4528 longest_fixed_length = 0;
4531 && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
4532 ri->regstclass = NULL;
4533 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4535 && !(data.start_class->flags & ANYOF_EOS)
4536 && !cl_is_anything(data.start_class))
4538 const U32 n = add_data(pRExC_state, 1, "f");
4540 Newx(RExC_rxi->data->data[n], 1,
4541 struct regnode_charclass_class);
4542 StructCopy(data.start_class,
4543 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4544 struct regnode_charclass_class);
4545 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4546 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4547 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4548 regprop(r, sv, (regnode*)data.start_class);
4549 PerlIO_printf(Perl_debug_log,
4550 "synthetic stclass \"%s\".\n",
4551 SvPVX_const(sv));});
4554 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4555 if (longest_fixed_length > longest_float_length) {
4556 r->check_end_shift = r->anchored_end_shift;
4557 r->check_substr = r->anchored_substr;
4558 r->check_utf8 = r->anchored_utf8;
4559 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4560 if (r->extflags & RXf_ANCH_SINGLE)
4561 r->extflags |= RXf_NOSCAN;
4564 r->check_end_shift = r->float_end_shift;
4565 r->check_substr = r->float_substr;
4566 r->check_utf8 = r->float_utf8;
4567 r->check_offset_min = r->float_min_offset;
4568 r->check_offset_max = r->float_max_offset;
4570 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4571 This should be changed ASAP! */
4572 if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
4573 r->extflags |= RXf_USE_INTUIT;
4574 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4575 r->extflags |= RXf_INTUIT_TAIL;
4577 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4578 if ( (STRLEN)minlen < longest_float_length )
4579 minlen= longest_float_length;
4580 if ( (STRLEN)minlen < longest_fixed_length )
4581 minlen= longest_fixed_length;
4585 /* Several toplevels. Best we can is to set minlen. */
4587 struct regnode_charclass_class ch_class;
4590 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4592 scan = ri->program + 1;
4593 cl_init(pRExC_state, &ch_class);
4594 data.start_class = &ch_class;
4595 data.last_closep = &last_close;
4598 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4599 &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4603 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4604 = r->float_substr = r->float_utf8 = NULL;
4605 if (!(data.start_class->flags & ANYOF_EOS)
4606 && !cl_is_anything(data.start_class))
4608 const U32 n = add_data(pRExC_state, 1, "f");
4610 Newx(RExC_rxi->data->data[n], 1,
4611 struct regnode_charclass_class);
4612 StructCopy(data.start_class,
4613 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4614 struct regnode_charclass_class);
4615 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4616 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4617 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4618 regprop(r, sv, (regnode*)data.start_class);
4619 PerlIO_printf(Perl_debug_log,
4620 "synthetic stclass \"%s\".\n",
4621 SvPVX_const(sv));});
4625 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4626 the "real" pattern. */
4628 PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4629 (IV)minlen, (IV)r->minlen);
4631 r->minlenret = minlen;
4632 if (r->minlen < minlen)
4635 if (RExC_seen & REG_SEEN_GPOS)
4636 r->extflags |= RXf_GPOS_SEEN;
4637 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4638 r->extflags |= RXf_LOOKBEHIND_SEEN;
4639 if (RExC_seen & REG_SEEN_EVAL)
4640 r->extflags |= RXf_EVAL_SEEN;
4641 if (RExC_seen & REG_SEEN_CANY)
4642 r->extflags |= RXf_CANY_SEEN;
4643 if (RExC_seen & REG_SEEN_VERBARG)
4644 r->intflags |= PREGf_VERBARG_SEEN;
4645 if (RExC_seen & REG_SEEN_CUTGROUP)
4646 r->intflags |= PREGf_CUTGROUP_SEEN;
4647 if (RExC_paren_names)
4648 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4650 r->paren_names = NULL;
4651 if (r->prelen == 3 && strEQ("\\s+", r->precomp))
4652 r->extflags |= RXf_WHITE;
4653 else if (r->prelen == 1 && r->precomp[0] == '^')
4654 r->extflags |= RXf_START_ONLY;
4657 if (RExC_paren_names) {
4658 ri->name_list_idx = add_data( pRExC_state, 1, "p" );
4659 ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
4662 ri->name_list_idx = 0;
4664 if (RExC_recurse_count) {
4665 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4666 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4667 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4670 Newxz(r->startp, RExC_npar, I32);
4671 Newxz(r->endp, RExC_npar, I32);
4672 /* assume we don't need to swap parens around before we match */
4675 PerlIO_printf(Perl_debug_log,"Final program:\n");
4678 #ifdef RE_TRACK_PATTERN_OFFSETS
4679 DEBUG_OFFSETS_r(if (ri->u.offsets) {
4680 const U32 len = ri->u.offsets[0];
4682 GET_RE_DEBUG_FLAGS_DECL;
4683 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
4684 for (i = 1; i <= len; i++) {
4685 if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
4686 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4687 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
4689 PerlIO_printf(Perl_debug_log, "\n");
4695 #undef RE_ENGINE_PTR
4699 Perl_reg_named_buff_get(pTHX_ const REGEXP * const rx, SV* namesv, U32 flags)
4701 AV *retarray = NULL;
4706 if (rx && rx->paren_names) {
4707 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4710 SV* sv_dat=HeVAL(he_str);
4711 I32 *nums=(I32*)SvPVX(sv_dat);
4712 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4713 if ((I32)(rx->lastparen) >= nums[i] &&
4714 rx->endp[nums[i]] != -1)
4716 ret = CALLREG_NUMBUF(rx,nums[i],NULL);
4720 ret = newSVsv(&PL_sv_undef);
4724 av_push(retarray, ret);
4728 return (SV*)retarray;
4735 Perl_reg_numbered_buff_get(pTHX_ const REGEXP * const rx, I32 paren, SV* usesv)
4740 SV *sv = usesv ? usesv : newSVpvs("");
4743 sv_setsv(sv,&PL_sv_undef);
4747 if (paren == -2 && rx->startp[0] != -1) {
4753 if (paren == -1 && rx->endp[0] != -1) {
4755 s = rx->subbeg + rx->endp[0];
4756 i = rx->sublen - rx->endp[0];
4759 if ( 0 <= paren && paren <= (I32)rx->nparens &&
4760 (s1 = rx->startp[paren]) != -1 &&
4761 (t1 = rx->endp[paren]) != -1)
4765 s = rx->subbeg + s1;
4767 sv_setsv(sv,&PL_sv_undef);
4770 assert(rx->sublen >= (s - rx->subbeg) + i );
4772 const int oldtainted = PL_tainted;
4774 sv_setpvn(sv, s, i);
4775 PL_tainted = oldtainted;
4776 if ( (rx->extflags & RXf_CANY_SEEN)
4777 ? (RX_MATCH_UTF8(rx)
4778 && (!i || is_utf8_string((U8*)s, i)))
4779 : (RX_MATCH_UTF8(rx)) )
4786 if (RX_MATCH_TAINTED(rx)) {
4787 if (SvTYPE(sv) >= SVt_PVMG) {
4788 MAGIC* const mg = SvMAGIC(sv);
4791 SvMAGIC_set(sv, mg->mg_moremagic);
4793 if ((mgt = SvMAGIC(sv))) {
4794 mg->mg_moremagic = mgt;
4795 SvMAGIC_set(sv, mg);
4805 sv_setsv(sv,&PL_sv_undef);
4811 /* Scans the name of a named buffer from the pattern.
4812 * If flags is REG_RSN_RETURN_NULL returns null.
4813 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
4814 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
4815 * to the parsed name as looked up in the RExC_paren_names hash.
4816 * If there is an error throws a vFAIL().. type exception.
4819 #define REG_RSN_RETURN_NULL 0
4820 #define REG_RSN_RETURN_NAME 1
4821 #define REG_RSN_RETURN_DATA 2
4824 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4825 char *name_start = RExC_parse;
4827 if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
4828 /* skip IDFIRST by using do...while */
4831 RExC_parse += UTF8SKIP(RExC_parse);
4832 } while (isALNUM_utf8((U8*)RExC_parse));
4836 } while (isALNUM(*RExC_parse));
4840 SV* sv_name = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4841 (int)(RExC_parse - name_start)));
4844 if ( flags == REG_RSN_RETURN_NAME)
4846 else if (flags==REG_RSN_RETURN_DATA) {
4849 if ( ! sv_name ) /* should not happen*/
4850 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
4851 if (RExC_paren_names)
4852 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
4854 sv_dat = HeVAL(he_str);
4856 vFAIL("Reference to nonexistent named group");
4860 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
4867 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4868 int rem=(int)(RExC_end - RExC_parse); \
4877 if (RExC_lastparse!=RExC_parse) \
4878 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4881 iscut ? "..." : "<" \
4884 PerlIO_printf(Perl_debug_log,"%16s",""); \
4889 num=REG_NODE_NUM(RExC_emit); \
4890 if (RExC_lastnum!=num) \
4891 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4893 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4894 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4895 (int)((depth*2)), "", \
4899 RExC_lastparse=RExC_parse; \
4904 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4905 DEBUG_PARSE_MSG((funcname)); \
4906 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4908 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4909 DEBUG_PARSE_MSG((funcname)); \
4910 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4913 - reg - regular expression, i.e. main body or parenthesized thing
4915 * Caller must absorb opening parenthesis.
4917 * Combining parenthesis handling with the base level of regular expression
4918 * is a trifle forced, but the need to tie the tails of the branches to what
4919 * follows makes it hard to avoid.
4921 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4923 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4925 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4928 /* this idea is borrowed from STR_WITH_LEN in handy.h */
4929 #define CHECK_WORD(s,v,l) \
4930 (((sizeof(s)-1)==(l)) && (strnEQ(start_verb, (s ""), (sizeof(s)-1))))
4933 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4934 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4937 register regnode *ret; /* Will be the head of the group. */
4938 register regnode *br;
4939 register regnode *lastbr;
4940 register regnode *ender = NULL;
4941 register I32 parno = 0;
4943 const I32 oregflags = RExC_flags;
4944 bool have_branch = 0;
4946 I32 freeze_paren = 0;
4947 I32 after_freeze = 0;
4949 /* for (?g), (?gc), and (?o) warnings; warning
4950 about (?c) will warn about (?g) -- japhy */
4952 #define WASTED_O 0x01
4953 #define WASTED_G 0x02
4954 #define WASTED_C 0x04
4955 #define WASTED_GC (0x02|0x04)
4956 I32 wastedflags = 0x00;
4958 char * parse_start = RExC_parse; /* MJD */
4959 char * const oregcomp_parse = RExC_parse;
4961 GET_RE_DEBUG_FLAGS_DECL;
4962 DEBUG_PARSE("reg ");
4965 *flagp = 0; /* Tentatively. */
4968 /* Make an OPEN node, if parenthesized. */
4970 if ( *RExC_parse == '*') { /* (*VERB:ARG) */
4971 char *start_verb = RExC_parse;
4972 STRLEN verb_len = 0;
4973 char *start_arg = NULL;
4974 unsigned char op = 0;
4976 int internal_argval = 0; /* internal_argval is only useful if !argok */
4977 while ( *RExC_parse && *RExC_parse != ')' ) {
4978 if ( *RExC_parse == ':' ) {
4979 start_arg = RExC_parse + 1;
4985 verb_len = RExC_parse - start_verb;
4988 while ( *RExC_parse && *RExC_parse != ')' )
4990 if ( *RExC_parse != ')' )
4991 vFAIL("Unterminated verb pattern argument");
4992 if ( RExC_parse == start_arg )
4995 if ( *RExC_parse != ')' )
4996 vFAIL("Unterminated verb pattern");
4999 switch ( *start_verb ) {
5000 case 'A': /* (*ACCEPT) */
5001 if ( CHECK_WORD("ACCEPT",start_verb,verb_len) ) {
5003 internal_argval = RExC_nestroot;
5006 case 'C': /* (*COMMIT) */
5007 if ( CHECK_WORD("COMMIT",start_verb,verb_len) )
5010 case 'F': /* (*FAIL) */
5011 if ( verb_len==1 || CHECK_WORD("FAIL",start_verb,verb_len) ) {
5016 case ':': /* (*:NAME) */
5017 case 'M': /* (*MARK:NAME) */
5018 if ( verb_len==0 || CHECK_WORD("MARK",start_verb,verb_len) ) {
5023 case 'P': /* (*PRUNE) */
5024 if ( CHECK_WORD("PRUNE",start_verb,verb_len) )
5027 case 'S': /* (*SKIP) */
5028 if ( CHECK_WORD("SKIP",start_verb,verb_len) )
5031 case 'T': /* (*THEN) */
5032 /* [19:06] <TimToady> :: is then */
5033 if ( CHECK_WORD("THEN",start_verb,verb_len) ) {
5035 RExC_seen |= REG_SEEN_CUTGROUP;
5041 vFAIL3("Unknown verb pattern '%.*s'",
5042 verb_len, start_verb);
5045 if ( start_arg && internal_argval ) {
5046 vFAIL3("Verb pattern '%.*s' may not have an argument",
5047 verb_len, start_verb);
5048 } else if ( argok < 0 && !start_arg ) {
5049 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
5050 verb_len, start_verb);
5052 ret = reganode(pRExC_state, op, internal_argval);
5053 if ( ! internal_argval && ! SIZE_ONLY ) {
5055 SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
5056 ARG(ret) = add_data( pRExC_state, 1, "S" );
5057 RExC_rxi->data->data[ARG(ret)]=(void*)sv;
5064 if (!internal_argval)
5065 RExC_seen |= REG_SEEN_VERBARG;
5066 } else if ( start_arg ) {
5067 vFAIL3("Verb pattern '%.*s' may not have an argument",
5068 verb_len, start_verb);
5070 ret = reg_node(pRExC_state, op);
5072 nextchar(pRExC_state);
5075 if (*RExC_parse == '?') { /* (?...) */
5076 bool is_logical = 0;
5077 const char * const seqstart = RExC_parse;
5080 paren = *RExC_parse++;
5081 ret = NULL; /* For look-ahead/behind. */
5084 case 'P': /* (?P...) variants for those used to PCRE/Python */
5085 paren = *RExC_parse++;
5086 if ( paren == '<') /* (?P<...>) named capture */
5088 else if (paren == '>') { /* (?P>name) named recursion */
5089 goto named_recursion;
5091 else if (paren == '=') { /* (?P=...) named backref */
5092 /* this pretty much dupes the code for \k<NAME> in regatom(), if
5093 you change this make sure you change that */
5094 char* name_start = RExC_parse;
5096 SV *sv_dat = reg_scan_name(pRExC_state,
5097 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5098 if (RExC_parse == name_start || *RExC_parse != ')')
5099 vFAIL2("Sequence %.3s... not terminated",parse_start);
5102 num = add_data( pRExC_state, 1, "S" );
5103 RExC_rxi->data->data[num]=(void*)sv_dat;
5104 SvREFCNT_inc(sv_dat);
5107 ret = reganode(pRExC_state,
5108 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5112 Set_Node_Offset(ret, parse_start+1);
5113 Set_Node_Cur_Length(ret); /* MJD */
5115 nextchar(pRExC_state);
5119 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5121 case '<': /* (?<...) */
5122 if (*RExC_parse == '!')
5124 else if (*RExC_parse != '=')
5130 case '\'': /* (?'...') */
5131 name_start= RExC_parse;
5132 svname = reg_scan_name(pRExC_state,
5133 SIZE_ONLY ? /* reverse test from the others */
5134 REG_RSN_RETURN_NAME :
5135 REG_RSN_RETURN_NULL);
5136 if (RExC_parse == name_start) {
5138 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5141 if (*RExC_parse != paren)
5142 vFAIL2("Sequence (?%c... not terminated",
5143 paren=='>' ? '<' : paren);
5147 if (!svname) /* shouldnt happen */
5149 "panic: reg_scan_name returned NULL");
5150 if (!RExC_paren_names) {
5151 RExC_paren_names= newHV();
5152 sv_2mortal((SV*)RExC_paren_names);
5154 RExC_paren_name_list= newAV();
5155 sv_2mortal((SV*)RExC_paren_name_list);
5158 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
5160 sv_dat = HeVAL(he_str);
5162 /* croak baby croak */
5164 "panic: paren_name hash element allocation failed");
5165 } else if ( SvPOK(sv_dat) ) {
5166 /* (?|...) can mean we have dupes so scan to check
5167 its already been stored. Maybe a flag indicating
5168 we are inside such a construct would be useful,
5169 but the arrays are likely to be quite small, so
5170 for now we punt -- dmq */
5171 IV count = SvIV(sv_dat);
5172 I32 *pv = (I32*)SvPVX(sv_dat);
5174 for ( i = 0 ; i < count ; i++ ) {
5175 if ( pv[i] == RExC_npar ) {
5181 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
5182 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
5183 pv[count] = RExC_npar;
5187 (void)SvUPGRADE(sv_dat,SVt_PVNV);
5188 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
5193 if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
5194 SvREFCNT_dec(svname);
5197 /*sv_dump(sv_dat);*/
5199 nextchar(pRExC_state);
5201 goto capturing_parens;
5203 RExC_seen |= REG_SEEN_LOOKBEHIND;
5205 case '=': /* (?=...) */
5206 case '!': /* (?!...) */
5207 RExC_seen_zerolen++;
5208 if (*RExC_parse == ')') {
5209 ret=reg_node(pRExC_state, OPFAIL);
5210 nextchar(pRExC_state);
5214 case '|': /* (?|...) */
5215 /* branch reset, behave like a (?:...) except that
5216 buffers in alternations share the same numbers */
5218 after_freeze = freeze_paren = RExC_npar;
5220 case ':': /* (?:...) */
5221 case '>': /* (?>...) */
5223 case '$': /* (?$...) */
5224 case '@': /* (?@...) */
5225 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
5227 case '#': /* (?#...) */
5228 while (*RExC_parse && *RExC_parse != ')')
5230 if (*RExC_parse != ')')
5231 FAIL("Sequence (?#... not terminated");
5232 nextchar(pRExC_state);
5235 case '0' : /* (?0) */
5236 case 'R' : /* (?R) */
5237 if (*RExC_parse != ')')
5238 FAIL("Sequence (?R) not terminated");
5239 ret = reg_node(pRExC_state, GOSTART);
5240 *flagp |= POSTPONED;
5241 nextchar(pRExC_state);
5244 { /* named and numeric backreferences */
5246 case '&': /* (?&NAME) */
5247 parse_start = RExC_parse - 1;
5250 SV *sv_dat = reg_scan_name(pRExC_state,
5251 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5252 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5254 goto gen_recurse_regop;
5257 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5259 vFAIL("Illegal pattern");
5261 goto parse_recursion;
5263 case '-': /* (?-1) */
5264 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5265 RExC_parse--; /* rewind to let it be handled later */
5269 case '1': case '2': case '3': case '4': /* (?1) */
5270 case '5': case '6': case '7': case '8': case '9':
5273 num = atoi(RExC_parse);
5274 parse_start = RExC_parse - 1; /* MJD */
5275 if (*RExC_parse == '-')
5277 while (isDIGIT(*RExC_parse))
5279 if (*RExC_parse!=')')
5280 vFAIL("Expecting close bracket");
5283 if ( paren == '-' ) {
5285 Diagram of capture buffer numbering.
5286 Top line is the normal capture buffer numbers
5287 Botton line is the negative indexing as from
5291 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5295 num = RExC_npar + num;
5298 vFAIL("Reference to nonexistent group");
5300 } else if ( paren == '+' ) {
5301 num = RExC_npar + num - 1;
5304 ret = reganode(pRExC_state, GOSUB, num);
5306 if (num > (I32)RExC_rx->nparens) {
5308 vFAIL("Reference to nonexistent group");
5310 ARG2L_SET( ret, RExC_recurse_count++);
5312 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5313 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5317 RExC_seen |= REG_SEEN_RECURSE;
5318 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5319 Set_Node_Offset(ret, parse_start); /* MJD */
5321 *flagp |= POSTPONED;
5322 nextchar(pRExC_state);
5324 } /* named and numeric backreferences */
5327 case 'p': /* (?p...) */
5328 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
5329 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
5331 case '?': /* (??...) */
5333 if (*RExC_parse != '{') {
5335 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5338 *flagp |= POSTPONED;
5339 paren = *RExC_parse++;
5341 case '{': /* (?{...}) */
5346 char *s = RExC_parse;
5348 RExC_seen_zerolen++;
5349 RExC_seen |= REG_SEEN_EVAL;
5350 while (count && (c = *RExC_parse)) {
5361 if (*RExC_parse != ')') {
5363 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5367 OP_4tree *sop, *rop;
5368 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5371 Perl_save_re_context(aTHX);
5372 rop = sv_compile_2op(sv, &sop, "re", &pad);
5373 sop->op_private |= OPpREFCOUNTED;
5374 /* re_dup will OpREFCNT_inc */
5375 OpREFCNT_set(sop, 1);
5378 n = add_data(pRExC_state, 3, "nop");
5379 RExC_rxi->data->data[n] = (void*)rop;
5380 RExC_rxi->data->data[n+1] = (void*)sop;
5381 RExC_rxi->data->data[n+2] = (void*)pad;
5384 else { /* First pass */
5385 if (PL_reginterp_cnt < ++RExC_seen_evals
5387 /* No compiled RE interpolated, has runtime
5388 components ===> unsafe. */
5389 FAIL("Eval-group not allowed at runtime, use re 'eval'");
5390 if (PL_tainting && PL_tainted)
5391 FAIL("Eval-group in insecure regular expression");
5392 #if PERL_VERSION > 8
5393 if (IN_PERL_COMPILETIME)
5398 nextchar(pRExC_state);
5400 ret = reg_node(pRExC_state, LOGICAL);
5403 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5404 /* deal with the length of this later - MJD */
5407 ret = reganode(pRExC_state, EVAL, n);
5408 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5409 Set_Node_Offset(ret, parse_start);
5412 case '(': /* (?(?{...})...) and (?(?=...)...) */
5415 if (RExC_parse[0] == '?') { /* (?(?...)) */
5416 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
5417 || RExC_parse[1] == '<'
5418 || RExC_parse[1] == '{') { /* Lookahead or eval. */
5421 ret = reg_node(pRExC_state, LOGICAL);
5424 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
5428 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
5429 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
5431 char ch = RExC_parse[0] == '<' ? '>' : '\'';
5432 char *name_start= RExC_parse++;
5434 SV *sv_dat=reg_scan_name(pRExC_state,
5435 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5436 if (RExC_parse == name_start || *RExC_parse != ch)
5437 vFAIL2("Sequence (?(%c... not terminated",
5438 (ch == '>' ? '<' : ch));
5441 num = add_data( pRExC_state, 1, "S" );
5442 RExC_rxi->data->data[num]=(void*)sv_dat;
5443 SvREFCNT_inc(sv_dat);
5445 ret = reganode(pRExC_state,NGROUPP,num);
5446 goto insert_if_check_paren;
5448 else if (RExC_parse[0] == 'D' &&
5449 RExC_parse[1] == 'E' &&
5450 RExC_parse[2] == 'F' &&
5451 RExC_parse[3] == 'I' &&
5452 RExC_parse[4] == 'N' &&
5453 RExC_parse[5] == 'E')
5455 ret = reganode(pRExC_state,DEFINEP,0);
5458 goto insert_if_check_paren;
5460 else if (RExC_parse[0] == 'R') {
5463 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5464 parno = atoi(RExC_parse++);
5465 while (isDIGIT(*RExC_parse))
5467 } else if (RExC_parse[0] == '&') {
5470 sv_dat = reg_scan_name(pRExC_state,
5471 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5472 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5474 ret = reganode(pRExC_state,INSUBP,parno);
5475 goto insert_if_check_paren;
5477 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5480 parno = atoi(RExC_parse++);
5482 while (isDIGIT(*RExC_parse))
5484 ret = reganode(pRExC_state, GROUPP, parno);
5486 insert_if_check_paren:
5487 if ((c = *nextchar(pRExC_state)) != ')')
5488 vFAIL("Switch condition not recognized");
5490 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
5491 br = regbranch(pRExC_state, &flags, 1,depth+1);
5493 br = reganode(pRExC_state, LONGJMP, 0);
5495 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
5496 c = *nextchar(pRExC_state);
5501 vFAIL("(?(DEFINE)....) does not allow branches");
5502 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
5503 regbranch(pRExC_state, &flags, 1,depth+1);
5504 REGTAIL(pRExC_state, ret, lastbr);
5507 c = *nextchar(pRExC_state);
5512 vFAIL("Switch (?(condition)... contains too many branches");
5513 ender = reg_node(pRExC_state, TAIL);
5514 REGTAIL(pRExC_state, br, ender);
5516 REGTAIL(pRExC_state, lastbr, ender);
5517 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
5520 REGTAIL(pRExC_state, ret, ender);
5524 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
5528 RExC_parse--; /* for vFAIL to print correctly */
5529 vFAIL("Sequence (? incomplete");
5533 parse_flags: /* (?i) */
5535 U32 posflags = 0, negflags = 0;
5536 U32 *flagsp = &posflags;
5538 while (*RExC_parse) {
5539 /* && strchr("iogcmsx", *RExC_parse) */
5540 /* (?g), (?gc) and (?o) are useless here
5541 and must be globally applied -- japhy */
5542 switch (*RExC_parse) {
5543 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
5546 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5547 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
5548 if (! (wastedflags & wflagbit) ) {
5549 wastedflags |= wflagbit;
5552 "Useless (%s%c) - %suse /%c modifier",
5553 flagsp == &negflags ? "?-" : "?",
5555 flagsp == &negflags ? "don't " : "",
5563 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5564 if (! (wastedflags & WASTED_C) ) {
5565 wastedflags |= WASTED_GC;
5568 "Useless (%sc) - %suse /gc modifier",
5569 flagsp == &negflags ? "?-" : "?",
5570 flagsp == &negflags ? "don't " : ""
5576 if (flagsp == &negflags) {
5577 if (SIZE_ONLY && ckWARN(WARN_REGEXP))
5578 vWARN(RExC_parse + 1,"Useless use of (?-k)");
5580 *flagsp |= RXf_PMf_KEEPCOPY;
5584 if (flagsp == &negflags) {
5586 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5590 wastedflags = 0; /* reset so (?g-c) warns twice */
5596 RExC_flags |= posflags;
5597 RExC_flags &= ~negflags;
5598 nextchar(pRExC_state);
5609 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5614 }} /* one for the default block, one for the switch */
5621 ret = reganode(pRExC_state, OPEN, parno);
5624 RExC_nestroot = parno;
5625 if (RExC_seen & REG_SEEN_RECURSE
5626 && !RExC_open_parens[parno-1])
5628 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5629 "Setting open paren #%"IVdf" to %d\n",
5630 (IV)parno, REG_NODE_NUM(ret)));
5631 RExC_open_parens[parno-1]= ret;
5634 Set_Node_Length(ret, 1); /* MJD */
5635 Set_Node_Offset(ret, RExC_parse); /* MJD */
5643 /* Pick up the branches, linking them together. */
5644 parse_start = RExC_parse; /* MJD */
5645 br = regbranch(pRExC_state, &flags, 1,depth+1);
5646 /* branch_len = (paren != 0); */
5650 if (*RExC_parse == '|') {
5651 if (!SIZE_ONLY && RExC_extralen) {
5652 reginsert(pRExC_state, BRANCHJ, br, depth+1);
5655 reginsert(pRExC_state, BRANCH, br, depth+1);
5656 Set_Node_Length(br, paren != 0);
5657 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
5661 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
5663 else if (paren == ':') {
5664 *flagp |= flags&SIMPLE;
5666 if (is_open) { /* Starts with OPEN. */
5667 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
5669 else if (paren != '?') /* Not Conditional */
5671 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
5673 while (*RExC_parse == '|') {
5674 if (!SIZE_ONLY && RExC_extralen) {
5675 ender = reganode(pRExC_state, LONGJMP,0);
5676 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
5679 RExC_extralen += 2; /* Account for LONGJMP. */
5680 nextchar(pRExC_state);
5682 if (RExC_npar > after_freeze)
5683 after_freeze = RExC_npar;
5684 RExC_npar = freeze_paren;
5686 br = regbranch(pRExC_state, &flags, 0, depth+1);
5690 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
5692 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
5695 if (have_branch || paren != ':') {
5696 /* Make a closing node, and hook it on the end. */
5699 ender = reg_node(pRExC_state, TAIL);
5702 ender = reganode(pRExC_state, CLOSE, parno);
5703 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
5704 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5705 "Setting close paren #%"IVdf" to %d\n",
5706 (IV)parno, REG_NODE_NUM(ender)));
5707 RExC_close_parens[parno-1]= ender;
5708 if (RExC_nestroot == parno)
5711 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
5712 Set_Node_Length(ender,1); /* MJD */
5718 *flagp &= ~HASWIDTH;
5721 ender = reg_node(pRExC_state, SUCCEED);
5724 ender = reg_node(pRExC_state, END);
5726 assert(!RExC_opend); /* there can only be one! */
5731 REGTAIL(pRExC_state, lastbr, ender);
5733 if (have_branch && !SIZE_ONLY) {
5735 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5737 /* Hook the tails of the branches to the closing node. */
5738 for (br = ret; br; br = regnext(br)) {
5739 const U8 op = PL_regkind[OP(br)];
5741 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
5743 else if (op == BRANCHJ) {
5744 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
5752 static const char parens[] = "=!<,>";
5754 if (paren && (p = strchr(parens, paren))) {
5755 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
5756 int flag = (p - parens) > 1;
5759 node = SUSPEND, flag = 0;
5760 reginsert(pRExC_state, node,ret, depth+1);
5761 Set_Node_Cur_Length(ret);
5762 Set_Node_Offset(ret, parse_start + 1);
5764 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
5768 /* Check for proper termination. */
5770 RExC_flags = oregflags;
5771 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
5772 RExC_parse = oregcomp_parse;
5773 vFAIL("Unmatched (");
5776 else if (!paren && RExC_parse < RExC_end) {
5777 if (*RExC_parse == ')') {
5779 vFAIL("Unmatched )");
5782 FAIL("Junk on end of regexp"); /* "Can't happen". */
5786 RExC_npar = after_freeze;
5791 - regbranch - one alternative of an | operator
5793 * Implements the concatenation operator.
5796 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
5799 register regnode *ret;
5800 register regnode *chain = NULL;
5801 register regnode *latest;
5802 I32 flags = 0, c = 0;
5803 GET_RE_DEBUG_FLAGS_DECL;
5804 DEBUG_PARSE("brnc");
5808 if (!SIZE_ONLY && RExC_extralen)
5809 ret = reganode(pRExC_state, BRANCHJ,0);
5811 ret = reg_node(pRExC_state, BRANCH);
5812 Set_Node_Length(ret, 1);
5816 if (!first && SIZE_ONLY)
5817 RExC_extralen += 1; /* BRANCHJ */
5819 *flagp = WORST; /* Tentatively. */
5822 nextchar(pRExC_state);
5823 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
5825 latest = regpiece(pRExC_state, &flags,depth+1);
5826 if (latest == NULL) {
5827 if (flags & TRYAGAIN)
5831 else if (ret == NULL)
5833 *flagp |= flags&(HASWIDTH|POSTPONED);
5834 if (chain == NULL) /* First piece. */
5835 *flagp |= flags&SPSTART;
5838 REGTAIL(pRExC_state, chain, latest);
5843 if (chain == NULL) { /* Loop ran zero times. */
5844 chain = reg_node(pRExC_state, NOTHING);
5849 *flagp |= flags&SIMPLE;
5856 - regpiece - something followed by possible [*+?]
5858 * Note that the branching code sequences used for ? and the general cases
5859 * of * and + are somewhat optimized: they use the same NOTHING node as
5860 * both the endmarker for their branch list and the body of the last branch.
5861 * It might seem that this node could be dispensed with entirely, but the
5862 * endmarker role is not redundant.
5865 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5868 register regnode *ret;
5870 register char *next;
5872 const char * const origparse = RExC_parse;
5874 I32 max = REG_INFTY;
5876 const char *maxpos = NULL;
5877 GET_RE_DEBUG_FLAGS_DECL;
5878 DEBUG_PARSE("piec");
5880 ret = regatom(pRExC_state, &flags,depth+1);
5882 if (flags & TRYAGAIN)
5889 if (op == '{' && regcurly(RExC_parse)) {
5891 parse_start = RExC_parse; /* MJD */
5892 next = RExC_parse + 1;
5893 while (isDIGIT(*next) || *next == ',') {
5902 if (*next == '}') { /* got one */
5906 min = atoi(RExC_parse);
5910 maxpos = RExC_parse;
5912 if (!max && *maxpos != '0')
5913 max = REG_INFTY; /* meaning "infinity" */
5914 else if (max >= REG_INFTY)
5915 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5917 nextchar(pRExC_state);
5920 if ((flags&SIMPLE)) {
5921 RExC_naughty += 2 + RExC_naughty / 2;
5922 reginsert(pRExC_state, CURLY, ret, depth+1);
5923 Set_Node_Offset(ret, parse_start+1); /* MJD */
5924 Set_Node_Cur_Length(ret);
5927 regnode * const w = reg_node(pRExC_state, WHILEM);
5930 REGTAIL(pRExC_state, ret, w);
5931 if (!SIZE_ONLY && RExC_extralen) {
5932 reginsert(pRExC_state, LONGJMP,ret, depth+1);
5933 reginsert(pRExC_state, NOTHING,ret, depth+1);
5934 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
5936 reginsert(pRExC_state, CURLYX,ret, depth+1);
5938 Set_Node_Offset(ret, parse_start+1);
5939 Set_Node_Length(ret,
5940 op == '{' ? (RExC_parse - parse_start) : 1);
5942 if (!SIZE_ONLY && RExC_extralen)
5943 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
5944 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5946 RExC_whilem_seen++, RExC_extralen += 3;
5947 RExC_naughty += 4 + RExC_naughty; /* compound interest */
5955 if (max && max < min)
5956 vFAIL("Can't do {n,m} with n > m");
5958 ARG1_SET(ret, (U16)min);
5959 ARG2_SET(ret, (U16)max);
5971 #if 0 /* Now runtime fix should be reliable. */
5973 /* if this is reinstated, don't forget to put this back into perldiag:
5975 =item Regexp *+ operand could be empty at {#} in regex m/%s/
5977 (F) The part of the regexp subject to either the * or + quantifier
5978 could match an empty string. The {#} shows in the regular
5979 expression about where the problem was discovered.
5983 if (!(flags&HASWIDTH) && op != '?')
5984 vFAIL("Regexp *+ operand could be empty");
5987 parse_start = RExC_parse;
5988 nextchar(pRExC_state);
5990 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5992 if (op == '*' && (flags&SIMPLE)) {
5993 reginsert(pRExC_state, STAR, ret, depth+1);
5997 else if (op == '*') {
6001 else if (op == '+' && (flags&SIMPLE)) {
6002 reginsert(pRExC_state, PLUS, ret, depth+1);
6006 else if (op == '+') {
6010 else if (op == '?') {
6015 if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
6017 "%.*s matches null string many times",
6018 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
6022 if (RExC_parse < RExC_end && *RExC_parse == '?') {
6023 nextchar(pRExC_state);
6024 reginsert(pRExC_state, MINMOD, ret, depth+1);
6025 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
6027 #ifndef REG_ALLOW_MINMOD_SUSPEND
6030 if (RExC_parse < RExC_end && *RExC_parse == '+') {
6032 nextchar(pRExC_state);
6033 ender = reg_node(pRExC_state, SUCCEED);
6034 REGTAIL(pRExC_state, ret, ender);
6035 reginsert(pRExC_state, SUSPEND, ret, depth+1);
6037 ender = reg_node(pRExC_state, TAIL);
6038 REGTAIL(pRExC_state, ret, ender);
6042 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
6044 vFAIL("Nested quantifiers");
6051 /* reg_namedseq(pRExC_state,UVp)
6053 This is expected to be called by a parser routine that has
6054 recognized'\N' and needs to handle the rest. RExC_parse is
6055 expected to point at the first char following the N at the time
6058 If valuep is non-null then it is assumed that we are parsing inside
6059 of a charclass definition and the first codepoint in the resolved
6060 string is returned via *valuep and the routine will return NULL.
6061 In this mode if a multichar string is returned from the charnames
6062 handler a warning will be issued, and only the first char in the
6063 sequence will be examined. If the string returned is zero length
6064 then the value of *valuep is undefined and NON-NULL will
6065 be returned to indicate failure. (This will NOT be a valid pointer
6068 If value is null then it is assumed that we are parsing normal text
6069 and inserts a new EXACT node into the program containing the resolved
6070 string and returns a pointer to the new node. If the string is
6071 zerolength a NOTHING node is emitted.
6073 On success RExC_parse is set to the char following the endbrace.
6074 Parsing failures will generate a fatal errorvia vFAIL(...)
6076 NOTE: We cache all results from the charnames handler locally in
6077 the RExC_charnames hash (created on first use) to prevent a charnames
6078 handler from playing silly-buggers and returning a short string and
6079 then a long string for a given pattern. Since the regexp program
6080 size is calculated during an initial parse this would result
6081 in a buffer overrun so we cache to prevent the charname result from
6082 changing during the course of the parse.
6086 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
6088 char * name; /* start of the content of the name */
6089 char * endbrace; /* endbrace following the name */
6092 STRLEN len; /* this has various purposes throughout the code */
6093 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
6094 regnode *ret = NULL;
6096 if (*RExC_parse != '{') {
6097 vFAIL("Missing braces on \\N{}");
6099 name = RExC_parse+1;
6100 endbrace = strchr(RExC_parse, '}');
6103 vFAIL("Missing right brace on \\N{}");
6105 RExC_parse = endbrace + 1;
6108 /* RExC_parse points at the beginning brace,
6109 endbrace points at the last */
6110 if ( name[0]=='U' && name[1]=='+' ) {
6111 /* its a "unicode hex" notation {U+89AB} */
6112 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
6113 | PERL_SCAN_DISALLOW_PREFIX
6114 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6116 len = (STRLEN)(endbrace - name - 2);
6117 cp = grok_hex(name + 2, &len, &fl, NULL);
6118 if ( len != (STRLEN)(endbrace - name - 2) ) {
6127 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
6129 /* fetch the charnames handler for this scope */
6130 HV * const table = GvHV(PL_hintgv);
6132 hv_fetchs(table, "charnames", FALSE) :
6134 SV *cv= cvp ? *cvp : NULL;
6137 /* create an SV with the name as argument */
6138 sv_name = newSVpvn(name, endbrace - name);
6140 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
6141 vFAIL2("Constant(\\N{%s}) unknown: "
6142 "(possibly a missing \"use charnames ...\")",
6145 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
6146 vFAIL2("Constant(\\N{%s}): "
6147 "$^H{charnames} is not defined",SvPVX(sv_name));
6152 if (!RExC_charnames) {
6153 /* make sure our cache is allocated */
6154 RExC_charnames = newHV();
6155 sv_2mortal((SV*)RExC_charnames);
6157 /* see if we have looked this one up before */
6158 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
6160 sv_str = HeVAL(he_str);
6173 count= call_sv(cv, G_SCALAR);
6175 if (count == 1) { /* XXXX is this right? dmq */
6177 SvREFCNT_inc_simple_void(sv_str);
6185 if ( !sv_str || !SvOK(sv_str) ) {
6186 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
6187 "did not return a defined value",SvPVX(sv_name));
6189 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
6194 char *p = SvPV(sv_str, len);
6197 if ( SvUTF8(sv_str) ) {
6198 *valuep = utf8_to_uvchr((U8*)p, &numlen);
6202 We have to turn on utf8 for high bit chars otherwise
6203 we get failures with
6205 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
6206 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
6208 This is different from what \x{} would do with the same
6209 codepoint, where the condition is > 0xFF.
6216 /* warn if we havent used the whole string? */
6218 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6220 "Ignoring excess chars from \\N{%s} in character class",
6224 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6226 "Ignoring zero length \\N{%s} in character class",
6231 SvREFCNT_dec(sv_name);
6233 SvREFCNT_dec(sv_str);
6234 return len ? NULL : (regnode *)&len;
6235 } else if(SvCUR(sv_str)) {
6241 char * parse_start = name-3; /* needed for the offsets */
6243 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
6245 ret = reg_node(pRExC_state,
6246 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6249 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
6250 sv_utf8_upgrade(sv_str);
6251 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
6255 p = SvPV(sv_str, len);
6257 /* len is the length written, charlen is the size the char read */
6258 for ( len = 0; p < pend; p += charlen ) {
6260 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
6262 STRLEN foldlen,numlen;
6263 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6264 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
6265 /* Emit all the Unicode characters. */
6267 for (foldbuf = tmpbuf;
6271 uvc = utf8_to_uvchr(foldbuf, &numlen);
6273 const STRLEN unilen = reguni(pRExC_state, uvc, s);
6276 /* In EBCDIC the numlen
6277 * and unilen can differ. */
6279 if (numlen >= foldlen)
6283 break; /* "Can't happen." */
6286 const STRLEN unilen = reguni(pRExC_state, uvc, s);
6298 RExC_size += STR_SZ(len);
6301 RExC_emit += STR_SZ(len);
6303 Set_Node_Cur_Length(ret); /* MJD */
6305 nextchar(pRExC_state);
6307 ret = reg_node(pRExC_state,NOTHING);
6310 SvREFCNT_dec(sv_str);
6313 SvREFCNT_dec(sv_name);
6323 * It returns the code point in utf8 for the value in *encp.
6324 * value: a code value in the source encoding
6325 * encp: a pointer to an Encode object
6327 * If the result from Encode is not a single character,
6328 * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6331 S_reg_recode(pTHX_ const char value, SV **encp)
6334 SV * const sv = sv_2mortal(newSVpvn(&value, numlen));
6335 const char * const s = encp && *encp ? sv_recode_to_utf8(sv, *encp)
6337 const STRLEN newlen = SvCUR(sv);
6338 UV uv = UNICODE_REPLACEMENT;
6342 ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6345 if (!newlen || numlen != newlen) {
6346 uv = UNICODE_REPLACEMENT;
6355 - regatom - the lowest level
6357 Try to identify anything special at the start of the pattern. If there
6358 is, then handle it as required. This may involve generating a single regop,
6359 such as for an assertion; or it may involve recursing, such as to
6360 handle a () structure.
6362 If the string doesn't start with something special then we gobble up
6363 as much literal text as we can.
6365 Once we have been able to handle whatever type of thing started the
6366 sequence, we return.
6368 Note: we have to be careful with escapes, as they can be both literal
6369 and special, and in the case of \10 and friends can either, depending
6370 on context. Specifically there are two seperate switches for handling
6371 escape sequences, with the one for handling literal escapes requiring
6372 a dummy entry for all of the special escapes that are actually handled
6377 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6380 register regnode *ret = NULL;
6382 char *parse_start = RExC_parse;
6383 GET_RE_DEBUG_FLAGS_DECL;
6384 DEBUG_PARSE("atom");
6385 *flagp = WORST; /* Tentatively. */
6389 switch (*RExC_parse) {
6391 RExC_seen_zerolen++;
6392 nextchar(pRExC_state);
6393 if (RExC_flags & RXf_PMf_MULTILINE)
6394 ret = reg_node(pRExC_state, MBOL);
6395 else if (RExC_flags & RXf_PMf_SINGLELINE)
6396 ret = reg_node(pRExC_state, SBOL);
6398 ret = reg_node(pRExC_state, BOL);
6399 Set_Node_Length(ret, 1); /* MJD */
6402 nextchar(pRExC_state);
6404 RExC_seen_zerolen++;
6405 if (RExC_flags & RXf_PMf_MULTILINE)
6406 ret = reg_node(pRExC_state, MEOL);
6407 else if (RExC_flags & RXf_PMf_SINGLELINE)
6408 ret = reg_node(pRExC_state, SEOL);
6410 ret = reg_node(pRExC_state, EOL);
6411 Set_Node_Length(ret, 1); /* MJD */
6414 nextchar(pRExC_state);
6415 if (RExC_flags & RXf_PMf_SINGLELINE)
6416 ret = reg_node(pRExC_state, SANY);
6418 ret = reg_node(pRExC_state, REG_ANY);
6419 *flagp |= HASWIDTH|SIMPLE;
6421 Set_Node_Length(ret, 1); /* MJD */
6425 char * const oregcomp_parse = ++RExC_parse;
6426 ret = regclass(pRExC_state,depth+1);
6427 if (*RExC_parse != ']') {
6428 RExC_parse = oregcomp_parse;
6429 vFAIL("Unmatched [");
6431 nextchar(pRExC_state);
6432 *flagp |= HASWIDTH|SIMPLE;
6433 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
6437 nextchar(pRExC_state);
6438 ret = reg(pRExC_state, 1, &flags,depth+1);
6440 if (flags & TRYAGAIN) {
6441 if (RExC_parse == RExC_end) {
6442 /* Make parent create an empty node if needed. */
6450 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
6454 if (flags & TRYAGAIN) {
6458 vFAIL("Internal urp");
6459 /* Supposed to be caught earlier. */
6462 if (!regcurly(RExC_parse)) {
6471 vFAIL("Quantifier follows nothing");
6476 This switch handles escape sequences that resolve to some kind
6477 of special regop and not to literal text. Escape sequnces that
6478 resolve to literal text are handled below in the switch marked
6481 Every entry in this switch *must* have a corresponding entry
6482 in the literal escape switch. However, the opposite is not
6483 required, as the default for this switch is to jump to the
6484 literal text handling code.
6486 switch (*++RExC_parse) {
6487 /* Special Escapes */
6489 RExC_seen_zerolen++;
6490 ret = reg_node(pRExC_state, SBOL);
6492 goto finish_meta_pat;
6494 ret = reg_node(pRExC_state, GPOS);
6495 RExC_seen |= REG_SEEN_GPOS;
6497 goto finish_meta_pat;
6499 RExC_seen_zerolen++;
6500 ret = reg_node(pRExC_state, KEEPS);
6502 goto finish_meta_pat;
6504 ret = reg_node(pRExC_state, SEOL);
6506 RExC_seen_zerolen++; /* Do not optimize RE away */
6507 goto finish_meta_pat;
6509 ret = reg_node(pRExC_state, EOS);
6511 RExC_seen_zerolen++; /* Do not optimize RE away */
6512 goto finish_meta_pat;
6514 ret = reg_node(pRExC_state, CANY);
6515 RExC_seen |= REG_SEEN_CANY;
6516 *flagp |= HASWIDTH|SIMPLE;
6517 goto finish_meta_pat;
6519 ret = reg_node(pRExC_state, CLUMP);
6521 goto finish_meta_pat;
6523 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
6524 *flagp |= HASWIDTH|SIMPLE;
6525 goto finish_meta_pat;
6527 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
6528 *flagp |= HASWIDTH|SIMPLE;
6529 goto finish_meta_pat;
6531 RExC_seen_zerolen++;
6532 RExC_seen |= REG_SEEN_LOOKBEHIND;
6533 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
6535 goto finish_meta_pat;
6537 RExC_seen_zerolen++;
6538 RExC_seen |= REG_SEEN_LOOKBEHIND;
6539 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
6541 goto finish_meta_pat;
6543 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
6544 *flagp |= HASWIDTH|SIMPLE;
6545 goto finish_meta_pat;
6547 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
6548 *flagp |= HASWIDTH|SIMPLE;
6549 goto finish_meta_pat;
6551 ret = reg_node(pRExC_state, DIGIT);
6552 *flagp |= HASWIDTH|SIMPLE;
6553 goto finish_meta_pat;
6555 ret = reg_node(pRExC_state, NDIGIT);
6556 *flagp |= HASWIDTH|SIMPLE;
6557 goto finish_meta_pat;
6559 ret = reganode(pRExC_state, PRUNE, 0);
6562 goto finish_meta_pat;
6564 ret = reganode(pRExC_state, SKIP, 0);
6568 nextchar(pRExC_state);
6569 Set_Node_Length(ret, 2); /* MJD */
6574 char* const oldregxend = RExC_end;
6576 char* parse_start = RExC_parse - 2;
6579 if (RExC_parse[1] == '{') {
6580 /* a lovely hack--pretend we saw [\pX] instead */
6581 RExC_end = strchr(RExC_parse, '}');
6583 const U8 c = (U8)*RExC_parse;
6585 RExC_end = oldregxend;
6586 vFAIL2("Missing right brace on \\%c{}", c);
6591 RExC_end = RExC_parse + 2;
6592 if (RExC_end > oldregxend)
6593 RExC_end = oldregxend;
6597 ret = regclass(pRExC_state,depth+1);
6599 RExC_end = oldregxend;
6602 Set_Node_Offset(ret, parse_start + 2);
6603 Set_Node_Cur_Length(ret);
6604 nextchar(pRExC_state);
6605 *flagp |= HASWIDTH|SIMPLE;
6609 /* Handle \N{NAME} here and not below because it can be
6610 multicharacter. join_exact() will join them up later on.
6611 Also this makes sure that things like /\N{BLAH}+/ and
6612 \N{BLAH} being multi char Just Happen. dmq*/
6614 ret= reg_namedseq(pRExC_state, NULL);
6616 case 'k': /* Handle \k<NAME> and \k'NAME' */
6619 char ch= RExC_parse[1];
6620 if (ch != '<' && ch != '\'' && ch != '{') {
6622 vFAIL2("Sequence %.2s... not terminated",parse_start);
6624 /* this pretty much dupes the code for (?P=...) in reg(), if
6625 you change this make sure you change that */
6626 char* name_start = (RExC_parse += 2);
6628 SV *sv_dat = reg_scan_name(pRExC_state,
6629 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6630 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
6631 if (RExC_parse == name_start || *RExC_parse != ch)
6632 vFAIL2("Sequence %.3s... not terminated",parse_start);
6635 num = add_data( pRExC_state, 1, "S" );
6636 RExC_rxi->data->data[num]=(void*)sv_dat;
6637 SvREFCNT_inc(sv_dat);
6641 ret = reganode(pRExC_state,
6642 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
6646 /* override incorrect value set in reganode MJD */
6647 Set_Node_Offset(ret, parse_start+1);
6648 Set_Node_Cur_Length(ret); /* MJD */
6649 nextchar(pRExC_state);
6655 case '1': case '2': case '3': case '4':
6656 case '5': case '6': case '7': case '8': case '9':
6659 bool isg = *RExC_parse == 'g';
6664 if (*RExC_parse == '{') {
6668 if (*RExC_parse == '-') {
6672 if (hasbrace && !isDIGIT(*RExC_parse)) {
6673 if (isrel) RExC_parse--;
6675 goto parse_named_seq;
6677 num = atoi(RExC_parse);
6679 num = RExC_npar - num;
6681 vFAIL("Reference to nonexistent or unclosed group");
6683 if (!isg && num > 9 && num >= RExC_npar)
6686 char * const parse_start = RExC_parse - 1; /* MJD */
6687 while (isDIGIT(*RExC_parse))
6689 if (parse_start == RExC_parse - 1)
6690 vFAIL("Unterminated \\g... pattern");
6692 if (*RExC_parse != '}')
6693 vFAIL("Unterminated \\g{...} pattern");
6697 if (num > (I32)RExC_rx->nparens)
6698 vFAIL("Reference to nonexistent group");
6701 ret = reganode(pRExC_state,
6702 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
6706 /* override incorrect value set in reganode MJD */
6707 Set_Node_Offset(ret, parse_start+1);
6708 Set_Node_Cur_Length(ret); /* MJD */
6710 nextchar(pRExC_state);
6715 if (RExC_parse >= RExC_end)
6716 FAIL("Trailing \\");
6719 /* Do not generate "unrecognized" warnings here, we fall
6720 back into the quick-grab loop below */
6727 if (RExC_flags & RXf_PMf_EXTENDED) {
6728 if ( reg_skipcomment( pRExC_state ) )
6734 register STRLEN len;
6739 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6741 parse_start = RExC_parse - 1;
6747 ret = reg_node(pRExC_state,
6748 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6750 for (len = 0, p = RExC_parse - 1;
6751 len < 127 && p < RExC_end;
6754 char * const oldp = p;
6756 if (RExC_flags & RXf_PMf_EXTENDED)
6757 p = regwhite( pRExC_state, p );
6768 /* Literal Escapes Switch
6770 This switch is meant to handle escape sequences that
6771 resolve to a literal character.
6773 Every escape sequence that represents something
6774 else, like an assertion or a char class, is handled
6775 in the switch marked 'Special Escapes' above in this
6776 routine, but also has an entry here as anything that
6777 isn't explicitly mentioned here will be treated as
6778 an unescaped equivalent literal.
6782 /* These are all the special escapes. */
6783 case 'A': /* Start assertion */
6784 case 'b': case 'B': /* Word-boundary assertion*/
6785 case 'C': /* Single char !DANGEROUS! */
6786 case 'd': case 'D': /* digit class */
6787 case 'g': case 'G': /* generic-backref, pos assertion */
6788 case 'k': case 'K': /* named backref, keep marker */
6789 case 'N': /* named char sequence */
6790 case 'p': case 'P': /* unicode property */
6791 case 's': case 'S': /* space class */
6792 case 'v': case 'V': /* (*PRUNE) and (*SKIP) */
6793 case 'w': case 'W': /* word class */
6794 case 'X': /* eXtended Unicode "combining character sequence" */
6795 case 'z': case 'Z': /* End of line/string assertion */
6799 /* Anything after here is an escape that resolves to a
6800 literal. (Except digits, which may or may not)
6819 ender = ASCII_TO_NATIVE('\033');
6823 ender = ASCII_TO_NATIVE('\007');
6828 char* const e = strchr(p, '}');
6832 vFAIL("Missing right brace on \\x{}");
6835 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6836 | PERL_SCAN_DISALLOW_PREFIX;
6837 STRLEN numlen = e - p - 1;
6838 ender = grok_hex(p + 1, &numlen, &flags, NULL);
6845 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6847 ender = grok_hex(p, &numlen, &flags, NULL);
6850 if (PL_encoding && ender < 0x100)
6851 goto recode_encoding;
6855 ender = UCHARAT(p++);
6856 ender = toCTRL(ender);
6858 case '0': case '1': case '2': case '3':case '4':
6859 case '5': case '6': case '7': case '8':case '9':
6861 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
6864 ender = grok_oct(p, &numlen, &flags, NULL);
6871 if (PL_encoding && ender < 0x100)
6872 goto recode_encoding;
6876 SV* enc = PL_encoding;
6877 ender = reg_recode((const char)(U8)ender, &enc);
6878 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
6879 vWARN(p, "Invalid escape in the specified encoding");
6885 FAIL("Trailing \\");
6888 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
6889 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
6890 goto normal_default;
6895 if (UTF8_IS_START(*p) && UTF) {
6897 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
6898 &numlen, UTF8_ALLOW_DEFAULT);
6905 if ( RExC_flags & RXf_PMf_EXTENDED)
6906 p = regwhite( pRExC_state, p );
6908 /* Prime the casefolded buffer. */
6909 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
6911 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
6916 /* Emit all the Unicode characters. */
6918 for (foldbuf = tmpbuf;
6920 foldlen -= numlen) {
6921 ender = utf8_to_uvchr(foldbuf, &numlen);
6923 const STRLEN unilen = reguni(pRExC_state, ender, s);
6926 /* In EBCDIC the numlen
6927 * and unilen can differ. */
6929 if (numlen >= foldlen)
6933 break; /* "Can't happen." */
6937 const STRLEN unilen = reguni(pRExC_state, ender, s);
6946 REGC((char)ender, s++);
6952 /* Emit all the Unicode characters. */
6954 for (foldbuf = tmpbuf;
6956 foldlen -= numlen) {
6957 ender = utf8_to_uvchr(foldbuf, &numlen);
6959 const STRLEN unilen = reguni(pRExC_state, ender, s);
6962 /* In EBCDIC the numlen
6963 * and unilen can differ. */
6965 if (numlen >= foldlen)
6973 const STRLEN unilen = reguni(pRExC_state, ender, s);
6982 REGC((char)ender, s++);
6986 Set_Node_Cur_Length(ret); /* MJD */
6987 nextchar(pRExC_state);
6989 /* len is STRLEN which is unsigned, need to copy to signed */
6992 vFAIL("Internal disaster");
6996 if (len == 1 && UNI_IS_INVARIANT(ender))
7000 RExC_size += STR_SZ(len);
7003 RExC_emit += STR_SZ(len);
7013 S_regwhite( RExC_state_t *pRExC_state, char *p )
7015 const char *e = RExC_end;
7019 else if (*p == '#') {
7028 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7036 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
7037 Character classes ([:foo:]) can also be negated ([:^foo:]).
7038 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
7039 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
7040 but trigger failures because they are currently unimplemented. */
7042 #define POSIXCC_DONE(c) ((c) == ':')
7043 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
7044 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
7047 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
7050 I32 namedclass = OOB_NAMEDCLASS;
7052 if (value == '[' && RExC_parse + 1 < RExC_end &&
7053 /* I smell either [: or [= or [. -- POSIX has been here, right? */
7054 POSIXCC(UCHARAT(RExC_parse))) {
7055 const char c = UCHARAT(RExC_parse);
7056 char* const s = RExC_parse++;
7058 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
7060 if (RExC_parse == RExC_end)
7061 /* Grandfather lone [:, [=, [. */
7064 const char* const t = RExC_parse++; /* skip over the c */
7067 if (UCHARAT(RExC_parse) == ']') {
7068 const char *posixcc = s + 1;
7069 RExC_parse++; /* skip over the ending ] */
7072 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
7073 const I32 skip = t - posixcc;
7075 /* Initially switch on the length of the name. */
7078 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
7079 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
7082 /* Names all of length 5. */
7083 /* alnum alpha ascii blank cntrl digit graph lower
7084 print punct space upper */
7085 /* Offset 4 gives the best switch position. */
7086 switch (posixcc[4]) {
7088 if (memEQ(posixcc, "alph", 4)) /* alpha */
7089 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
7092 if (memEQ(posixcc, "spac", 4)) /* space */
7093 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
7096 if (memEQ(posixcc, "grap", 4)) /* graph */
7097 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
7100 if (memEQ(posixcc, "asci", 4)) /* ascii */
7101 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
7104 if (memEQ(posixcc, "blan", 4)) /* blank */
7105 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
7108 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
7109 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
7112 if (memEQ(posixcc, "alnu", 4)) /* alnum */
7113 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
7116 if (memEQ(posixcc, "lowe", 4)) /* lower */
7117 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
7118 else if (memEQ(posixcc, "uppe", 4)) /* upper */
7119 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
7122 if (memEQ(posixcc, "digi", 4)) /* digit */
7123 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
7124 else if (memEQ(posixcc, "prin", 4)) /* print */
7125 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
7126 else if (memEQ(posixcc, "punc", 4)) /* punct */
7127 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
7132 if (memEQ(posixcc, "xdigit", 6))
7133 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
7137 if (namedclass == OOB_NAMEDCLASS)
7138 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
7140 assert (posixcc[skip] == ':');
7141 assert (posixcc[skip+1] == ']');
7142 } else if (!SIZE_ONLY) {
7143 /* [[=foo=]] and [[.foo.]] are still future. */
7145 /* adjust RExC_parse so the warning shows after
7147 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
7149 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7152 /* Maternal grandfather:
7153 * "[:" ending in ":" but not in ":]" */
7163 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
7166 if (POSIXCC(UCHARAT(RExC_parse))) {
7167 const char *s = RExC_parse;
7168 const char c = *s++;
7172 if (*s && c == *s && s[1] == ']') {
7173 if (ckWARN(WARN_REGEXP))
7175 "POSIX syntax [%c %c] belongs inside character classes",
7178 /* [[=foo=]] and [[.foo.]] are still future. */
7179 if (POSIXCC_NOTYET(c)) {
7180 /* adjust RExC_parse so the error shows after
7182 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
7184 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7191 #define _C_C_T_(NAME,TEST,WORD) \
7194 ANYOF_CLASS_SET(ret, ANYOF_##NAME); \
7196 for (value = 0; value < 256; value++) \
7198 ANYOF_BITMAP_SET(ret, value); \
7203 case ANYOF_N##NAME: \
7205 ANYOF_CLASS_SET(ret, ANYOF_N##NAME); \
7207 for (value = 0; value < 256; value++) \
7209 ANYOF_BITMAP_SET(ret, value); \
7217 parse a class specification and produce either an ANYOF node that
7218 matches the pattern or if the pattern matches a single char only and
7219 that char is < 256 and we are case insensitive then we produce an
7224 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
7227 register UV value = 0;
7228 register UV nextvalue;
7229 register IV prevvalue = OOB_UNICODE;
7230 register IV range = 0;
7231 register regnode *ret;
7234 char *rangebegin = NULL;
7235 bool need_class = 0;
7238 bool optimize_invert = TRUE;
7239 AV* unicode_alternate = NULL;
7241 UV literal_endpoint = 0;
7243 UV stored = 0; /* number of chars stored in the class */
7245 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
7246 case we need to change the emitted regop to an EXACT. */
7247 const char * orig_parse = RExC_parse;
7248 GET_RE_DEBUG_FLAGS_DECL;
7250 PERL_UNUSED_ARG(depth);
7253 DEBUG_PARSE("clas");
7255 /* Assume we are going to generate an ANYOF node. */
7256 ret = reganode(pRExC_state, ANYOF, 0);
7259 ANYOF_FLAGS(ret) = 0;
7261 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
7265 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
7269 RExC_size += ANYOF_SKIP;
7270 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
7273 RExC_emit += ANYOF_SKIP;
7275 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
7277 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
7278 ANYOF_BITMAP_ZERO(ret);
7279 listsv = newSVpvs("# comment\n");
7282 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7284 if (!SIZE_ONLY && POSIXCC(nextvalue))
7285 checkposixcc(pRExC_state);
7287 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
7288 if (UCHARAT(RExC_parse) == ']')
7292 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
7296 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
7299 rangebegin = RExC_parse;
7301 value = utf8n_to_uvchr((U8*)RExC_parse,
7302 RExC_end - RExC_parse,
7303 &numlen, UTF8_ALLOW_DEFAULT);
7304 RExC_parse += numlen;
7307 value = UCHARAT(RExC_parse++);
7309 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7310 if (value == '[' && POSIXCC(nextvalue))
7311 namedclass = regpposixcc(pRExC_state, value);
7312 else if (value == '\\') {
7314 value = utf8n_to_uvchr((U8*)RExC_parse,
7315 RExC_end - RExC_parse,
7316 &numlen, UTF8_ALLOW_DEFAULT);
7317 RExC_parse += numlen;
7320 value = UCHARAT(RExC_parse++);
7321 /* Some compilers cannot handle switching on 64-bit integer
7322 * values, therefore value cannot be an UV. Yes, this will
7323 * be a problem later if we want switch on Unicode.
7324 * A similar issue a little bit later when switching on
7325 * namedclass. --jhi */
7326 switch ((I32)value) {
7327 case 'w': namedclass = ANYOF_ALNUM; break;
7328 case 'W': namedclass = ANYOF_NALNUM; break;
7329 case 's': namedclass = ANYOF_SPACE; break;
7330 case 'S': namedclass = ANYOF_NSPACE; break;
7331 case 'd': namedclass = ANYOF_DIGIT; break;
7332 case 'D': namedclass = ANYOF_NDIGIT; break;
7333 case 'N': /* Handle \N{NAME} in class */
7335 /* We only pay attention to the first char of
7336 multichar strings being returned. I kinda wonder
7337 if this makes sense as it does change the behaviour
7338 from earlier versions, OTOH that behaviour was broken
7340 UV v; /* value is register so we cant & it /grrr */
7341 if (reg_namedseq(pRExC_state, &v)) {
7351 if (RExC_parse >= RExC_end)
7352 vFAIL2("Empty \\%c{}", (U8)value);
7353 if (*RExC_parse == '{') {
7354 const U8 c = (U8)value;
7355 e = strchr(RExC_parse++, '}');
7357 vFAIL2("Missing right brace on \\%c{}", c);
7358 while (isSPACE(UCHARAT(RExC_parse)))
7360 if (e == RExC_parse)
7361 vFAIL2("Empty \\%c{}", c);
7363 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
7371 if (UCHARAT(RExC_parse) == '^') {
7374 value = value == 'p' ? 'P' : 'p'; /* toggle */
7375 while (isSPACE(UCHARAT(RExC_parse))) {
7380 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
7381 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
7384 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7385 namedclass = ANYOF_MAX; /* no official name, but it's named */
7388 case 'n': value = '\n'; break;
7389 case 'r': value = '\r'; break;
7390 case 't': value = '\t'; break;
7391 case 'f': value = '\f'; break;
7392 case 'b': value = '\b'; break;
7393 case 'e': value = ASCII_TO_NATIVE('\033');break;
7394 case 'a': value = ASCII_TO_NATIVE('\007');break;
7396 if (*RExC_parse == '{') {
7397 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7398 | PERL_SCAN_DISALLOW_PREFIX;
7399 char * const e = strchr(RExC_parse++, '}');
7401 vFAIL("Missing right brace on \\x{}");
7403 numlen = e - RExC_parse;
7404 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7408 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7410 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7411 RExC_parse += numlen;
7413 if (PL_encoding && value < 0x100)
7414 goto recode_encoding;
7417 value = UCHARAT(RExC_parse++);
7418 value = toCTRL(value);
7420 case '0': case '1': case '2': case '3': case '4':
7421 case '5': case '6': case '7': case '8': case '9':
7425 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
7426 RExC_parse += numlen;
7427 if (PL_encoding && value < 0x100)
7428 goto recode_encoding;
7433 SV* enc = PL_encoding;
7434 value = reg_recode((const char)(U8)value, &enc);
7435 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
7437 "Invalid escape in the specified encoding");
7441 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
7443 "Unrecognized escape \\%c in character class passed through",
7447 } /* end of \blah */
7453 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
7455 if (!SIZE_ONLY && !need_class)
7456 ANYOF_CLASS_ZERO(ret);
7460 /* a bad range like a-\d, a-[:digit:] ? */
7463 if (ckWARN(WARN_REGEXP)) {
7465 RExC_parse >= rangebegin ?
7466 RExC_parse - rangebegin : 0;
7468 "False [] range \"%*.*s\"",
7471 if (prevvalue < 256) {
7472 ANYOF_BITMAP_SET(ret, prevvalue);
7473 ANYOF_BITMAP_SET(ret, '-');
7476 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7477 Perl_sv_catpvf(aTHX_ listsv,
7478 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
7482 range = 0; /* this was not a true range */
7488 const char *what = NULL;
7491 if (namedclass > OOB_NAMEDCLASS)
7492 optimize_invert = FALSE;
7493 /* Possible truncation here but in some 64-bit environments
7494 * the compiler gets heartburn about switch on 64-bit values.
7495 * A similar issue a little earlier when switching on value.
7497 switch ((I32)namedclass) {
7498 case _C_C_T_(ALNUM, isALNUM(value), "Word");
7499 case _C_C_T_(ALNUMC, isALNUMC(value), "Alnum");
7500 case _C_C_T_(ALPHA, isALPHA(value), "Alpha");
7501 case _C_C_T_(BLANK, isBLANK(value), "Blank");
7502 case _C_C_T_(CNTRL, isCNTRL(value), "Cntrl");
7503 case _C_C_T_(GRAPH, isGRAPH(value), "Graph");
7504 case _C_C_T_(LOWER, isLOWER(value), "Lower");
7505 case _C_C_T_(PRINT, isPRINT(value), "Print");
7506 case _C_C_T_(PSXSPC, isPSXSPC(value), "Space");
7507 case _C_C_T_(PUNCT, isPUNCT(value), "Punct");
7508 case _C_C_T_(SPACE, isSPACE(value), "SpacePerl");
7509 case _C_C_T_(UPPER, isUPPER(value), "Upper");
7510 case _C_C_T_(XDIGIT, isXDIGIT(value), "XDigit");
7513 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
7516 for (value = 0; value < 128; value++)
7517 ANYOF_BITMAP_SET(ret, value);
7519 for (value = 0; value < 256; value++) {
7521 ANYOF_BITMAP_SET(ret, value);
7530 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
7533 for (value = 128; value < 256; value++)
7534 ANYOF_BITMAP_SET(ret, value);
7536 for (value = 0; value < 256; value++) {
7537 if (!isASCII(value))
7538 ANYOF_BITMAP_SET(ret, value);
7547 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
7549 /* consecutive digits assumed */
7550 for (value = '0'; value <= '9'; value++)
7551 ANYOF_BITMAP_SET(ret, value);
7558 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
7560 /* consecutive digits assumed */
7561 for (value = 0; value < '0'; value++)
7562 ANYOF_BITMAP_SET(ret, value);
7563 for (value = '9' + 1; value < 256; value++)
7564 ANYOF_BITMAP_SET(ret, value);
7570 /* this is to handle \p and \P */
7573 vFAIL("Invalid [::] class");
7577 /* Strings such as "+utf8::isWord\n" */
7578 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
7581 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
7584 } /* end of namedclass \blah */
7587 if (prevvalue > (IV)value) /* b-a */ {
7588 const int w = RExC_parse - rangebegin;
7589 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
7590 range = 0; /* not a valid range */
7594 prevvalue = value; /* save the beginning of the range */
7595 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
7596 RExC_parse[1] != ']') {
7599 /* a bad range like \w-, [:word:]- ? */
7600 if (namedclass > OOB_NAMEDCLASS) {
7601 if (ckWARN(WARN_REGEXP)) {
7603 RExC_parse >= rangebegin ?
7604 RExC_parse - rangebegin : 0;
7606 "False [] range \"%*.*s\"",
7610 ANYOF_BITMAP_SET(ret, '-');
7612 range = 1; /* yeah, it's a range! */
7613 continue; /* but do it the next time */
7617 /* now is the next time */
7618 /*stored += (value - prevvalue + 1);*/
7620 if (prevvalue < 256) {
7621 const IV ceilvalue = value < 256 ? value : 255;
7624 /* In EBCDIC [\x89-\x91] should include
7625 * the \x8e but [i-j] should not. */
7626 if (literal_endpoint == 2 &&
7627 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
7628 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
7630 if (isLOWER(prevvalue)) {
7631 for (i = prevvalue; i <= ceilvalue; i++)
7633 ANYOF_BITMAP_SET(ret, i);
7635 for (i = prevvalue; i <= ceilvalue; i++)
7637 ANYOF_BITMAP_SET(ret, i);
7642 for (i = prevvalue; i <= ceilvalue; i++) {
7643 if (!ANYOF_BITMAP_TEST(ret,i)) {
7645 ANYOF_BITMAP_SET(ret, i);
7649 if (value > 255 || UTF) {
7650 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
7651 const UV natvalue = NATIVE_TO_UNI(value);
7652 stored+=2; /* can't optimize this class */
7653 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7654 if (prevnatvalue < natvalue) { /* what about > ? */
7655 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
7656 prevnatvalue, natvalue);
7658 else if (prevnatvalue == natvalue) {
7659 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
7661 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
7663 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
7665 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
7666 if (RExC_precomp[0] == ':' &&
7667 RExC_precomp[1] == '[' &&
7668 (f == 0xDF || f == 0x92)) {
7669 f = NATIVE_TO_UNI(f);
7672 /* If folding and foldable and a single
7673 * character, insert also the folded version
7674 * to the charclass. */
7676 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7677 if ((RExC_precomp[0] == ':' &&
7678 RExC_precomp[1] == '[' &&
7680 (value == 0xFB05 || value == 0xFB06))) ?
7681 foldlen == ((STRLEN)UNISKIP(f) - 1) :
7682 foldlen == (STRLEN)UNISKIP(f) )
7684 if (foldlen == (STRLEN)UNISKIP(f))
7686 Perl_sv_catpvf(aTHX_ listsv,
7689 /* Any multicharacter foldings
7690 * require the following transform:
7691 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7692 * where E folds into "pq" and F folds
7693 * into "rst", all other characters
7694 * fold to single characters. We save
7695 * away these multicharacter foldings,
7696 * to be later saved as part of the
7697 * additional "s" data. */
7700 if (!unicode_alternate)
7701 unicode_alternate = newAV();
7702 sv = newSVpvn((char*)foldbuf, foldlen);
7704 av_push(unicode_alternate, sv);
7708 /* If folding and the value is one of the Greek
7709 * sigmas insert a few more sigmas to make the
7710 * folding rules of the sigmas to work right.
7711 * Note that not all the possible combinations
7712 * are handled here: some of them are handled
7713 * by the standard folding rules, and some of
7714 * them (literal or EXACTF cases) are handled
7715 * during runtime in regexec.c:S_find_byclass(). */
7716 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7717 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7718 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7719 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7720 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7722 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7723 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7724 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7729 literal_endpoint = 0;
7733 range = 0; /* this range (if it was one) is done now */
7737 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7739 RExC_size += ANYOF_CLASS_ADD_SKIP;
7741 RExC_emit += ANYOF_CLASS_ADD_SKIP;
7747 /****** !SIZE_ONLY AFTER HERE *********/
7749 if( stored == 1 && value < 256
7750 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7752 /* optimize single char class to an EXACT node
7753 but *only* when its not a UTF/high char */
7754 const char * cur_parse= RExC_parse;
7755 RExC_emit = (regnode *)orig_emit;
7756 RExC_parse = (char *)orig_parse;
7757 ret = reg_node(pRExC_state,
7758 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7759 RExC_parse = (char *)cur_parse;
7760 *STRING(ret)= (char)value;
7762 RExC_emit += STR_SZ(1);
7765 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7766 if ( /* If the only flag is folding (plus possibly inversion). */
7767 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7769 for (value = 0; value < 256; ++value) {
7770 if (ANYOF_BITMAP_TEST(ret, value)) {
7771 UV fold = PL_fold[value];
7774 ANYOF_BITMAP_SET(ret, fold);
7777 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7780 /* optimize inverted simple patterns (e.g. [^a-z]) */
7781 if (optimize_invert &&
7782 /* If the only flag is inversion. */
7783 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7784 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7785 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7786 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7789 AV * const av = newAV();
7791 /* The 0th element stores the character class description
7792 * in its textual form: used later (regexec.c:Perl_regclass_swash())
7793 * to initialize the appropriate swash (which gets stored in
7794 * the 1st element), and also useful for dumping the regnode.
7795 * The 2nd element stores the multicharacter foldings,
7796 * used later (regexec.c:S_reginclass()). */
7797 av_store(av, 0, listsv);
7798 av_store(av, 1, NULL);
7799 av_store(av, 2, (SV*)unicode_alternate);
7800 rv = newRV_noinc((SV*)av);
7801 n = add_data(pRExC_state, 1, "s");
7802 RExC_rxi->data->data[n] = (void*)rv;
7810 /* reg_skipcomment()
7812 Absorbs an /x style # comments from the input stream.
7813 Returns true if there is more text remaining in the stream.
7814 Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
7815 terminates the pattern without including a newline.
7817 Note its the callers responsibility to ensure that we are
7823 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
7826 while (RExC_parse < RExC_end)
7827 if (*RExC_parse++ == '\n') {
7832 /* we ran off the end of the pattern without ending
7833 the comment, so we have to add an \n when wrapping */
7834 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7842 Advance that parse position, and optionall absorbs
7843 "whitespace" from the inputstream.
7845 Without /x "whitespace" means (?#...) style comments only,
7846 with /x this means (?#...) and # comments and whitespace proper.
7848 Returns the RExC_parse point from BEFORE the scan occurs.
7850 This is the /x friendly way of saying RExC_parse++.
7854 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7856 char* const retval = RExC_parse++;
7859 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7860 RExC_parse[2] == '#') {
7861 while (*RExC_parse != ')') {
7862 if (RExC_parse == RExC_end)
7863 FAIL("Sequence (?#... not terminated");
7869 if (RExC_flags & RXf_PMf_EXTENDED) {
7870 if (isSPACE(*RExC_parse)) {
7874 else if (*RExC_parse == '#') {
7875 if ( reg_skipcomment( pRExC_state ) )
7884 - reg_node - emit a node
7886 STATIC regnode * /* Location. */
7887 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7890 register regnode *ptr;
7891 regnode * const ret = RExC_emit;
7892 GET_RE_DEBUG_FLAGS_DECL;
7895 SIZE_ALIGN(RExC_size);
7900 if (OP(RExC_emit) == 255)
7901 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %s: %d ",
7902 reg_name[op], OP(RExC_emit));
7904 NODE_ALIGN_FILL(ret);
7906 FILL_ADVANCE_NODE(ptr, op);
7907 #ifdef RE_TRACK_PATTERN_OFFSETS
7908 if (RExC_offsets) { /* MJD */
7909 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
7910 "reg_node", __LINE__,
7912 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
7913 ? "Overwriting end of array!\n" : "OK",
7914 (UV)(RExC_emit - RExC_emit_start),
7915 (UV)(RExC_parse - RExC_start),
7916 (UV)RExC_offsets[0]));
7917 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7925 - reganode - emit a node with an argument
7927 STATIC regnode * /* Location. */
7928 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7931 register regnode *ptr;
7932 regnode * const ret = RExC_emit;
7933 GET_RE_DEBUG_FLAGS_DECL;
7936 SIZE_ALIGN(RExC_size);
7941 assert(2==regarglen[op]+1);
7943 Anything larger than this has to allocate the extra amount.
7944 If we changed this to be:
7946 RExC_size += (1 + regarglen[op]);
7948 then it wouldn't matter. Its not clear what side effect
7949 might come from that so its not done so far.
7955 if (OP(RExC_emit) == 255)
7956 Perl_croak(aTHX_ "panic: reganode overwriting end of allocated program space");
7958 NODE_ALIGN_FILL(ret);
7960 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7961 #ifdef RE_TRACK_PATTERN_OFFSETS
7962 if (RExC_offsets) { /* MJD */
7963 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7967 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7968 "Overwriting end of array!\n" : "OK",
7969 (UV)(RExC_emit - RExC_emit_start),
7970 (UV)(RExC_parse - RExC_start),
7971 (UV)RExC_offsets[0]));
7972 Set_Cur_Node_Offset;
7980 - reguni - emit (if appropriate) a Unicode character
7983 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7986 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7990 - reginsert - insert an operator in front of already-emitted operand
7992 * Means relocating the operand.
7995 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7998 register regnode *src;
7999 register regnode *dst;
8000 register regnode *place;
8001 const int offset = regarglen[(U8)op];
8002 const int size = NODE_STEP_REGNODE + offset;
8003 GET_RE_DEBUG_FLAGS_DECL;
8004 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
8005 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
8014 if (RExC_open_parens) {
8016 DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);
8017 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
8018 if ( RExC_open_parens[paren] >= opnd ) {
8019 DEBUG_PARSE_FMT("open"," - %d",size);
8020 RExC_open_parens[paren] += size;
8022 DEBUG_PARSE_FMT("open"," - %s","ok");
8024 if ( RExC_close_parens[paren] >= opnd ) {
8025 DEBUG_PARSE_FMT("close"," - %d",size);
8026 RExC_close_parens[paren] += size;
8028 DEBUG_PARSE_FMT("close"," - %s","ok");
8033 while (src > opnd) {
8034 StructCopy(--src, --dst, regnode);
8035 #ifdef RE_TRACK_PATTERN_OFFSETS
8036 if (RExC_offsets) { /* MJD 20010112 */
8037 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
8041 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
8042 ? "Overwriting end of array!\n" : "OK",
8043 (UV)(src - RExC_emit_start),
8044 (UV)(dst - RExC_emit_start),
8045 (UV)RExC_offsets[0]));
8046 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
8047 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
8053 place = opnd; /* Op node, where operand used to be. */
8054 #ifdef RE_TRACK_PATTERN_OFFSETS
8055 if (RExC_offsets) { /* MJD */
8056 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
8060 (UV)(place - RExC_emit_start) > RExC_offsets[0]
8061 ? "Overwriting end of array!\n" : "OK",
8062 (UV)(place - RExC_emit_start),
8063 (UV)(RExC_parse - RExC_start),
8064 (UV)RExC_offsets[0]));
8065 Set_Node_Offset(place, RExC_parse);
8066 Set_Node_Length(place, 1);
8069 src = NEXTOPER(place);
8070 FILL_ADVANCE_NODE(place, op);
8071 Zero(src, offset, regnode);
8075 - regtail - set the next-pointer at the end of a node chain of p to val.
8076 - SEE ALSO: regtail_study
8078 /* TODO: All three parms should be const */
8080 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8083 register regnode *scan;
8084 GET_RE_DEBUG_FLAGS_DECL;
8086 PERL_UNUSED_ARG(depth);
8092 /* Find last node. */
8095 regnode * const temp = regnext(scan);
8097 SV * const mysv=sv_newmortal();
8098 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
8099 regprop(RExC_rx, mysv, scan);
8100 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
8101 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
8102 (temp == NULL ? "->" : ""),
8103 (temp == NULL ? reg_name[OP(val)] : "")
8111 if (reg_off_by_arg[OP(scan)]) {
8112 ARG_SET(scan, val - scan);
8115 NEXT_OFF(scan) = val - scan;
8121 - regtail_study - set the next-pointer at the end of a node chain of p to val.
8122 - Look for optimizable sequences at the same time.
8123 - currently only looks for EXACT chains.
8125 This is expermental code. The idea is to use this routine to perform
8126 in place optimizations on branches and groups as they are constructed,
8127 with the long term intention of removing optimization from study_chunk so
8128 that it is purely analytical.
8130 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
8131 to control which is which.
8134 /* TODO: All four parms should be const */
8137 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8140 register regnode *scan;
8142 #ifdef EXPERIMENTAL_INPLACESCAN
8146 GET_RE_DEBUG_FLAGS_DECL;
8152 /* Find last node. */
8156 regnode * const temp = regnext(scan);
8157 #ifdef EXPERIMENTAL_INPLACESCAN
8158 if (PL_regkind[OP(scan)] == EXACT)
8159 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
8167 if( exact == PSEUDO )
8169 else if ( exact != OP(scan) )
8178 SV * const mysv=sv_newmortal();
8179 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8180 regprop(RExC_rx, mysv, scan);
8181 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8182 SvPV_nolen_const(mysv),
8191 SV * const mysv_val=sv_newmortal();
8192 DEBUG_PARSE_MSG("");
8193 regprop(RExC_rx, mysv_val, val);
8194 PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
8195 SvPV_nolen_const(mysv_val),
8196 (IV)REG_NODE_NUM(val),
8200 if (reg_off_by_arg[OP(scan)]) {
8201 ARG_SET(scan, val - scan);
8204 NEXT_OFF(scan) = val - scan;
8212 - regcurly - a little FSA that accepts {\d+,?\d*}
8215 S_regcurly(register const char *s)
8234 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
8237 Perl_regdump(pTHX_ const regexp *r)
8241 SV * const sv = sv_newmortal();
8242 SV *dsv= sv_newmortal();
8245 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
8247 /* Header fields of interest. */
8248 if (r->anchored_substr) {
8249 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
8250 RE_SV_DUMPLEN(r->anchored_substr), 30);
8251 PerlIO_printf(Perl_debug_log,
8252 "anchored %s%s at %"IVdf" ",
8253 s, RE_SV_TAIL(r->anchored_substr),
8254 (IV)r->anchored_offset);
8255 } else if (r->anchored_utf8) {
8256 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
8257 RE_SV_DUMPLEN(r->anchored_utf8), 30);
8258 PerlIO_printf(Perl_debug_log,
8259 "anchored utf8 %s%s at %"IVdf" ",
8260 s, RE_SV_TAIL(r->anchored_utf8),
8261 (IV)r->anchored_offset);
8263 if (r->float_substr) {
8264 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
8265 RE_SV_DUMPLEN(r->float_substr), 30);
8266 PerlIO_printf(Perl_debug_log,
8267 "floating %s%s at %"IVdf"..%"UVuf" ",
8268 s, RE_SV_TAIL(r->float_substr),
8269 (IV)r->float_min_offset, (UV)r->float_max_offset);
8270 } else if (r->float_utf8) {
8271 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
8272 RE_SV_DUMPLEN(r->float_utf8), 30);
8273 PerlIO_printf(Perl_debug_log,
8274 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
8275 s, RE_SV_TAIL(r->float_utf8),
8276 (IV)r->float_min_offset, (UV)r->float_max_offset);
8278 if (r->check_substr || r->check_utf8)
8279 PerlIO_printf(Perl_debug_log,
8281 (r->check_substr == r->float_substr
8282 && r->check_utf8 == r->float_utf8
8283 ? "(checking floating" : "(checking anchored"));
8284 if (r->extflags & RXf_NOSCAN)
8285 PerlIO_printf(Perl_debug_log, " noscan");
8286 if (r->extflags & RXf_CHECK_ALL)
8287 PerlIO_printf(Perl_debug_log, " isall");
8288 if (r->check_substr || r->check_utf8)
8289 PerlIO_printf(Perl_debug_log, ") ");
8291 if (ri->regstclass) {
8292 regprop(r, sv, ri->regstclass);
8293 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
8295 if (r->extflags & RXf_ANCH) {
8296 PerlIO_printf(Perl_debug_log, "anchored");
8297 if (r->extflags & RXf_ANCH_BOL)
8298 PerlIO_printf(Perl_debug_log, "(BOL)");
8299 if (r->extflags & RXf_ANCH_MBOL)
8300 PerlIO_printf(Perl_debug_log, "(MBOL)");
8301 if (r->extflags & RXf_ANCH_SBOL)
8302 PerlIO_printf(Perl_debug_log, "(SBOL)");
8303 if (r->extflags & RXf_ANCH_GPOS)
8304 PerlIO_printf(Perl_debug_log, "(GPOS)");
8305 PerlIO_putc(Perl_debug_log, ' ');
8307 if (r->extflags & RXf_GPOS_SEEN)
8308 PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
8309 if (r->intflags & PREGf_SKIP)
8310 PerlIO_printf(Perl_debug_log, "plus ");
8311 if (r->intflags & PREGf_IMPLICIT)
8312 PerlIO_printf(Perl_debug_log, "implicit ");
8313 PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
8314 if (r->extflags & RXf_EVAL_SEEN)
8315 PerlIO_printf(Perl_debug_log, "with eval ");
8316 PerlIO_printf(Perl_debug_log, "\n");
8318 PERL_UNUSED_CONTEXT;
8320 #endif /* DEBUGGING */
8324 - regprop - printable representation of opcode
8327 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
8332 RXi_GET_DECL(prog,progi);
8333 GET_RE_DEBUG_FLAGS_DECL;
8336 sv_setpvn(sv, "", 0);
8338 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
8339 /* It would be nice to FAIL() here, but this may be called from
8340 regexec.c, and it would be hard to supply pRExC_state. */
8341 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
8342 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
8344 k = PL_regkind[OP(o)];
8347 SV * const dsv = sv_2mortal(newSVpvs(""));
8348 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
8349 * is a crude hack but it may be the best for now since
8350 * we have no flag "this EXACTish node was UTF-8"
8352 const char * const s =
8353 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
8354 PL_colors[0], PL_colors[1],
8355 PERL_PV_ESCAPE_UNI_DETECT |
8356 PERL_PV_PRETTY_ELIPSES |
8359 Perl_sv_catpvf(aTHX_ sv, " %s", s );
8360 } else if (k == TRIE) {
8361 /* print the details of the trie in dumpuntil instead, as
8362 * progi->data isn't available here */
8363 const char op = OP(o);
8364 const U32 n = ARG(o);
8365 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
8366 (reg_ac_data *)progi->data->data[n] :
8368 const reg_trie_data * const trie
8369 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
8371 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
8372 DEBUG_TRIE_COMPILE_r(
8373 Perl_sv_catpvf(aTHX_ sv,
8374 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
8375 (UV)trie->startstate,
8376 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
8377 (UV)trie->wordcount,
8380 (UV)TRIE_CHARCOUNT(trie),
8381 (UV)trie->uniquecharcount
8384 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
8386 int rangestart = -1;
8387 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
8388 Perl_sv_catpvf(aTHX_ sv, "[");
8389 for (i = 0; i <= 256; i++) {
8390 if (i < 256 && BITMAP_TEST(bitmap,i)) {
8391 if (rangestart == -1)
8393 } else if (rangestart != -1) {
8394 if (i <= rangestart + 3)
8395 for (; rangestart < i; rangestart++)
8396 put_byte(sv, rangestart);
8398 put_byte(sv, rangestart);
8400 put_byte(sv, i - 1);
8405 Perl_sv_catpvf(aTHX_ sv, "]");
8408 } else if (k == CURLY) {
8409 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
8410 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
8411 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
8413 else if (k == WHILEM && o->flags) /* Ordinal/of */
8414 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
8415 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
8416 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
8417 if ( prog->paren_names ) {
8418 if ( k != REF || OP(o) < NREF) {
8419 AV *list= (AV *)progi->data->data[progi->name_list_idx];
8420 SV **name= av_fetch(list, ARG(o), 0 );
8422 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
8425 AV *list= (AV *)progi->data->data[ progi->name_list_idx ];
8426 SV *sv_dat=(SV*)progi->data->data[ ARG( o ) ];
8427 I32 *nums=(I32*)SvPVX(sv_dat);
8428 SV **name= av_fetch(list, nums[0], 0 );
8431 for ( n=0; n<SvIVX(sv_dat); n++ ) {
8432 Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
8433 (n ? "," : ""), (IV)nums[n]);
8435 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
8439 } else if (k == GOSUB)
8440 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
8441 else if (k == VERB) {
8443 Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
8444 SVfARG((SV*)progi->data->data[ ARG( o ) ]));
8445 } else if (k == LOGICAL)
8446 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
8447 else if (k == ANYOF) {
8448 int i, rangestart = -1;
8449 const U8 flags = ANYOF_FLAGS(o);
8451 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
8452 static const char * const anyofs[] = {
8485 if (flags & ANYOF_LOCALE)
8486 sv_catpvs(sv, "{loc}");
8487 if (flags & ANYOF_FOLD)
8488 sv_catpvs(sv, "{i}");
8489 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
8490 if (flags & ANYOF_INVERT)
8492 for (i = 0; i <= 256; i++) {
8493 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
8494 if (rangestart == -1)
8496 } else if (rangestart != -1) {
8497 if (i <= rangestart + 3)
8498 for (; rangestart < i; rangestart++)
8499 put_byte(sv, rangestart);
8501 put_byte(sv, rangestart);
8503 put_byte(sv, i - 1);
8509 if (o->flags & ANYOF_CLASS)
8510 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
8511 if (ANYOF_CLASS_TEST(o,i))
8512 sv_catpv(sv, anyofs[i]);
8514 if (flags & ANYOF_UNICODE)
8515 sv_catpvs(sv, "{unicode}");
8516 else if (flags & ANYOF_UNICODE_ALL)
8517 sv_catpvs(sv, "{unicode_all}");
8521 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
8525 U8 s[UTF8_MAXBYTES_CASE+1];
8527 for (i = 0; i <= 256; i++) { /* just the first 256 */
8528 uvchr_to_utf8(s, i);
8530 if (i < 256 && swash_fetch(sw, s, TRUE)) {
8531 if (rangestart == -1)
8533 } else if (rangestart != -1) {
8534 if (i <= rangestart + 3)
8535 for (; rangestart < i; rangestart++) {
8536 const U8 * const e = uvchr_to_utf8(s,rangestart);
8538 for(p = s; p < e; p++)
8542 const U8 *e = uvchr_to_utf8(s,rangestart);
8544 for (p = s; p < e; p++)
8547 e = uvchr_to_utf8(s, i-1);
8548 for (p = s; p < e; p++)
8555 sv_catpvs(sv, "..."); /* et cetera */
8559 char *s = savesvpv(lv);
8560 char * const origs = s;
8562 while (*s && *s != '\n')
8566 const char * const t = ++s;
8584 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
8586 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
8587 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
8589 PERL_UNUSED_CONTEXT;
8590 PERL_UNUSED_ARG(sv);
8592 PERL_UNUSED_ARG(prog);
8593 #endif /* DEBUGGING */
8597 Perl_re_intuit_string(pTHX_ regexp *prog)
8598 { /* Assume that RE_INTUIT is set */
8600 GET_RE_DEBUG_FLAGS_DECL;
8601 PERL_UNUSED_CONTEXT;
8605 const char * const s = SvPV_nolen_const(prog->check_substr
8606 ? prog->check_substr : prog->check_utf8);
8608 if (!PL_colorset) reginitcolors();
8609 PerlIO_printf(Perl_debug_log,
8610 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
8612 prog->check_substr ? "" : "utf8 ",
8613 PL_colors[5],PL_colors[0],
8616 (strlen(s) > 60 ? "..." : ""));
8619 return prog->check_substr ? prog->check_substr : prog->check_utf8;
8625 handles refcounting and freeing the perl core regexp structure. When
8626 it is necessary to actually free the structure the first thing it
8627 does is call the 'free' method of the regexp_engine associated to to
8628 the regexp, allowing the handling of the void *pprivate; member
8629 first. (This routine is not overridable by extensions, which is why
8630 the extensions free is called first.)
8632 See regdupe and regdupe_internal if you change anything here.
8634 #ifndef PERL_IN_XSUB_RE
8636 Perl_pregfree(pTHX_ struct regexp *r)
8639 GET_RE_DEBUG_FLAGS_DECL;
8641 if (!r || (--r->refcnt > 0))
8644 CALLREGFREE_PVT(r); /* free the private data */
8645 RX_MATCH_COPY_FREE(r);
8646 #ifdef PERL_OLD_COPY_ON_WRITE
8648 SvREFCNT_dec(r->saved_copy);
8651 if (r->anchored_substr)
8652 SvREFCNT_dec(r->anchored_substr);
8653 if (r->anchored_utf8)
8654 SvREFCNT_dec(r->anchored_utf8);
8655 if (r->float_substr)
8656 SvREFCNT_dec(r->float_substr);
8658 SvREFCNT_dec(r->float_utf8);
8659 Safefree(r->substrs);
8662 SvREFCNT_dec(r->paren_names);
8663 Safefree(r->wrapped);
8664 Safefree(r->startp);
8670 /* regfree_internal()
8672 Free the private data in a regexp. This is overloadable by
8673 extensions. Perl takes care of the regexp structure in pregfree(),
8674 this covers the *pprivate pointer which technically perldoesnt
8675 know about, however of course we have to handle the
8676 regexp_internal structure when no extension is in use.
8678 Note this is called before freeing anything in the regexp
8683 Perl_regfree_internal(pTHX_ struct regexp *r)
8687 GET_RE_DEBUG_FLAGS_DECL;
8693 SV *dsv= sv_newmortal();
8694 RE_PV_QUOTED_DECL(s, (r->extflags & RXf_UTF8),
8695 dsv, r->precomp, r->prelen, 60);
8696 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
8697 PL_colors[4],PL_colors[5],s);
8700 #ifdef RE_TRACK_PATTERN_OFFSETS
8702 Safefree(ri->u.offsets); /* 20010421 MJD */
8705 int n = ri->data->count;
8706 PAD* new_comppad = NULL;
8711 /* If you add a ->what type here, update the comment in regcomp.h */
8712 switch (ri->data->what[n]) {
8716 SvREFCNT_dec((SV*)ri->data->data[n]);
8719 Safefree(ri->data->data[n]);
8722 new_comppad = (AV*)ri->data->data[n];
8725 if (new_comppad == NULL)
8726 Perl_croak(aTHX_ "panic: pregfree comppad");
8727 PAD_SAVE_LOCAL(old_comppad,
8728 /* Watch out for global destruction's random ordering. */
8729 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
8732 refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
8735 op_free((OP_4tree*)ri->data->data[n]);
8737 PAD_RESTORE_LOCAL(old_comppad);
8738 SvREFCNT_dec((SV*)new_comppad);
8744 { /* Aho Corasick add-on structure for a trie node.
8745 Used in stclass optimization only */
8747 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
8749 refcount = --aho->refcount;
8752 PerlMemShared_free(aho->states);
8753 PerlMemShared_free(aho->fail);
8754 /* do this last!!!! */
8755 PerlMemShared_free(ri->data->data[n]);
8756 PerlMemShared_free(ri->regstclass);
8762 /* trie structure. */
8764 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
8766 refcount = --trie->refcount;
8769 PerlMemShared_free(trie->charmap);
8770 PerlMemShared_free(trie->states);
8771 PerlMemShared_free(trie->trans);
8773 PerlMemShared_free(trie->bitmap);
8775 PerlMemShared_free(trie->wordlen);
8777 PerlMemShared_free(trie->jump);
8779 PerlMemShared_free(trie->nextword);
8780 /* do this last!!!! */
8781 PerlMemShared_free(ri->data->data[n]);
8786 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
8789 Safefree(ri->data->what);
8793 Safefree(ri->swap->startp);
8794 Safefree(ri->swap->endp);
8800 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8801 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8802 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8803 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8806 regdupe - duplicate a regexp.
8808 This routine is called by sv.c's re_dup and is expected to clone a
8809 given regexp structure. It is a no-op when not under USE_ITHREADS.
8810 (Originally this *was* re_dup() for change history see sv.c)
8812 After all of the core data stored in struct regexp is duplicated
8813 the regexp_engine.dupe method is used to copy any private data
8814 stored in the *pprivate pointer. This allows extensions to handle
8815 any duplication it needs to do.
8817 See pregfree() and regfree_internal() if you change anything here.
8819 #if defined(USE_ITHREADS)
8820 #ifndef PERL_IN_XSUB_RE
8822 Perl_re_dup(pTHX_ const regexp *r, CLONE_PARAMS *param)
8827 struct reg_substr_datum *s;
8830 return (REGEXP *)NULL;
8832 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8836 npar = r->nparens+1;
8837 Newxz(ret, 1, regexp);
8838 Newx(ret->startp, npar, I32);
8839 Copy(r->startp, ret->startp, npar, I32);
8840 Newx(ret->endp, npar, I32);
8841 Copy(r->endp, ret->endp, npar, I32);
8844 Newx(ret->substrs, 1, struct reg_substr_data);
8845 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8846 s->min_offset = r->substrs->data[i].min_offset;
8847 s->max_offset = r->substrs->data[i].max_offset;
8848 s->end_shift = r->substrs->data[i].end_shift;
8849 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8850 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8853 ret->substrs = NULL;
8855 ret->wrapped = SAVEPVN(r->wrapped, r->wraplen);
8856 ret->precomp = ret->wrapped + (r->precomp - r->wrapped);
8857 ret->prelen = r->prelen;
8858 ret->wraplen = r->wraplen;
8860 ret->refcnt = r->refcnt;
8861 ret->minlen = r->minlen;
8862 ret->minlenret = r->minlenret;
8863 ret->nparens = r->nparens;
8864 ret->lastparen = r->lastparen;
8865 ret->lastcloseparen = r->lastcloseparen;
8866 ret->intflags = r->intflags;
8867 ret->extflags = r->extflags;
8869 ret->sublen = r->sublen;
8871 ret->engine = r->engine;
8873 ret->paren_names = hv_dup_inc(r->paren_names, param);
8875 if (RX_MATCH_COPIED(ret))
8876 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
8879 #ifdef PERL_OLD_COPY_ON_WRITE
8880 ret->saved_copy = NULL;
8883 ret->pprivate = r->pprivate;
8885 RXi_SET(ret,CALLREGDUPE_PVT(ret,param));
8887 ptr_table_store(PL_ptr_table, r, ret);
8890 #endif /* PERL_IN_XSUB_RE */
8895 This is the internal complement to regdupe() which is used to copy
8896 the structure pointed to by the *pprivate pointer in the regexp.
8897 This is the core version of the extension overridable cloning hook.
8898 The regexp structure being duplicated will be copied by perl prior
8899 to this and will be provided as the regexp *r argument, however
8900 with the /old/ structures pprivate pointer value. Thus this routine
8901 may override any copying normally done by perl.
8903 It returns a pointer to the new regexp_internal structure.
8907 Perl_regdupe_internal(pTHX_ const regexp *r, CLONE_PARAMS *param)
8910 regexp_internal *reti;
8914 npar = r->nparens+1;
8917 Newxc(reti, sizeof(regexp_internal) + (len+1)*sizeof(regnode), char, regexp_internal);
8918 Copy(ri->program, reti->program, len+1, regnode);
8921 Newx(reti->swap, 1, regexp_paren_ofs);
8922 /* no need to copy these */
8923 Newx(reti->swap->startp, npar, I32);
8924 Newx(reti->swap->endp, npar, I32);
8929 reti->regstclass = NULL;
8933 const int count = ri->data->count;
8936 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8937 char, struct reg_data);
8938 Newx(d->what, count, U8);
8941 for (i = 0; i < count; i++) {
8942 d->what[i] = ri->data->what[i];
8943 switch (d->what[i]) {
8944 /* legal options are one of: sSfpontTu
8945 see also regcomp.h and pregfree() */
8948 case 'p': /* actually an AV, but the dup function is identical. */
8949 case 'u': /* actually an HV, but the dup function is identical. */
8950 d->data[i] = sv_dup_inc((SV *)ri->data->data[i], param);
8953 /* This is cheating. */
8954 Newx(d->data[i], 1, struct regnode_charclass_class);
8955 StructCopy(ri->data->data[i], d->data[i],
8956 struct regnode_charclass_class);
8957 reti->regstclass = (regnode*)d->data[i];
8960 /* Compiled op trees are readonly and in shared memory,
8961 and can thus be shared without duplication. */
8963 d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
8967 /* Trie stclasses are readonly and can thus be shared
8968 * without duplication. We free the stclass in pregfree
8969 * when the corresponding reg_ac_data struct is freed.
8971 reti->regstclass= ri->regstclass;
8975 ((reg_trie_data*)ri->data->data[i])->refcount++;
8979 d->data[i] = ri->data->data[i];
8982 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
8991 reti->name_list_idx = ri->name_list_idx;
8993 #ifdef RE_TRACK_PATTERN_OFFSETS
8994 if (ri->u.offsets) {
8995 Newx(reti->u.offsets, 2*len+1, U32);
8996 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
8999 SetProgLen(reti,len);
9005 #endif /* USE_ITHREADS */
9010 converts a regexp embedded in a MAGIC struct to its stringified form,
9011 caching the converted form in the struct and returns the cached
9014 If lp is nonnull then it is used to return the length of the
9017 If flags is nonnull and the returned string contains UTF8 then
9018 (*flags & 1) will be true.
9020 If haseval is nonnull then it is used to return whether the pattern
9023 Normally called via macro:
9025 CALLREG_STRINGIFY(mg,&len,&utf8);
9029 CALLREG_AS_STR(mg,&lp,&flags,&haseval)
9031 See sv_2pv_flags() in sv.c for an example of internal usage.
9034 #ifndef PERL_IN_XSUB_RE
9037 Perl_reg_stringify(pTHX_ MAGIC *mg, STRLEN *lp, U32 *flags, I32 *haseval ) {
9039 const regexp * const re = (regexp *)mg->mg_obj;
9041 *haseval = re->seen_evals;
9043 *flags = ((re->extflags & RXf_UTF8) ? 1 : 0);
9050 - regnext - dig the "next" pointer out of a node
9053 Perl_regnext(pTHX_ register regnode *p)
9056 register I32 offset;
9061 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
9070 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
9073 STRLEN l1 = strlen(pat1);
9074 STRLEN l2 = strlen(pat2);
9077 const char *message;
9083 Copy(pat1, buf, l1 , char);
9084 Copy(pat2, buf + l1, l2 , char);
9085 buf[l1 + l2] = '\n';
9086 buf[l1 + l2 + 1] = '\0';
9088 /* ANSI variant takes additional second argument */
9089 va_start(args, pat2);
9093 msv = vmess(buf, &args);
9095 message = SvPV_const(msv,l1);
9098 Copy(message, buf, l1 , char);
9099 buf[l1-1] = '\0'; /* Overwrite \n */
9100 Perl_croak(aTHX_ "%s", buf);
9103 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
9105 #ifndef PERL_IN_XSUB_RE
9107 Perl_save_re_context(pTHX)
9111 struct re_save_state *state;
9113 SAVEVPTR(PL_curcop);
9114 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
9116 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
9117 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
9118 SSPUSHINT(SAVEt_RE_STATE);
9120 Copy(&PL_reg_state, state, 1, struct re_save_state);
9122 PL_reg_start_tmp = 0;
9123 PL_reg_start_tmpl = 0;
9124 PL_reg_oldsaved = NULL;
9125 PL_reg_oldsavedlen = 0;
9127 PL_reg_leftiter = 0;
9128 PL_reg_poscache = NULL;
9129 PL_reg_poscache_size = 0;
9130 #ifdef PERL_OLD_COPY_ON_WRITE
9134 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
9136 const REGEXP * const rx = PM_GETRE(PL_curpm);
9139 for (i = 1; i <= rx->nparens; i++) {
9140 char digits[TYPE_CHARS(long)];
9141 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
9142 GV *const *const gvp
9143 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
9146 GV * const gv = *gvp;
9147 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
9157 clear_re(pTHX_ void *r)
9160 ReREFCNT_dec((regexp *)r);
9166 S_put_byte(pTHX_ SV *sv, int c)
9168 if (isCNTRL(c) || c == 255 || !isPRINT(c))
9169 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
9170 else if (c == '-' || c == ']' || c == '\\' || c == '^')
9171 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
9173 Perl_sv_catpvf(aTHX_ sv, "%c", c);
9177 #define CLEAR_OPTSTART \
9178 if (optstart) STMT_START { \
9179 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
9183 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
9185 STATIC const regnode *
9186 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
9187 const regnode *last, const regnode *plast,
9188 SV* sv, I32 indent, U32 depth)
9191 register U8 op = PSEUDO; /* Arbitrary non-END op. */
9192 register const regnode *next;
9193 const regnode *optstart= NULL;
9196 GET_RE_DEBUG_FLAGS_DECL;
9198 #ifdef DEBUG_DUMPUNTIL
9199 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
9200 last ? last-start : 0,plast ? plast-start : 0);
9203 if (plast && plast < last)
9206 while (PL_regkind[op] != END && (!last || node < last)) {
9207 /* While that wasn't END last time... */
9210 if (op == CLOSE || op == WHILEM)
9212 next = regnext((regnode *)node);
9215 if (OP(node) == OPTIMIZED) {
9216 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
9223 regprop(r, sv, node);
9224 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
9225 (int)(2*indent + 1), "", SvPVX_const(sv));
9227 if (OP(node) != OPTIMIZED) {
9228 if (next == NULL) /* Next ptr. */
9229 PerlIO_printf(Perl_debug_log, " (0)");
9230 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
9231 PerlIO_printf(Perl_debug_log, " (FAIL)");
9233 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
9234 (void)PerlIO_putc(Perl_debug_log, '\n');
9238 if (PL_regkind[(U8)op] == BRANCHJ) {
9241 register const regnode *nnode = (OP(next) == LONGJMP
9242 ? regnext((regnode *)next)
9244 if (last && nnode > last)
9246 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
9249 else if (PL_regkind[(U8)op] == BRANCH) {
9251 DUMPUNTIL(NEXTOPER(node), next);
9253 else if ( PL_regkind[(U8)op] == TRIE ) {
9254 const regnode *this_trie = node;
9255 const char op = OP(node);
9256 const U32 n = ARG(node);
9257 const reg_ac_data * const ac = op>=AHOCORASICK ?
9258 (reg_ac_data *)ri->data->data[n] :
9260 const reg_trie_data * const trie =
9261 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
9263 AV *const trie_words = (AV *) ri->data->data[n + TRIE_WORDS_OFFSET];
9265 const regnode *nextbranch= NULL;
9267 sv_setpvn(sv, "", 0);
9268 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
9269 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
9271 PerlIO_printf(Perl_debug_log, "%*s%s ",
9272 (int)(2*(indent+3)), "",
9273 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
9274 PL_colors[0], PL_colors[1],
9275 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
9276 PERL_PV_PRETTY_ELIPSES |
9282 U16 dist= trie->jump[word_idx+1];
9283 PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
9284 (UV)((dist ? this_trie + dist : next) - start));
9287 nextbranch= this_trie + trie->jump[0];
9288 DUMPUNTIL(this_trie + dist, nextbranch);
9290 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
9291 nextbranch= regnext((regnode *)nextbranch);
9293 PerlIO_printf(Perl_debug_log, "\n");
9296 if (last && next > last)
9301 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
9302 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
9303 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
9305 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
9307 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
9309 else if ( op == PLUS || op == STAR) {
9310 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
9312 else if (op == ANYOF) {
9313 /* arglen 1 + class block */
9314 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
9315 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
9316 node = NEXTOPER(node);
9318 else if (PL_regkind[(U8)op] == EXACT) {
9319 /* Literal string, where present. */
9320 node += NODE_SZ_STR(node) - 1;
9321 node = NEXTOPER(node);
9324 node = NEXTOPER(node);
9325 node += regarglen[(U8)op];
9327 if (op == CURLYX || op == OPEN)
9331 #ifdef DEBUG_DUMPUNTIL
9332 PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
9337 #endif /* DEBUGGING */
9341 * c-indentation-style: bsd
9343 * indent-tabs-mode: t
9346 * ex: set ts=8 sts=4 sw=4 noet: